示例#1
0
文件: views.py 项目: komaliitm/Patedu
def GenerateReport(month=None, year=None):
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	now_utc = utcnow_aware()
	now = now_utc.astimezone(tz)
	if not month:
		month = now.month
	if not year:
		year = now.year

	f1 = open('MCTSDLPMCS_IMM_SMS_REPORT'+str(month)+', '+str(year), 'w')
	f2 = open('MCTSDLPMCS_ANC_SMS_REPORT'+str(month)+', '+str(year), 'w')
	cds = ContentDelivered.objects.filter(timestamp__year = year, timestamp__month=month, status=0)

	i = 0
	j = 0
	for cd in cds:
		if ANCBenef.objects.filter(id=cd.benefeciary.id).count() > 0:
			f = f2
			i = i + 1
			cnt = i
		elif IMMBenef.objects.filter(id=cd.benefeciary.id).count() > 0:
			f = f1
			j = j+1
			cnt = j
		else:
			continue
		f.write(str(cnt)+". ")
		f.write('MSG: '+cd.msg.encode('utf8'))
		f.write(', NUMBER: '+cd.benefeciary.notify_number)
		f.write(', WHOM: self\n') 
	f1.close()
	f2.close()
示例#2
0
文件: views.py 项目: komaliitm/Patedu
def ProcessSubcenterData(benefs, sub, since_months, reg_type, months):
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz)

	this_month_date = today.replace(hour=6, minute=0, second=0, day=1).astimezone(pytz.utc)

	Overdue = 0
	new_reg = 0
	GivenServices = 0
	DueServices = 0
	OverDueRate = 0
	overdue_services_group = []
	due_srvices_group = []
	given_services_group = []
	if benefs:
		txs_service = Transactions.objects.all().filter(Q(subcenter=sub), Q(beneficiary__in = benefs), Q(timestamp__gte=since_months.date())).exclude(event__val=reg_type)
		txs_reg = Transactions.objects.all().filter(Q(subcenter=sub), Q(event__val=reg_type), Q(timestamp__gte=since_months.date()) )
		dues_service = DueEvents.objects.all().filter(Q(subcenter=sub), Q(beneficiary__in = benefs), Q(date__gte=since_months.date()) ).exclude(Q(event__val__icontains='pentavalent') | Q(event__val__icontains='je') | Q(event__val__icontains='mmr') )

		GivenServices = txs_service.count()
		DueServices = dues_service.count()

		overdues_service = OverDueEvents.objects.all().filter(Q(subcenter=sub), Q(beneficiary__in = benefs), Q(date__gte=since_months.date()) ).exclude(Q(event__val__icontains='pentavalent') | Q(event__val__icontains='je') | Q(event__val__icontains='mmr') )
		overdue_services_group = list(overdues_service.values('event_id').annotate(ods_count=Count('id'), event_name=Max('event__val')))
		given_services_group = list(txs_service.values('event_id').annotate(ods_count=Count('id'), event_name=Max('event__val')))
		due_srvices_group = list(dues_service.values('event_id').annotate(ods_count=Count('id'), event_name=Max('event__val')))
		Overdue = overdues_service.count()
		new_reg = txs_reg.count()
		
		if Overdue > 0:
			#TODO derive sample 
			sample_size = dues_service.count() if dues_service.count() > 0 else txs_service.count()
			sample_size = sample_size if sample_size > 0 else benefs.count()
			sample_size = sample_size if sample_size > 0 else 500

			OverDueRate = (float(Overdue)/(months*sample_size))*100
	
		if dues_service:
			Adherence = txs_service.count() * 100 / dues_service.count()
		else:
			Adherence = None
		
	else:
		Adherence = None

	ProgressData = GetLastSixMonthsProgress(benefs, sub, reg_type)
	return {
			'Overdue':Overdue,
			'DueServices':DueServices,
			'overdue_sg':overdue_services_group,
			'due_sg':due_srvices_group,
			'given_sg':given_services_group,
			'new_reg':new_reg,
			'GivenServices':GivenServices,
			'OverDueRate':OverDueRate,
			'Adherence':Adherence,
			'ProgressData':ProgressData
	}
示例#3
0
文件: views.py 项目: komaliitm/Patedu
def GetLastSixMonthsProgress(benefs, sub, reg_type):
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz)

	ProgressData = [0,0,0,0,0,0]
	this_month_date = today.replace(hour=6, minute=0, second=0, day=1).astimezone(pytz.utc)
	if benefs:
		for month in range(1,6):
			since_date = this_month_date - relativedelta(months=month)

			#TODO: Introduce for new benef registration later
			dues_service = DueEvents.objects.all().filter(Q(subcenter=sub), Q(beneficiary__in = benefs), Q(date__gte=since_date.date()) & Q(date__lt=this_month_date.date()) )
			overdues_service = OverDueEvents.objects.all().filter(Q(subcenter=sub), Q(beneficiary__in = benefs), Q(date__gte=since_date.date()) & Q(date__lt=this_month_date.date()))
			Overdue = overdues_service.count()

			OverDueRate = 0
			if Overdue > 0:
				#TODO derive sample 
				sample_size = dues_service.count() if dues_service.count() > 0 else benefs.count()
				sample_size = sample_size if sample_size > 0 else 500

				OverDueRate = (float(Overdue)/(month*sample_size))*100

			ProgressData[6-month] = OverDueRate
			this_month_date = since_date
	return ProgressData
示例#4
0
文件: views.py 项目: komaliitm/Patedu
def ODSANMANC(request):
	if request.method == 'GET':
		anm_id = request.GET.get('CustomField')
		if not anm_id:
			return HttpResponseBadRequest('ANM ID is not provided')
		try:
			anm = CareProvider.objects.get(id=int(anm_id))
		except:
			return HttpResponseBadRequest('ANM does not exist')

		timezone = 'Asia/Kolkata'
		tz = pytz.timezone(timezone)
		today = utcnow_aware().replace(tzinfo=tz)
		date_then = today.replace(hour=12, minute=0, day=1, second=0).date()
		
		#All ANC overdue services for given ANM
		from django.db.models import Count
		anc_benefs = ANCBenef.objects.filter(careprovider=anm)
		anc_ods = OverDueEvents.objects.filter(beneficiary__in=anc_benefs).values('event').annotate(count=Count('event'))

		anm_stats_anc = ''
		for anc_od in anc_ods:
			if anm_stats_anc:
				anm_stats_anc +='. '
			event = Events.objects.get(id=anc_od.get('event'))
			event_count = anc_od.get('count')
			anm_stats_anc += event.val+' '+str(event_count)+' Overdue!'
		return HttpResponse(anm_stats_anc, content_type='text/plain')
	else:
		return HttpResponseBadRequest('HTTP method type not allowed')
示例#5
0
文件: views.py 项目: komaliitm/Patedu
def generate_schedule(benef_id):
	ret = {"status":0,
	"msg":""}

	try:
		vaccine_benef = VaccinationBeneficiary.objects.get(BeneficiaryId=benef_id)
	except ObjectDoesNotExist:
		ret["status"] = 1
		ret["msg"] = "Vaccination Beneficiary ID is not correct"
		return ret

	if vaccine_benef.isScheduleGenerated:
		ret["status"] = 1
		ret["msg"] = "for given beneficiary the schedule is already generated"
		return ret

	#Generate schedule here
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz).date()

	dob = vaccine_benef.Dob
	delta_dob = today - dob
	today_weeks = delta_dob.days/7

	#TODO: Accomodate richness in model itself
	richness = [
		{'stage':'1M', 'days':30},
		{'stage':'1W', 'days':7},
		{'stage':'1D', 'days':1},
		{'stage':'AW1', 'days':15},
		{'stage':'AW2', 'days':4}
	]

	#find all vaccines greater than today_weeks
	vaccines = Vaccinations.objects.filter(AgeInWeeks__gte=today_weeks)
	for vaccine in vaccines:
		vaccine_eta = dob + timedelta(days=vaccine.AgeInWeeks*7)
		
		#Generate the reminders for future based on richness level
		for level in richness:
			rem_eta = vaccine_eta - timedelta(days=level['days'])
			if rem_eta >= today:
				try:
					rem_template = VaccineReminderTemplate.objects.get(Vaccine=vaccine, stage=level['stage'], Language=vaccine_benef.Language)
					vac_rem = VaccineReminder(vaccine_reference=rem_template, vaccination_beneficiary= vaccine_benef, dueDate= rem_eta, vaccDate=vaccine_eta)
					vac_rem.save()
				except ObjectDoesNotExist:
					print 'Error: Template missing for the vaccine: '+vaccine.vaccineId+' '+level['stage']+' '+vaccine_benef.Language
			else:
				#TODO: Account for recently missed vaccinations
				continue
示例#6
0
文件: views.py 项目: komaliitm/Patedu
def send_reminders():
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz)
	print 'Executing send_reminders scheduled function'
	today_date = today.date()

	reminders = VaccineReminder.objects.filter( Q(state=2)|Q(state=1), Q(dueDate__lte=today_date))

	for reminder in reminders:
		language = reminder.vaccine_reference.Language
		vaccine_name = reminder.vaccine_reference.Vaccine.VaccineName
		benef_name = reminder.vaccination_beneficiary.ChildName
		benef_number = reminder.vaccination_beneficiary.NotifyNumber
		gaurdian_name = reminder.vaccination_beneficiary.Gaurdian_name
		hw = reminder.vaccination_beneficiary.health_worker
		if hw and hw.first_name:
			hw_name = hw.first_name+' '+hw.last_name
		else:
			hw_name = ''
		vacc_date = '{0.month}/{0.day}/{0.year}'.format(reminder.vaccDate)

		#TODO: Accomodate for IVR, and email later
		sms_id = reminder.vaccine_reference.sms_message
		sms_temp = ''
		try:
			sms_temp = SMSMessages.objects.get(msg_identifier=sms_id).msg
		except ObjectDoesNotExist:
			print 'ERROR: SMS msg not found for the id: '+sms_id
			continue
		sms_temp = sms_temp.replace(u'childName', unicode(benef_name))
		sms_temp = sms_temp.replace(u'vaccineName', unicode(vaccine_name))
		sms_temp = sms_temp.replace(u'date', unicode(vacc_date))
		sms_temp = sms_temp.replace(u'hwName', unicode(hw_name))
		sms_msg = sms_temp
		#sms_msg_hexlified = binascii.hexlify(sms_msg.encode('utf-8'))
		sms_msg_hexlified = toHex(sms_msg)
		#send sms
		print 'sending sms'
		sent_code = SendSMSUnicode(recNum=benef_number, msgtxt=sms_msg_hexlified)

		if 'Status=1' in sent_code:
			reminder.state = 1
			reminder.errorCode = sent_code
			reminder.save()
		elif 'Status=0' in sent_code:
			reminder.state = 0
			reminder.save()
示例#7
0
文件: views.py 项目: komaliitm/Patedu
def RestBeneficiary(request, id):
	try:
		vaccine_benef = VaccinationBeneficiary.objects.get(BeneficiaryId=id)
	except ObjectDoesNotExist:
		return HttpResponseBadRequest('Vaccination Beneficiary ID is not correct')

	if request.method == 'GET':
		return HttpResponse(json.dumps(vaccine_benef.json()), mimetype="application/json")
	elif request.method == 'POST':
		req = request.POST
		name = req.get('name')
		notif_num = req.get('notif_num')
		dob = req.get('dob')
		sex = req.get('sex')
		gaurdian_name = req.get('gaurdian_name')
		language = req.get('language')
		hw_num = req.get('hw_num')
		is_verified = req.get('is_verified')
		
		if name is not None: vaccine_benef.ChildName = name
		if dob is not None:
			dob = dateutil.parser.parse(dob).date()
			vaccine_benef.Dob = dob
		if notif_num is not None: vaccine_benef.NotifyNumber = notif_num
		if sex is not None: vaccine_benef.Sex = sex
		if gaurdian_name is not None: vaccine_benef.Gaurdian_name = gaurdian_name
		if language is not None: vaccine_benef.Language = language
		if is_verified is not None: vaccine_benef.isVerified = is_verified

		if hw_num is not None:
			hw = None
			try:
				hw = HealthWorker.objects.get(phone=hw_num)
			except ObjectDoesNotExist:
				hw = HealthWorker(phone=hw_num, username=hw_num, password= "******")
				hw.save()
			vaccine_benef.health_worker = hw
		
		vaccine_benef.ModifiedOn = utcnow_aware()

		vaccine_benef.save()
		return HttpResponse( json.dumps(vaccine_benef.json()), mimetype="application/json")
	elif request.method == 'DELETE':
		vaccine_benef.delete()
		return HttpResponse("Beneficiary deleted")
	return HttpResponseBadRequest('Unknown http request type') 
示例#8
0
文件: views.py 项目: komaliitm/Patedu
def GenerateWorkplan(subcenter, report_type, since_months):
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today = utcnow_aware().replace(tzinfo=tz)
	date_this = today.replace(hour=12, minute=0, day=1, second=0).date()
	date_then = date_this - relativedelta(months=(since_months-1))

	benefs = report_type.objects.filter(subcenter = subcenter, odue_events__date__gte=date_then).distinct() | report_type.objects.filter(subcenter = subcenter, due_events__date__gte=date_then).distinct()
	workplan = [benef.json(date_then) for benef in benefs]
	data = {
		'workplan':workplan,
		'subcenter':subcenter.json(),
		'since_months':since_months,
		'date_then':date_then.isoformat(),
		'date_this':date_then.isoformat(),
		'area':report_type.TYPE
	}
	return data
示例#9
0
文件: tasks.py 项目: komaliitm/Patedu
def ReceiveSMSToday():
	url = settings.SMSPROVIDERRECEIVE_URL
	userSmsProvider = settings.SMSPROVIDER_USER
	passSmsProvider = settings.SMSPROVIDER_PASS
	senderId = str(settings.SMSREPLYNUMBER)

	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz)
	today_date = today.date()
	sdtime = today_date.isoformat()+' 00:00:00'
	edtime = today_date.isoformat()+' 23:59:59'

	GET_str = '?'+'user='******':'+passSmsProvider+'&'+'senderID='+senderId+'&'+'sdtime='+sdtime+'&'+'edtime='+edtime
	GET_url = url+GET_str
	print GET_url
	r = requests.get(GET_url)
	return r.text
示例#10
0
文件: views.py 项目: komaliitm/Patedu
def ExotelUpdateCallStatus(request):
	if request.method == 'POST':
		sid = request.POST['CallSid']
		status = request.POST['Status']
		recording_url = request.POST.get('RecordingUrl')
		date_updated = request.POST.get('DateUpdated')
		try:
			marker = ExotelCallStatus.objects.get(sid=sid)
			marker.status = status
			marker.recording_url = recording_url
			marker.dt_updated = utcnow_aware().date()
			marker.exotel_update_received = True
			marker.save()
		except:
			marker = ExotelCallStatus.objects.create(sid=sid, status=status, recording_url=recording_url, date_initiated = utcnow_aware().date(), dt_updated = utcnow_aware(), exotel_update_received = True)	 
		
		return HttpResponse('Success')
	else:
		return HttpResponseBadRequest('Http method not supported')
示例#11
0
文件: tasks.py 项目: komaliitm/Patedu
def ReceiveSMSSinceLast():
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	now_utc = utcnow_aware()
	now = now_utc.astimezone(tz)
	now_date = now.date()

	rets = LastRetrieveTime.objects.filter(status=0)
	if rets: 
		rets = rets.order_by('-last_ret')
		last_ret_utc = rets[0].last_ret
		last_ret = last_ret_utc.astimezone(tz)
		last_ret = last_ret + timedelta(seconds=1)
		sdtime = last_ret.strftime('%Y-%m-%d %H:%M:%S')
	else:
		sdtime = now_date.isoformat()+' 00:00:00'

	edtime = now.strftime('%Y-%m-%d %H:%M:%S')
	print 'sdtime: '+sdtime
	print 'edtime: '+edtime

	url = settings.SMSPROVIDERRECEIVE_URL
	userSmsProvider = settings.SMSPROVIDER_USER
	passSmsProvider = settings.SMSPROVIDER_PASS
	senderId = str(settings.SMSREPLYNUMBER)

	GET_str = '?'+'user='******':'+passSmsProvider+'&'+'senderID='+senderId+'&'+'sdtime='+sdtime+'&'+'edtime='+edtime
	GET_url = url+GET_str
	print GET_url
	r = requests.get(GET_url)
	lrt = LastRetrieveTime(last_ret=now_utc)
	print r.text
	if 'Status=0' in r.text:
		lrt.status = 0
	else:
		lrt.status = 1
	lrt.save()
	return r.text
示例#12
0
文件: views.py 项目: komaliitm/Patedu
def SaveIMMBeneficiary(benef, subcenter, date_then):
    address = benef.get("address")
    phone_no_of_whom = benef.get("phone_no_of_whom")
    year_of_reg_child_id = benef.get("year_of_reg_child_id")
    asha_phone_name = benef.get("ASHA (Phone No.)")
    anm_phone_name = benef.get("HealthProvider (Phone No.)")
    mother_name_mother_id = benef.get("mother_name_mother_id")
    birthdate = benef.get("birthdate")
    overDue_services = benef.get("overDue_services")
    given_services = benef.get("given_services")
    due_services = benef.get("due_services")
    child_name_sex = benef.get("child_name_sex")
    
    #parse mother_name_mother_id
    mother_name = None
    mother_mcts_id = None
    if mother_name_mother_id:
        mother_name_mother_id = mother_name_mother_id.replace("\n","").lower()

        _regSearch = re.search('(\d+)', mother_name_mother_id)
        if _regSearch:
            mother_mcts_id = _regSearch.group(0)

        _regSearch = re.search('([a-z/ ]+)', mother_name_mother_id)
        if _regSearch:
            mother_name = _regSearch.group(0).strip()

    #parse child_name_sex
    child_name = None
    child_sex = None
    if child_name_sex:
        child_name_sex = child_name_sex.replace("\n","").lower()
        child_details = child_name_sex.split("(")

        _regSearch = re.search('([a-z ]+)', child_details[0])
        if _regSearch:
            child_name = _regSearch.group(0).strip()

        if len(child_details) > 1:
            _regSearch = re.search('([a-z]+$)', child_details[1])
            if _regSearch:
                child_sex = _regSearch.group(0).strip()
    
    #parse overdue services
    od_services = []
    if overDue_services:
        overDue_services = overDue_services.replace("\n","").lower()
        od_services = overDue_services.split(",")

    gn_services = []
    if given_services:
        given_services = given_services.replace("\n","").lower()
        gn_services = given_services.split(",")

    d_services = []
    if due_services:
        due_services = due_services.replace("\n", "").lower()
        d_services = due_services.split(",")

    #parse lmp_date
    if birthdate:
        birthdate = datetime.datetime.strptime(birthdate, "%d/%m/%Y").date()
    else:
        birthdate = None

    #parse village
    vill_name = None
    vill_mcts_id = None
    vill_value = None
    if address:
        address = address.replace("\n", "").lower()
        vill_value = address
        _regSearch = re.search('([a-z ]+)', address)
        if _regSearch:
            vill_name = _regSearch.group(0).strip()
        
        _regSearch = re.search('(\d+)', address)
        if _regSearch:
            vill_mcts_id = _regSearch.group(0)
    
    #parse phone
    phone = None
    phone_type = None
    if phone_no_of_whom:
        raw_phone = phone_no_of_whom.replace("\n","").lower()

        _regSearch = re.search('(\d+)', raw_phone)
        if _regSearch:
            phone = _regSearch.group(0)

        _regSearch = re.search('([a-z]+)', raw_phone)
        if _regSearch:
            phone_type_str = _regSearch.group(0).lower()
            phone_type = Beneficiary.NUMBER_TYPE_MAP.get(phone_type_str)
            if phone_type is None:
                phone_type = 0

    #parse mother mcts id
    child_mcts_id = None
    if year_of_reg_child_id:
        child_mcts_id = year_of_reg_child_id.replace(" ","").replace("\n","").replace("(","").replace(")","_").replace("-","_")
        if '_' in child_mcts_id:
            child_mcts_id = child_mcts_id.split('_')[2]

    #parse ASHA phone, name
    asha_name = None
    asha_phone = ''
    if asha_phone_name:
        asha_phone_name = asha_phone_name.replace("\n","").lower()

        _regSearch = re.search('(\d+)', asha_phone_name)
        if _regSearch:
            asha_phone = _regSearch.group(0)

        _regSearch = re.search('([a-z ]+)', asha_phone_name)
        if _regSearch:
            asha_name = _regSearch.group(0).strip().lower()

    #parse anm phone, name
    anm_name = None
    anm_phone = ''
    if anm_phone_name:
        anm_phone_name = anm_phone_name.replace("\n","").lower()

        _regSearch = re.search('(\d+)', anm_phone_name)
        if _regSearch:
            anm_phone = _regSearch.group(0)

        _regSearch = re.search('([a-z ]+)', anm_phone_name)
        if _regSearch:
            anm_name = _regSearch.group(0).strip().lower()

    #check and create address
    addrs = None
    if vill_mcts_id is not None:
        addrs = Address.objects.filter(village_mcts_id=vill_mcts_id)
    if not addrs and vill_value is not None:
        addrs = Address.objects.filter(value=vill_value)
    if addrs:
        village = addrs[0]
    else: 
        try:
            village = Address.objects.create(value=vill_value, village=vill_name, village_mcts_id = vill_mcts_id)
        except:
            village = None

    #check and create care giver
    if asha_name:
        cgs = CareGiver.objects.filter(designation='ASHA', phone=asha_phone)
        if cgs.count() > 0:
            cg = cgs[0]
            if cg.first_name != asha_name:
                cg.first_name = asha_name
                cg.save()
        else:
            username = asha_name+"_"+asha_phone+"_ASHA"
            username = username[0:29]
            cg = CareGiver.objects.create(first_name=asha_name, designation='ASHA', phone=asha_phone, address=village, username=username)
    else:
        cg = None

    #check and create care provider
    if anm_name:
        cps = CareProvider.objects.filter(designation='ANM', phone=anm_phone)
        if cps.count() > 0:
            cp = cps[0]
            if cp.first_name != anm_name:
                cp.first_name = anm_name
                cp.save()
        else:
            username = anm_name +"_"+anm_phone+"_ANM"
            username = username[0:29]
            cp = CareProvider.objects.create(first_name=anm_name, designation='ANM', phone=anm_phone, username=username)
    else:
        cp = None

    #check and create IMM benefeciary
    imm_benefs = IMMBenef.objects.filter(MCTS_ID = child_mcts_id)
    if imm_benefs.count() > 0:
        imm_benef = imm_benefs[0]
        print 'Beneficiary Exists'
    else:
        username = child_mcts_id+"_"+child_name
        username = username[0:29]
        imm_benef = IMMBenef.objects.create(dob = birthdate, child_name=child_name, child_sex=child_sex, \
        mother_name=mother_name, mother_mcts_id= mother_mcts_id, active=True, MCTS_ID=child_mcts_id, \
        notify_number=phone, notify_number_type= phone_type, address=village, \
        createdon=utcnow_aware(), modifiedon=utcnow_aware(), subcenter=subcenter, \
        first_name=child_name, caregiver=cg, careprovider=cp, username=username)
        #create beneficiary registration transaction
        events = Events.objects.filter(val=Events.IMM_REG_VAL)
        if events.count() > 0:
            event = events[0]
        else:
            event = Events.objects.create(val=Events.IMM_REG_VAL)
        
        try:
            Transactions.objects.create(event=event, subcenter=subcenter, beneficiary= imm_benef, timestamp=date_then)
        except:
            print "Tried to create imm_reg Transactions without benefeciary"


    #check and create events
    for service in d_services + od_services + gn_services:
        service = service.strip()
        scs = Events.objects.filter(val=service)
        if scs.count() == 0:
            event = Events.objects.create(val=service)

    #create DueEvents
    for service in d_services:
        service = service.strip()
        event = Events.objects.get(val=service)
        des = DueEvents.objects.all().filter(event=event, subcenter=subcenter, beneficiary=imm_benef, date__month=date_then.month, date__year=date_then.year)
        if des:
            print 'Due service already exists'
            continue
        try:
            DueEvents.objects.create(event=event, subcenter=subcenter, beneficiary= imm_benef, date=date_then)
        except:
            print "Tried to create DueEvents without benefeciary"
    #create over due events
    for service in od_services:
        service = service.strip()
        event = Events.objects.get(val=service)
        odes = OverDueEvents.objects.all().filter(event=event, subcenter=subcenter, beneficiary=imm_benef, date__month=date_then.month, date__year=date_then.year)
        if odes:
            print 'OverDue service already exists'
            continue
        try:
            OverDueEvents.objects.create(event=event, subcenter=subcenter, beneficiary= imm_benef, date=date_then)
        except:
            print "Tried to create OverDueEvents without benefeciary"
    #check and create Transactions
    for service in gn_services:
        service = service.strip()
        event = Events.objects.get(val=service)
        dt_then = datetime.datetime.combine(date_then, datetime.datetime.min.time())  + datetime.timedelta(days=1)
        dt_cutoff = utcnow_aware() - datetime.timedelta(days=IMMBenef.IMM_SPAN)
        txs = Transactions.objects.filter(beneficiary=imm_benef, event=event, timestamp__gt = dt_cutoff)
        if txs.count() > 0:
            print 'Transaction service already exists'
            continue
        try:
            Transactions.objects.create(event=event, subcenter=subcenter, beneficiary= imm_benef, timestamp=date_then)
        except:
            print "Tried to create Transactions without benefeciary"
示例#13
0
文件: views.py 项目: komaliitm/Patedu
def SaveANCBeneficiary(benef, subcenter, date_then):
    print "In ANC Parser"
    expected_delivery_date = benef.get("expected_delivery_date")
    address = benef.get("address")
    phone_no_of_whom = benef.get("phone_no_of_whom")
    year_of_reg_mother_id = benef.get("year_of_reg_mother_id")
    asha_phone_name = benef.get("ASHA (Phone No.)")
    anm_phone_name = benef.get("ANM (Phone No.)")
    mother_name_husband_name = benef.get("mother_name_husband_name")
    lmp_date = benef.get("lmp_date")
    overDue_services = benef.get("overDue_services")
    given_services = benef.get("given_services")
    due_services = benef.get("due_services")
    
    #parse overdue services
    od_services = []
    if overDue_services:
        overDue_services = overDue_services.replace("\n","").lower()
        od_services = overDue_services.split(",")

    gn_services = []
    if given_services:
        given_services = given_services.replace("\n","").lower()
        gn_services = given_services.split(",")

    d_services = []
    if due_services:
        due_services = due_services.replace("\n", "").lower()
        d_services = due_services.split(",")

    #parse lmp_date
    if lmp_date:
        lmp_date = datetime.datetime.strptime(lmp_date, "%d/%m/%Y").date()
    else:
        lmp_date = None

    #parse mother name husband name
    mother_name  = None
    husband_name = None
    if mother_name_husband_name:
        couple = mother_name_husband_name.lower().replace('\n', '').split('w/o')
        
        _regSearch = re.search('[a-z ]+', couple[0])
        if _regSearch:
            mother_name = _regSearch.group(0).strip()

        if len(couple) > 1:
            _regSearch = re.search('[a-z ]+', couple[1])
            if _regSearch:
                husband_name = _regSearch.group(0).strip()

    #parse expected delivery date
    edd = None
    if expected_delivery_date:
        edd = datetime.datetime.strptime(expected_delivery_date, "%d/%m/%Y").date()
    
    #parse village
    vill_name = None
    vill_mcts_id = None
    vill_value = None
    if address:
        address = address.replace("\n", "").lower()
        vill_value = address
        _regSearch = re.search('([a-z ]+)', address)
        if _regSearch:
            vill_name = _regSearch.group(0).strip()
        
        _regSearch = re.search('(\d+)', address)
        if _regSearch:
            vill_mcts_id = _regSearch.group(0)
    
    #parse phone
    phone = None
    phone_type = None
    if phone_no_of_whom:
        raw_phone = phone_no_of_whom.replace("\n","").lower()

        _regSearch = re.search('(\d+)', raw_phone)
        if _regSearch:
            phone = _regSearch.group(0)

        _regSearch = re.search('([a-z]+)', raw_phone)
        if _regSearch:
            phone_type_str = _regSearch.group(0).lower()
            phone_type = Beneficiary.NUMBER_TYPE_MAP.get(phone_type_str)
            if phone_type is None:
                phone_type = 0

    #parse mother mcts id
    mother_mcts_id = None
    if year_of_reg_mother_id:
        mother_mcts_id = year_of_reg_mother_id.replace(" ","").replace("\n","").replace("(","").replace(")","_").replace("-","_")
        if '_' in mother_mcts_id:
            mother_mcts_id = mother_mcts_id.split('_')[2]
    #parse ASHA phone, name
    asha_name = None
    asha_phone = ''
    if asha_phone_name:
        asha_phone_name = asha_phone_name.replace("\n","").lower()

        _regSearch = re.search('(\d+)', asha_phone_name)
        if _regSearch:
            asha_phone = _regSearch.group(0)

        _regSearch = re.search('([a-z ]+)', asha_phone_name)
        if _regSearch:
            asha_name = _regSearch.group(0).strip().lower()

    #parse anm phone, name
    anm_name = None
    anm_phone = ''
    if anm_phone_name:
        anm_phone_name = anm_phone_name.replace("\n","").lower()

        _regSearch = re.search('(\d+)', anm_phone_name)
        if _regSearch:
            anm_phone = _regSearch.group(0)

        _regSearch = re.search('([a-z ]+)', anm_phone_name)
        if _regSearch:
            anm_name = _regSearch.group(0).strip().lower()

    #check and create address
    addrs = None
    if vill_mcts_id is not None:
        addrs = Address.objects.filter(village_mcts_id=vill_mcts_id)
    if not addrs and vill_value is not None:
        addrs = Address.objects.filter(value=vill_value)
    if addrs:
        village = addrs[0]
    else: 
        try:
            village = Address.objects.create(value=vill_value, village=vill_name, village_mcts_id = vill_mcts_id)
        except:
            village = None

    #check and create care giver
    if asha_name:        
        username = asha_name+"_"+asha_phone+"_ASHA"
        username = username[0:29]
        cgs = CareGiver.objects.filter(designation='ASHA', phone=asha_phone)
        if cgs.count() > 0:
            cg = cgs[0]
            if asha_name != cg.first_name:
                cg.first_name = asha_name
                cg.save() 
        else:
            cg = CareGiver.objects.create(first_name=asha_name, designation='ASHA', phone=asha_phone, address=village, username=username)
    else:
        cg = None

    #check and create care provider
    if anm_name:
        cps = CareProvider.objects.filter(designation='ANM', phone=anm_phone)
        if cps.count() > 0:
            cp = cps[0]
            if anm_name != cp.first_name:
                cp.first_name = anm_name
                cp.save()
        else:
            username = anm_name +"_"+anm_phone+"_ANM"
            username = username[0:29]
            cp = CareProvider.objects.create(first_name=anm_name, designation='ANM', phone=anm_phone, username=username)
    else:
        cp = None


    #check and create ANC benefeciary
    anc_benefs = ANCBenef.objects.filter(MCTS_ID = mother_mcts_id)
    if anc_benefs.count() > 0:
        anc_benef = anc_benefs[0]
        print 'benefeciary exists'
    else:
        username = mother_mcts_id+"_"+mother_name
        username = username[0:29]
        anc_benef = ANCBenef.objects.create(LMP= lmp_date, EDD= edd, husband= husband_name, \
        active=True, MCTS_ID=mother_mcts_id, \
        notify_number=phone, notify_number_type= phone_type, address=village, \
        createdon=utcnow_aware(), modifiedon=utcnow_aware(), subcenter=subcenter, \
        first_name=mother_name, caregiver=cg, careprovider=cp, username=username)
        #create beneficiary registration transaction
        events = Events.objects.filter(val=Events.ANC_REG_VAL)
        if events.count() > 0:
            event = events[0]
        else:
            event = Events.objects.create(val=Events.ANC_REG_VAL)
        
        try:
            Transactions.objects.create(event=event, subcenter=subcenter, beneficiary= anc_benef, timestamp=date_then)
        except:
            print "Tried to create anc_reg Transactions without benefeciary"


    #check and create events
    for service in d_services + od_services + gn_services:
        service = service.strip()
        scs = Events.objects.filter(val=service)
        if scs.count() == 0:
            event = Events.objects.create(val=service)

    #create DueEvents
    for service in d_services:
        service = service.strip()
        event = Events.objects.get(val=service)
        des = DueEvents.objects.all().filter(event=event, subcenter=subcenter, beneficiary=anc_benef, date__month=date_then.month, date__year=date_then.year)
        if des:
            print 'DueEvent exists'
            continue
        try:
            DueEvents.objects.create(event=event, subcenter=subcenter, beneficiary= anc_benef, date=date_then)
        except:
            print "Tried to create DueEvents without benefeciary"
    #create over due events
    for service in od_services:
        service = service.strip()
        event = Events.objects.get(val=service)
        odes = OverDueEvents.objects.all().filter(event=event, subcenter=subcenter, beneficiary=anc_benef, date__month=date_then.month, date__year=date_then.year)
        if odes:
            print 'Overdue event exists'
            continue
        try:
            OverDueEvents.objects.create(event=event, subcenter=subcenter, beneficiary= anc_benef, date=date_then)
        except:
            print "Tried to create OverDueEvents without benefeciary"
    #check and create Transactions
    for service in gn_services:
        service = service.strip()
        event = Events.objects.get(val=service)
        dt_then = datetime.datetime.combine(date_then, datetime.datetime.min.time()) +  datetime.timedelta(days=1)
        dt_cutoff = utcnow_aware() - datetime.timedelta(days=ANCBenef.ANC_SPAN)
        txs = Transactions.objects.filter(beneficiary=anc_benef, event=event, timestamp__gt = dt_cutoff)
        if txs.count() > 0:
            print 'Transaction exists'
            continue
        try:
            Transactions.objects.create(event=event, subcenter=subcenter, beneficiary= anc_benef, timestamp=date_then)
        except:
            print "Tried to create Transactions without benefeciary"
示例#14
0
文件: views.py 项目: komaliitm/Patedu
def mother_name_husband_name(benef, subcenter):
    expected_delivery_date = benef.get("expected_delivery_date")
    address = benef.get("address")
    phone_no_of_whom = benef.get("phone_no_of_whom")
    year_of_reg_mother_id = benef.get("year_of_reg_mother_id")
    delivery_date = benef.get("delivery_date")
    pnc_complications = benef.get("PNC Complication")
    asha_phone_name = benef.get("ASHA (Phone No.)")
    anm_phone_name = benef.get("ANM (Phone No.)")
    mother_name_husband_name = benef.get("mother_name_husband_name")
    lmp_date = benef.get("lmp_date")
    place_of_delivery = benef.get("place_of_delivery")
    delivery_type = benef.get("delivery_type")

    #parse lmp_date
    if lmp_date:
        lmp_date = datetime.datetime.strptime(lmp_date, "%d/%m/%Y").date()
    else:
        lmp_date = None

    #parse place_of_delivery
    if not place_of_delivery:
        place_of_delivery = None

    #parse delivery_type
    if not delivery_type:
        delivery_type = None

    #parse mother name husband name
    mother_name  = None
    husband_name = None
    if mother_name_husband_name:
        couple = mother_name_husband_name.lower().replace('\n', '').split('w/o')
        
        _regSearch = re.search('[a-z ]+', couple[0])
        if _regSearch:
            mother_name = _regSearch.group(0).strip()

        if len(couple) > 1:
            _regSearch = re.search('[a-z ]+', couple[1])
            if _regSearch:
                husband_name = _regSearch.group(0).strip()


    #parse delivery date
    edd = None
    if expected_delivery_date:
        edd = datetime.datetime.strptime(expected_delivery_date, "%d/%m/%Y").date()
    
    #parse village
    vill_name = None
    vill_mcts_id = None
    vill_value = None
    if address:
        address = address.replace("\n", "").lower()
        vill_value = address
        _regSearch = re.search('([a-z ]+)', address)
        if _regSearch:
            vill_name = _regSearch.group(0).strip()
        
        _regSearch = re.search('(\d+)', address)
        if _regSearch:
            vill_mcts_id = _regSearch.group(0)
    
    phone = None
    phone_type = None
    if phone_no_of_whom:
        raw_phone = phone_no_of_whom.replace("\n","").lower()

        _regSearch = re.search('(\d+)', raw_phone)
        if _regSearch:
            phone = _regSearch.group(0)

        _regSearch = re.search('([a-z]+)', raw_phone)
        if _regSearch:
            phone_type_str = _regSearch.group(0).lower()
            phone_type = Beneficiary.NUMBER_TYPE_MAP.get(phone_type_str)
            if phone_type is None:
                phone_type = 0

    #parse mother mcts id
    mother_mcts_id = None
    if year_of_reg_mother_id:
        mother_mcts_id = year_of_reg_mother_id.replace(" ","").replace("\n","").replace("(","").replace(")","_").replace("-","_")
        if '_' in mother_mcts_id:
            mother_mcts_id = mother_mcts_id.split('_')[2]
    #parse delivery date
    dd = None
    if delivery_date:
        dd = datetime.datetime.strptime(delivery_date, "%d/%m/%Y").date()

    #parse pnc_complications
    if not pnc_complications:
        pnc_complications = None

    #parse ASHA phone, name
    asha_name = None
    asha_phone = None
    if asha_phone_name:
        asha_phone_name = asha_phone_name.replace("\n","").lower()

        _regSearch = re.search('(\d+)', asha_phone_name)
        if _regSearch:
            asha_phone = _regSearch.group(0)

        _regSearch = re.search('([a-z ]+)', asha_phone_name)
        if _regSearch:
            asha_name = _regSearch.group(0).strip().lower()

    #parse anm phone, name
    anm_name = None
    anm_phone = None
    if anm_phone_name:
        anm_phone_name = anm_phone_name.replace("\n","").lower()

        _regSearch = re.search('(\d+)', anm_phone_name)
        if _regSearch:
            anm_phone = _regSearch.group(0)

        _regSearch = re.search('([a-z ]+)', anm_phone_name)
        if _regSearch:
            anm_name = _regSearch.group(0).strip().lower()

    #check and create address
    addrs = None
    if vill_mcts_id is not None:
        addrs = Address.objects.filter(village_mcts_id=vill_mcts_id)
    if not addrs and vill_value is not None:
        addrs = Address.objects.filter(value=vill_value)
    if addrs:
        village = addrs[0]
    else: 
        try:
            village = Address.objects.create(value=vill_value, village=vill_name, village_mcts_id = vill_mcts_id)
        except:
            village = None

    #check and create care giver
    if asha_name:
        cgs = CareGiver.objects.filter(designation='ASHA', phone=asha_phone)
        if cgs.count() > 0:
            cg = cgs[0]
            if cg.first_name != asha_name:
                cg.first_name = asha_name
                cg.save()
        else:
            username = asha_name+"_"+asha_phone+"_ASHA"
            username = username[0:29]
            cg = CareGiver.objects.create(first_name=asha_name, designation='ASHA', phone=asha_phone, address=village, username=username)
    else:
        cg = None

    #check and create care provider
    if anm_name:
        cps = CareProvider.objects.filter(designation='ANM', phone=anm_phone)
        if cps.count() > 0:
            cp = cps[0]
            if cp.first_name != anm_name:
                cp.first_name = anm_name
                cp.save()
        else:
            username = anm_name +"_"+anm_phone+"_ANM"
            username = username[0:29]
            cp = CareProvider.objects.create(first_name=anm_name, designation='ANM', phone=anm_phone, username=username)
    else:
        cp = None


    #check and create PNC benefeciary
    pnc_benefs = PNCBenef.objects.filter(MCTS_ID = mother_mcts_id)
    if pnc_benefs.count() > 0:
        pnc_benef = pnc_benefs[0]
    else:
        username = mother_mcts_id+"_"+mother_name
        pnc_benef = PNCBenef.objects.create(LMP= lmp_date, EDD= edd, husband= husband_name, ADD = dd, \
        delivery_place = place_of_delivery, delivery_type=delivery_type, \
        complications=pnc_complications, active=True, MCTS_ID=mother_mcts_id, \
        notify_number=phone, notify_number_type= phone_type, address=village, \
        createdon=utcnow_aware(), modifiedon=utcnow_aware(), subcenter=subcenter, \
        first_name=mother_name, caregiver=cg, careprovider=cp, username=username)
示例#15
0
文件: views.py 项目: komaliitm/Patedu
def SendSchSMS(role=StaticData.SCHEDULE_MSG, job=StaticData.SENDER, reach = StaticData.REACHONLYSELF, month=None, year=None):
	#TODO pick timezone from DB
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	now_utc = utcnow_aware()
	now = now_utc.astimezone(tz)
	if not month:
		month = now.month
	if not year:
		year = now.year

	#if category == StaticData.SCHEDULE_MSG:
	sms_template = u"prelude name की event category इस महीने होनी आवश्यक है. अविलंब आशा बहनजी asha से संपर्क करे. धन्यवाद!"
	
	_allBenefs = Beneficiary.objects.all()
	i=0
	f = open('SMSsendLog', 'w')
	for benef in _allBenefs:
		
		cds = ContentDelivered.objects.filter(benefeciary=benef)
		if cds.count() > 0:
			print 'already sent'
			continue

		if not benef.notify_number or benef.notify_number_type != Beneficiary.NUMBER_TYPE.SELF:
			continue
		benef_number = benef.notify_number
		if len(benef_number) == 11:
			benef_number = benef_number[1:len(benef_number)]
		if int(benef_number) == 0:
			continue

		# #Find all due and unhandled services this month.
		_allDueCurrentMonth = DueEvents.objects.filter(date__year = year, date__month = month, beneficiary= benef)
		event = None
		_numEvents = 0
		for _dueService in _allDueCurrentMonth:
			if not event:
				event = _dueService.event.val
			else:
				event = event +', '+_dueService.event.val
				_numEvents = _numEvents + 1
		if not event:
			continue

		if len(event) > 10:
			event = unicode(event[0:10]) + u" आदि" +unicode(" ("+str(_numEvents)+")")
		else: 
			event = unicode(event)

		if ANCBenef.objects.filter(id=benef.id).count() > 0:
			prelude = u"श्रीमती"
			category = u"जाँच/टीकाकरण"
		elif IMMBenef.objects.filter(id=benef.id).count() > 0:
			prelude = u"बच्चे"
			category = u"टीकाकरण"

		name = unicode(benef.first_name)
		asha_name = u''
		if benef.caregiver:
			asha_name = unicode(benef.caregiver.first_name)
		
		#print unicodedata.normalize('NFKD', asha_name).encode('ascii', 'ignore')

		sms_text = sms_template.replace(u"prelude", prelude).replace(u"name", name).replace(u"category", category).replace(u"event", event).replace(u"asha", asha_name)
		#print sms_text
		sms_msg_hexlified = toHex(sms_text)

		print 'sending Voice Call:'
		
		sms_indicator = "#"+str(i)+": "+benef_number+" : "+ unicodedata.normalize('NFKD', event).encode('ascii', 'ignore') 
		print sms_indicator
		print unicodedata.normalize('NFKD', sms_text).encode('ascii', 'ignore')
		
		#f.write(sms_indicator)
		#f.write(unicodedata.normalize('NFKD', sms_text).encode('ascii', 'ignore'))
		#f.write('\n')

		#sent_code = SendSMSUnicode(recNum=benef_number, msgtxt=sms_msg_hexlified)
		sent_code = 'Status=0'
		#print sent_code
		#f.write(sent_code)
		#f.write('#################################\n')

		i = i +1

		if 'Status=1' in sent_code:
			ContentDelivered.objects.create(msg= sms_text, medium=ContentDelivered.SMS, timestamp = utcnow_aware(), status=1, benefeciary = benef)
		elif 'Status=0' in sent_code:
			ContentDelivered.objects.create(msg= sms_text, medium=ContentDelivered.SMS, timestamp = utcnow_aware(), status=0, benefeciary = benef)	
	f.close()
	return HttpResponse('Succefully sent the SMS', mimetype="application/json")
示例#16
0
文件: views.py 项目: komaliitm/Patedu
def RestBeneficiaryList(request):
	if request.method == 'GET':
		name = request.GET.get('name')
		notif_num = request.GET.get('notif_num')
		dob = request.GET.get('dob')
		sex = request.GET.get('sex')
		gaurdian_name = request.GET.get('gaurdian_name')
		language = request.GET.get('language')
		hw_num = request.GET.get('hw_num')
		is_verified = request.GET.get('is_verified')

		filter_set ={}

		if name is not None: filter_set['ChildName'] = name
		if dob is not None:
			dob = dateutil.parser.parse(dob).date()
			filter_set['Dob'] = dob
		if notif_num is not None: filter_set['NotifyNumber'] = notif_num
		if sex is not None: filter_set['Sex'] = sex
		if gaurdian_name is not None: filter_set['Gaurdian_name']= gaurdian_name
		if language is not None: filter_set['Language'] = language
		if is_verified is not None: filter_set['isVerified'] = is_verified 

		if hw_num is not None:
			hw = None
			try:
				hw = HealthWorker.objects.get(phone=hw_num)
			except ObjectDoesNotExist:
				hw = HealthWorker(phone=hw_num, username=hw_num, password= "******")
				hw.save()
			filter_set['health_worker'] = hw
		
		beneficiaries = VaccinationBeneficiary.objects.all()
		for k, v in filter_set.items():
			if v:
				beneficiaries = beneficiaries.filter(**{k: v})

		ret_val = [record.json() for record in beneficiaries]
		return HttpResponse(json.dumps(ret_val), mimetype="application/json")
	elif request.method == 'POST':
		name = request.POST.get('name')
		notif_num = request.POST.get('notif_num')
		dob = request.POST.get('dob')
		sex = request.POST.get('sex')
		gaurdian_name = request.POST.get('gaurdian_name')
		language = request.POST.get('language')
		hw_num = request.POST.get('hw_num')

		if name is not None and dob is not None and notif_num is not None:
			dob = dateutil.parser.parse(dob).date()
			
			beneficiaries = VaccinationBeneficiary.objects.filter(NotifyNumber = notif_num, Dob=dob) 
			if beneficiaries.count() > 0:
				return HttpResponse( json.dumps(beneficiaries[0].json()), mimetype="application/json")
			
			benef_post = VaccinationBeneficiary(ChildName=name, Dob=dob)
			if notif_num is not None: benef_post.NotifyNumber = notif_num
			if sex is not None: benef_post.Sex = sex
			if gaurdian_name is not None: benef_post.Gaurdian_name = gaurdian_name
			if language is not None: benef_post.Language = language
			
			if hw_num is not None:
				hw = None
				try:
					hw = HealthWorker.objects.get(phone=hw_num)
				except ObjectDoesNotExist:
					hw = HealthWorker(phone=hw_num, username=hw_num, password= "******")
					hw.save()
				benef_post.health_worker = hw
			benef_post.isVerified = False
			benef_post.VerificationCode = randint(1000, 9999)
			benef_post.CreatedOn = utcnow_aware()
			benef_post.ModifiedOn = utcnow_aware()
			benef_post.BeneficiaryId = get_a_Uuid()

			benef_post.save()
			platform = sys.platform

			generate_schedule(benef_post.BeneficiaryId)
			welcome_msg_id = 'VAC_WELCOME'
			if platform == 'linux2':
				result = send_instant_msg.delay(benef_post.NotifyNumber, welcome_msg_id)
			else:
				result = send_instant_msg(benef_post.NotifyNumber, welcome_msg_id)
			return HttpResponse( json.dumps(benef_post.json()), mimetype="application/json")
		else:
			return HttpResponseBadRequest('Name or DOB cannot be empty while adding a value')
	return HttpResponseBadRequest('Unsupported HTTP request type for this URL')
示例#17
0
文件: views.py 项目: komaliitm/Patedu
def OutreachData(request):
	today_date = utcnow_aware().date()
	this_month_date = today_date.replace(day=1)
	this_week = today_date.day%7
	last_week_date = today_date.replace(day=7*(this_week-1))

	if request.method == 'GET':
		district_mcts_id = str(request.GET.get('district_mcts_id')) if request.GET.get('district_mcts_id') else '36'
		try:
			district = District.objects.get(MCTS_ID=district_mcts_id)
		except:
			return HttpResponseBadRequest('Wrong district id specified')
		months_back = int(request.GET.get('months_back')) if request.GET.get('months_back') else 0
		
		#
		blocks = Block.objects.filter(subcenters__district=district).distinct()
		outreach_anm = []
		outreach_asha = []
		outreach_benef = []
		for block in blocks:
			anm_outreach_data = {}
			asha_outreach_data = {}
			benef_outreach_data = {}
			anm_outreach_data['name'] = block.name.upper()
			anm_outreach_data['scheduled'] = 'NA'
			anm_outreach_data['sent'] = ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, subcenter__block=block, role='ANM').count()
			anm_outreach_data['answered'] = ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, status='completed', subcenter__block=block, role='ANM').count()
			asha_outreach_data['name'] = block.name.upper()
			asha_outreach_data['scheduled'] = 'NA'
			asha_outreach_data['sent'] = ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, subcenter__block=block, role='ASHA').count()
			asha_outreach_data['answered'] = ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, status='completed', subcenter__block=block, role='ASHA').count()
			benef_outreach_data['name'] = block.name.upper()
			benef_outreach_data['scheduled'] = 0
			benef_outreach_data['sent'] = 0
			benef_outreach_data['answered'] = 0
			
			anm_outreach_data['total'] = ExotelCallStatus.objects.filter(subcenter__block=block, role='ANM').count()
			anm_outreach_data['week'] = ExotelCallStatus.objects.filter(date_initiated__gte=last_week_date, subcenter__block=block, role='ANM').count()

			asha_outreach_data['total'] = ExotelCallStatus.objects.filter(subcenter__block=block, role='ASHA').count()
			asha_outreach_data['week'] = ExotelCallStatus.objects.filter(date_initiated__gte=last_week_date, subcenter__block=block, role='ASHA').count()


			subcenters = SubCenter.objects.filter(block=block)
			subcenters_anm = []
			subcenters_asha = []
			subcenters_benef = []
			for subcenter in subcenters:
				#Calculate seprately, for this subcenter calls stats in each area
				
				anm_status_map = ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, subcenter=subcenter, role='ANM').values('status').annotate(count=Count('id'))
				asha_status_map = ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, subcenter=subcenter, role='ASHA').values('status').annotate(count=Count('id'))
				dict_anm = {
					'name':subcenter.name,
					'scheduled':'NA',
					'sent':ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, subcenter=subcenter, role='ANM').count(),
					'answered':ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, status='completed', subcenter=subcenter, role='ANM').count(),
					'status_map': [status for status in anm_status_map]
				}

				dict_asha = {
					'name':subcenter.name,
					'scheduled':'NA',
					'sent':ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, subcenter=subcenter, role='ASHA').count(),
					'answered':ExotelCallStatus.objects.filter(date_initiated__gte=this_month_date, status='completed', subcenter=subcenter, role='ASHA').count(),
					'status_map': [status for status in asha_status_map]
				}

				dict_benef = {
					'name':subcenter.name,
					'scheduled':0,
					'sent':0,
					'answered':0
				}
				subcenters_anm.append(dict_anm)
				subcenters_asha.append(dict_asha)
				subcenters_benef.append(dict_benef)
			anm_outreach_data['subcenter'] = subcenters_anm
			asha_outreach_data['subcenter'] = subcenters_asha
			benef_outreach_data['subcenter'] = subcenters_benef
			outreach_anm.append(anm_outreach_data)
			outreach_asha.append(asha_outreach_data)
			outreach_benef.append(benef_outreach_data)
		outreach ={
			'anm':outreach_anm,
			'asha':outreach_asha,
			'benef':outreach_benef
		}
		return HttpResponse(json.dumps(outreach),  mimetype='application/json')
	else:
		return HttpResponseBadRequest('HTTP method type not allowed')
示例#18
0
def analytics_aggregator_allblocks(district_mcts_id='36'):
	try:
		district = District.objects.get(MCTS_ID=district_mcts_id)
	except ObjectDoesNotExist:
		print "specified district does not exist"
		return

	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz) 
	
	dt_month = today.date().month
	dt_year = today.date().year

	month_span = [1, 2, 3, 4, 5, 6, 12]
	for months in month_span:
		this_month_date = today.replace(hour=6, minute=0, second=0, day=1).astimezone(pytz.utc)
		since_months = this_month_date - relativedelta(months=(months-1))
		blocks = SubCenter.objects.filter(district=district).values('block_id')
		for block_entry in blocks:
			block = Block.objects.get(id=block_entry['block_id'])
			if AnalyticsData.objects.filter(block=block, since_months=months, month= this_month_date.month, year=this_month_date.year):
				continue
			subcenters = SubCenter.objects.filter(block=block)
			data = []
			num_good_anc = 0
			num_poor_anc = 0
			num_avg_anc = 0
			num_good_pnc = 0
			num_poor_pnc = 0
			num_avg_pnc = 0
			num_good_imm = 0
			num_poor_imm = 0
			num_avg_imm = 0
			for sub in subcenters:
				sub_data = {}

				#total beneficiaries.
				anc_benefs = ANCBenef.objects.filter(subcenter = sub)
				pnc_benefs = PNCBenef.objects.filter(subcenter = sub)
				imm_benefs = IMMBenef.objects.filter(subcenter = sub)

				sub_data["Beneficiaries_anc"] = anc_benefs.count()
				sub_data["Beneficiaries_pnc"] = pnc_benefs.count()
				sub_data["Beneficiaries_imm"] = imm_benefs.count()

				from mcts_transactions.views import ProcessSubcenterData, get_status, increment_count_on_status
				data_anc = ProcessSubcenterData(anc_benefs, sub, since_months, Events.ANC_REG_VAL, months)
				data_pnc = ProcessSubcenterData(pnc_benefs, sub, since_months, Events.PNC_REG_VAL, months)
				data_imm = ProcessSubcenterData(imm_benefs, sub, since_months, Events.IMM_REG_VAL, months)

				sub_data["Beneficiaries_anc"] = anc_benefs.count()
				sub_data["Beneficiaries_pnc"] = pnc_benefs.count()
				sub_data["Beneficiaries_imm"] = imm_benefs.count()
				sub_data["Adherence_anc"] = data_anc["Adherence"]
				sub_data["Adherence_pnc"] = data_pnc["Adherence"]
				sub_data["Adherence_imm"] = data_imm["Adherence"]
				sub_data["new_reg_anc"] = data_anc["new_reg"]
				sub_data["new_reg_pnc"] = data_pnc["new_reg"]
				sub_data["new_reg_imm"] = data_imm["new_reg"]
	 			sub_data["Overdue_anc"] = data_anc["Overdue"]
				sub_data["Overdue_pnc"] = data_pnc["Overdue"]
				sub_data["Overdue_imm"] = data_imm["Overdue"]
				sub_data["overdue_sg_anc"] = data_anc["overdue_sg"]
				sub_data["overdue_sg_pnc"] = data_pnc["overdue_sg"]
				sub_data["overdue_sg_imm"] = data_imm["overdue_sg"]
				sub_data["GivenServices_anc"] = data_anc["GivenServices"]
				sub_data["GivenServices_pnc"] = data_pnc["GivenServices"]
				sub_data["GivenServices_imm"] = data_imm["GivenServices"]
				sub_data["OverDueRate_anc"] = data_anc["OverDueRate"]
				sub_data["OverDueRate_pnc"] = data_pnc["OverDueRate"]
				sub_data["OverDueRate_imm"] = data_imm["OverDueRate"]
				sub_data["ProgressData_anc"] = data_anc["ProgressData"]
				sub_data["ProgressData_pnc"] = data_pnc["ProgressData"]
				sub_data["ProgressData_imm"] = data_imm["ProgressData"]

				status_anc = get_status(data_anc["OverDueRate"], 5, 7)
				status_pnc = get_status(data_pnc["OverDueRate"], 5, 7)
				status_imm = get_status(data_imm["OverDueRate"], 5, 7)
				
				num_good_anc, num_avg_anc, num_poor_anc = increment_count_on_status(status_anc, num_good_anc, num_avg_anc, num_poor_anc)
				num_good_pnc, num_avg_pnc, num_poor_pnc = increment_count_on_status(status_pnc, num_good_pnc, num_avg_pnc, num_poor_pnc)
				num_good_imm, num_avg_imm, num_poor_imm = increment_count_on_status(status_imm, num_good_imm, num_avg_imm, num_poor_imm) 

				sub_data["status_anc"] = status_anc
				sub_data["status_pnc"] = status_pnc
				sub_data["status_imm"] = status_imm
				from math import ceil
				sub_data["status"] = ceil((status_anc + status_pnc + status_imm)/3 - 0.5)
				sub_data["Subcenter"] = sub.name
				sub_data["SubcenterId"] = sub.id

				AshaDetails = []
				cgs = Beneficiary.objects.all().filter(subcenter = sub).values("caregiver").distinct()
				for cg in cgs:
					if cg["caregiver"]:
						_cg = CareGiver.objects.get(id=cg["caregiver"])
						AshaDetails.append(_cg.first_name+':'+_cg.phone)

				sub_data["AshaDetails"] = AshaDetails
				
				ANMDetails = []
				cps = Beneficiary.objects.all().filter(subcenter = sub).values("careprovider").distinct()
				for cp in cps:
					if cp["careprovider"]:
						_cp = CareProvider.objects.get(id=cp["careprovider"])
						ANMDetails.append(_cp.first_name+':'+_cp.phone)

				sub_data["ANMDetails"] = ANMDetails

				# TODO remove dummy lat, long later
				_lat = block._lat if block._lat else 25.619626 
				_long = block._long if block._long else 79.180409
				sign = randint(1,2)
				if sign == 1:
					_lat = _lat + randint(1,100)*0.005
					_long = _long + randint(1,100)*0.005
				else:
					_lat = _lat - randint(1,100)*0.005
					_long = _long - randint(1,100)*0.005

				sub_data["lat"] = sub._lat if sub._lat else _lat
				sub_data["long"] = sub._long if sub._long else _long

				data.append(sub_data)
			block_data = {}
			block_data["data"] = data
			block_data["summary"] = { "Good":num_good_anc , "Poor":num_poor_anc ,"Average":num_avg_anc }	
			block_data["summary_anc"] = { "Good":num_good_anc , "Poor":num_poor_anc ,"Average":num_avg_anc }
			block_data["summary_pnc"] = { "Good":num_good_pnc , "Poor":num_poor_pnc ,"Average":num_avg_pnc }
			block_data["summary_imm"] = { "Good":num_good_imm , "Poor":num_poor_imm ,"Average":num_avg_imm }
			block_data["blockid"] = block.id
			block_data["blockname"] = block.name
			if not AnalyticsData.objects.filter(block=block, since_months=months, month= this_month_date.month, year=this_month_date.year):
				print "adding: "+str(block.id)+" , "+"months "
				ad = AnalyticsData.objects.create(block = block, data = json.dumps(block_data["data"]), summary=json.dumps(block_data["summary"]),\
			 		summary_anc=json.dumps(block_data["summary_anc"]), summary_imm=json.dumps(block_data["summary_imm"]),\
			 		summary_pnc=json.dumps(block_data["summary_pnc"]), since_months = months, month = this_month_date.month, year=this_month_date.year)
示例#19
0
文件: views.py 项目: komaliitm/Patedu
def UploadAndSave(input_excel, benef_type):
    ret = {
        'status':0,
        'msg':''
    }

    book = xlrd.open_workbook(file_contents=input_excel.read())
    sheet = book.sheet_by_index(0)
    initialIndex = 0
    workplan_list = []

    w=0
    while(1==1):
        w=w+1
        startIndex = getStartingRow(sheet, initialIndex)
       
        if startIndex == "NoData":
            break
        else:
            chunk_dict={}
            columnArray = []
            dict_header = getHeaderDict(sheet, initialIndex, startIndex)
            columnArray = getColumnNames(sheet, startIndex)
            #print "colIndexes="+str(colIndexes)
            rowIndex= startIndex                
            t=0
            row_list=[]
            dict_row = {}
            rowIndex=rowIndex+1
            try:
                while sheet.cell_value(rowIndex,colIndexes[0])!="" and sheet.cell_value(rowIndex,colIndexes[1])!="":
                   
                    t=t+1
                    dict_row = getRowDict(rowIndex, columnArray , sheet)
                   
                    row_list.append(dict_row)
                    rowIndex=rowIndex+1
            except:
                print "Exception Main Loop"

            chunk_dict["header"] = dict_header
            chunk_dict["data"] = row_list
            workplan_list.append(chunk_dict)
            initialIndex = rowIndex
    
    _fileObject = None
    ret['msg'] = "Saved successfully"
    for workplan_chunk in workplan_list:           
        header = workplan_chunk["header"]
        data = workplan_chunk["data"]
        
        if len(data) == 0:
            ret['msg'] = 'Data length is zero'
            continue

        if benef_type == 'ANC' and 'lmp_date' not in data[0]:
            ret['msg'] = 'Incorrect report type selected. Immunization selected for ANC workplan.'
            ret['status'] = 1
            return ret


        if benef_type != 'ANC' and 'lmp_date' in data[0]:
            ret['msg'] = 'Incorrect report type selected. ANC selected for Immunization workplan.'
            ret['status'] = 1
            return ret

        #header data
        block = header.get("Health_Block").replace("\n","").strip()
        district = header.get("District").replace("\n","").strip()
        health_facility = header.get("Health_Facility").replace("\n","").strip()
        month = header.get("ReportMonth").replace("\n","").strip()
        year = header.get("ReportYear").replace("\n","").strip()
        state = header.get("State").replace("\n","").strip()
        subfacility = header.get("SubFacility").replace("\n","").strip()
        subfacility_id = header.get("SubFacilityID").replace("\n","").strip()
        
        stamp = benef_type+"_"+state+"_"+district+"_"+block+"_"+health_facility+"_"+subfacility+"_"+subfacility_id+"_"+year+"_"+month+"_"+state
        if not AvailableMCTSData.objects.filter(stamp=stamp):
            chunk = AvailableMCTSData.objects.create(stamp= stamp, benef_type=benef_type, block=block, district=district, health_facility=health_facility, month=month, year=year, state=state, subfacility=subfacility, subfacility_id=subfacility_id, time_stamp=utcnow_aware())
        else:
            ret['msg'] = 'Report already exists'
            continue

        timezone = 'Asia/Kolkata'
        tz = pytz.timezone(timezone)
        today_utc = utcnow_aware()
        today = today_utc.astimezone(tz)
        #create then date, which is 1st of given month 12:00 PM noon IST
        if month and year:
            date_str = month+','+year
            date_then = datetime.datetime.strptime(date_str, "%B,%Y")
            date_then = date_then + datetime.timedelta(hours=12)
            date_then = date_then.replace(second=0)
        else:
            date_then = today.replace(hour=12, minute=0, day=1, second=0).astimezone(pytz.utc)

        t_district = GetFacilityFromString(district)
        t_block = GetFacilityFromString(block)
        t_health_facility = GetFacilityFromString(health_facility)

        #check and create district
        if t_district:
            dsts = District.objects.filter(MCTS_ID = t_district[1])
            if dsts.count()>0:
                district = dsts[0]
            else:
                district = District.objects.create(MCTS_ID = t_district[1], name=t_district[0])
        else:
            district = None

        #check and create block
        if t_block:
            blocks = Block.objects.filter(MCTS_ID = t_block[1])
            if blocks.count()>0:
                block = blocks[0]
            else:
                block = Block.objects.create(MCTS_ID = t_block[1], name=t_block[0])
        else:
            block = None

        #check and create health facility
        if t_health_facility:
            hfs = HealthFacility.objects.filter(MCTS_ID = t_health_facility[1])
            if hfs.count()>0:
                health_facility = hfs[0]
            else:
                health_facility = HealthFacility.objects.create(MCTS_ID = t_health_facility[1], name = t_health_facility[0])
        else:
            health_facility = None

        #check and create subcenter
        sbs = SubCenter.objects.filter(MCTS_ID = subfacility_id)
        if sbs.count() > 0:
            subfacility = sbs[0]
        else:
            subfacility = SubCenter.objects.create(MCTS_ID = subfacility_id, name=subfacility, district=district, block=block, health_facility=health_facility)

        for benef in data:
            if benef_type == 'ANC':
                print 'Prcessing subcenter for ANC'
                SaveANCBeneficiary(benef=benef, subcenter=subfacility, date_then=date_then)
            elif benef_type == 'PNC':
                SavePNCBeneficiary(benef=benef, subcenter=subfacility)
            elif benef_type == 'IMM1' or benef_type == 'IMM2':
                SaveIMMBeneficiary(benef=benef, subcenter=subfacility, date_then=date_then)
                pass
    #print workplan_list
    # print workplan_list[0]["header"]
    # print workplan_list[0]["data"][0]
    # print workplan_list[0]["data"][len(workplan_list[0]["data"])-1]

    # parsed = ""
    # for wp in workplan_list:
    #  parsed = parsed + " " +str(len(wp["data"]))

    # print parsed
    #newdoc = Document(myfile = request.FILES['file'])
    #newdoc.save()
        # Redirect to the document list after POST
    return ret
示例#20
0
文件: views.py 项目: komaliitm/Patedu
def DashboardData(request, blockid = None):
	if blockid:
		blocks = Block.objects.filter(id=blockid)
		if blocks.count() == 0:
			return HttpResponseBadRequest('wrong block id provided in the request')
		blockname = blocks[0].name
	else:
		blocks = Block.objects.all()
		blockname = 'All'

	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz)

	this_month_date = today.replace(hour=6, minute=0, second=0, day=1).astimezone(pytz.utc)
	#process GET params
	since_months = int(request.GET.get('since_months')) if request.GET.get('since_months') else None
	if since_months > 12:
		since_months =12 	
	if since_months:
		months = since_months
		since_months = this_month_date - relativedelta(months=since_months)
	else:
		months = 12
		since_months = this_month_date - relativedelta(months=12)

	data = []
	summary = {"Good":0, "Poor":0, "Average":0, "Excellent":0}
	summary_anc = {"Good":0, "Poor":0, "Average":0, "Excellent":0}
	summary_pnc = {"Good":0, "Poor":0, "Average":0, "Excellent":0}
	summary_imm = {"Good":0, "Poor":0, "Average":0, "Excellent":0}
	# num_good_anc = 0
	# num_poor_anc = 0
	# num_avg_anc = 0
	# num_good_pnc = 0
	# num_poor_pnc = 0
	# num_avg_pnc = 0
	# num_good_imm = 0
	# num_poor_imm = 0
	# num_avg_imm = 0
	from common.models import AnalyticsData
	from mcts_transactions.tasks import analytics_aggregator_allblocks
	for block in blocks:
		analytics_data = AnalyticsData.objects.filter(block=block, since_months=months, month= this_month_date.month, year=this_month_date.year)
		if not analytics_data:
			continue
			analytics_aggregator_allblocks.delay()
			return HttpResponseNotAllowed('Check after 5 mins. Data generation in progress.') 
		data += json.loads(analytics_data[0].data)

		summary["Good"] += json.loads(analytics_data[0].summary)["Good"]
		summary["Poor"] += json.loads(analytics_data[0].summary)["Poor"]
		summary["Average"] += json.loads(analytics_data[0].summary)["Average"]
		summary["Excellent"] += json.loads(analytics_data[0].summary)["Excellent"]

		summary_anc["Good"] += json.loads(analytics_data[0].summary_anc)["Good"]
		summary_anc["Poor"] += json.loads(analytics_data[0].summary_anc)["Poor"]
		summary_anc["Average"] += json.loads(analytics_data[0].summary_anc)["Average"]
		summary_anc["Excellent"] += json.loads(analytics_data[0].summary_anc)["Excellent"]

		summary_pnc["Good"] += json.loads(analytics_data[0].summary_pnc)["Good"]
		summary_pnc["Poor"] += json.loads(analytics_data[0].summary_pnc)["Poor"]
		summary_pnc["Average"] += json.loads(analytics_data[0].summary_pnc)["Average"]
		summary_pnc["Excellent"] += json.loads(analytics_data[0].summary_pnc)["Excellent"]

		summary_imm["Good"] += json.loads(analytics_data[0].summary_imm)["Good"]
		summary_imm["Poor"] += json.loads(analytics_data[0].summary_imm)["Poor"]
		summary_imm["Average"] += json.loads(analytics_data[0].summary_imm)["Average"]
		summary_imm["Excellent"] += json.loads(analytics_data[0].summary_imm)["Excellent"]
	block_data = {}
	block_data["data"] = data
	block_data["summary"] = summary
	block_data["summary_anc"] = summary_anc
	block_data["summary_pnc"] = summary_pnc
	block_data["summary_imm"] = summary_imm
	block_data["blockid"] = blockid
	block_data["blockname"] = blockname
	
	return HttpResponse(json.dumps(block_data), mimetype="application/json")
示例#21
0
文件: views.py 项目: komaliitm/Patedu
def BlockIndicesData(request):
	today_date = utcnow_aware().date()
	fin_marker = today_date.replace(month = 4, day=1)
	if today_date.month < 4:
		fin_marker = fin_marker.replace(year=today_date.year-1)
	this_month_date = today_date.replace(day=1)
	months_since_start = (this_month_date.month-fin_marker.month) if this_month_date.month > 3 else (this_month_date.month-fin_marker.month + 12) 

	last_year_date = this_month_date.replace(year=this_month_date.year-1)

	months_since_last_year = substract_months(this_month_date, last_year_date)

	mother_reg = [] #{block id, name, count, target, %, sorted}
	child_reg = [] #{block id,name, count, target, %, sorted}
	full_imm = [] #{block id,name, count, target, %, sorted}
	full_anc = [] #{block id,name, count, target, %, sorted}
	del_rep = [] #{block id,name, count, target, %, sorted}

	if request.method == 'GET':
		district_mcts_id = str(request.GET.get('district_mcts_id')) if request.GET.get('district_mcts_id') else '36'
		try:
			district = District.objects.get(MCTS_ID=district_mcts_id)
		except:
			return HttpResponseBadRequest('Wrong district id specified')
		from common.models import NHMTargets, PopulationData
		#Find all distinct blocks
		blocks = Block.objects.filter()
		#query to get all beneficiaries of  given financial year & given iterative block
		for block in blocks:
			imm_benefs = IMMBenef.objects.filter(subcenter__block=block, dob__gte=last_year_date)
			anc_benefs = ANCBenef.objects.filter(subcenter__block=block, LMP__gte=last_year_date)

			sex_ratio = 0
			female_infants = imm_benefs.filter(child_sex__icontains='f')
			sex_ratio = ceil(1000*2*female_infants.count()/imm_benefs.count()) if imm_benefs else 0

			mreg_district_target = NHMTargets.objects.get(target_type='MREG', district=district, target_year=fin_marker.year).target_value
			creg_district_target = NHMTargets.objects.get(target_type='CREG', district=district, target_year=fin_marker.year).target_value

			district_population = PopulationData.objects.get(unit_type=District.__name__, MCTS_ID= district.MCTS_ID, year=fin_marker.year).population
			block_population = PopulationData.objects.get(unit_type=Block.__name__, MCTS_ID=block.MCTS_ID, year=fin_marker.year).population

			mreg_target = ceil((mreg_district_target * block_population) / (district_population) )
			creg_target = ceil((creg_district_target * block_population) / (district_population) )

			# imm_benefs_last_year = IMMBenef.objects.filter(subcenter__block=block, dob__year=last_year_date.year, dob__month=last_year_date.month)
			# anc_benefs_last_year = ANCBenef.objects.filter(subcenter__block=block, LMP__year=last_year_date.year, LMP__month=last_year_date.month)
			
			imm_benefs_last_year = imm_benefs
			anc_benefs_last_year = anc_benefs

			# fimm_target = imm_benefs_last_year.count()
			# fanc_target = anc_benefs_last_year.count()
			# drep_target = fanc_target

			fimm_target = imm_benefs.count()
			fanc_target = anc_benefs.count()
			drep_target = ceil(mreg_target * 0.9)

			anc_reports = ANCReportings.objects.filter(benef__in=anc_benefs_last_year)
			fanc_reportings = anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=False, anc3_date__isnull=False,\
			 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=True, anc2_date__isnull=False, anc3_date__isnull=False,\
			 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=True, anc3_date__isnull=False,\
			 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=False, anc3_date__isnull=True,\
			 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=False, anc3_date__isnull=False,\
			 anc4_date__isnull=True)
			fanc_count = fanc_reportings.count()

			imm_reports = IMMReportings.objects.filter(benef__in=imm_benefs_last_year)
			fimm_reportings = imm_reports.filter(measles_date__isnull=False)
			fimm_count = fimm_reportings.count()

			drep_count = anc_reports.filter(delivery_date__isnull=False).count()

			mreg = {
				'block_id':block.MCTS_ID,
				'block_name':block.name,
				'count':anc_benefs.count(),
				'target':mreg_target,
				'percent': (float(anc_benefs.count())/float(mreg_target))*100 if mreg_target else 0
			}
			creg = {
				'block_id':block.MCTS_ID,
				'block_name':block.name,
				'count':imm_benefs.count(),
				'target':creg_target,
				'percent': (float(imm_benefs.count())/float(creg_target))*100 if creg_target else 0
			}
			fanc = {
				'block_id':block.MCTS_ID,
				'block_name':block.name,
				'count':fanc_count,
				'target':fanc_target,
				'percent':(float(fanc_count)/float(fanc_target))*100 if fanc_target else 0
			}
			fimm = {
				'block_id':block.MCTS_ID,
				'block_name':block.name,
				'count':fimm_count,
				'target':fimm_target,
				'percent':(float(fimm_count)/float(fimm_target))*100 if fimm_target else 0
			}
			drep = {
				'block_id':block.MCTS_ID,
				'block_name':block.name,
				'count':drep_count,
				'target':drep_target,
				'percent':(float(drep_count)/float(drep_target))*100 if drep_target else 0,
				'sex_ratio':sex_ratio
			}
			mother_reg.append(mreg)
			child_reg.append(creg)
			full_imm.append(fimm)
			full_anc.append(fanc)
			del_rep.append(drep)

		mother_reg = sorted(mother_reg, key=lambda k:k.get("percent"), reverse=True)
		child_reg = sorted(child_reg, key=lambda k:k.get("percent"), reverse=True)
		full_imm = sorted(full_imm, key=lambda k:k.get("percent"), reverse=True)
		full_anc = sorted(full_anc, key=lambda k:k.get("percent"), reverse=True)
		del_rep = sorted(del_rep, key=lambda k:k.get("percent"), reverse=True)
		#Prepare data: block name, count(), target, % sorted on %.
		#Preapre data: y-axis [index, block_name], x-axis [%, index]

		block_data = {
			"mother_reg":mother_reg, #{block id, name, count, target, %, sorted}
			"child_reg":child_reg,
			"full_imm":full_imm,
			"full_anc":full_anc,
			"del_rep":del_rep
		}

		mother_reg_graph_x = [[x.get("percent"), i] for i,x in enumerate(mother_reg)]
		mother_reg_graph_y = [[i, x.get("block_name")] for i,x in enumerate(mother_reg)]

		child_reg_graph_x = [[x.get("percent"), i] for i,x in enumerate(child_reg)]
		child_reg_graph_y = [[i, x.get("block_name")] for i,x in enumerate(child_reg)]

		full_imm_graph_x = [[x.get("percent"), i] for i,x in enumerate(full_imm)]
		full_imm_graph_y = [[i, x.get("block_name")] for i,x in enumerate(full_imm)]

		full_anc_graph_x = [[x.get("percent"), i] for i,x in enumerate(full_anc)]
		full_anc_graph_y = [[i, x.get("block_name")] for i,x in enumerate(full_anc)]

		del_rep_graph_x = [[x.get("percent"), i] for i,x in enumerate(del_rep)]
		del_rep_graph_y = [[i, x.get("block_name")] for i,x in enumerate(del_rep)]

		block_graph_data = {
			"mother_reg_chart" : [mother_reg_graph_x, mother_reg_graph_y],
			"child_reg_chart" : [child_reg_graph_x, child_reg_graph_y], 
			"full_anc_chart" : [full_anc_graph_x, full_anc_graph_y],
			"full_imm_chart" : [full_imm_graph_x, full_imm_graph_y],
			"del_rep_chart" : [del_rep_graph_x, del_rep_graph_y]
		}

		imm_benefs = IMMBenef.objects.filter(subcenter__district=district, dob__gte=last_year_date)
		anc_benefs = ANCBenef.objects.filter(subcenter__district=district, LMP__gte=last_year_date)

		mreg_district_target_annual = NHMTargets.objects.get(target_type='MREG', district=district, target_year=fin_marker.year).target_value
		creg_district_target_annual = NHMTargets.objects.get(target_type='CREG', district=district, target_year=fin_marker.year).target_value

		mreg_district_target = ceil((mreg_district_target_annual))
		creg_district_target = ceil((creg_district_target_annual))

		# imm_benefs_last_year = IMMBenef.objects.filter(subcenter__district=district, dob__year=last_year_date.year, dob__month=last_year_date.month)
		# anc_benefs_last_year = ANCBenef.objects.filter(subcenter__district=district, LMP__year=last_year_date.year, LMP__month=last_year_date.month)
		imm_benefs_last_year = imm_benefs
		anc_benefs_last_year = anc_benefs		

		fimm_target = imm_benefs.count()
		fanc_target = anc_benefs.count()
		drep_target = ceil(mreg_district_target * 0.9)
		
		# fimm_target = imm_benefs_last_year.count()
		# fanc_target = anc_benefs_last_year.count()
		# drep_target = fanc_target

		anc_reports = ANCReportings.objects.filter(benef__in=anc_benefs_last_year)
		fanc_reportings = anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=False, anc3_date__isnull=False,\
		 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=True, anc2_date__isnull=False, anc3_date__isnull=False,\
		 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=True, anc3_date__isnull=False,\
		 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=False, anc3_date__isnull=True,\
		 anc4_date__isnull=False) | anc_reports.filter( anc1_date__isnull=False, anc2_date__isnull=False, anc3_date__isnull=False,\
		 anc4_date__isnull=True)
		fanc_count = fanc_reportings.count()

		imm_reports = IMMReportings.objects.filter(benef__in=imm_benefs_last_year)
		fimm_reportings = imm_reports.filter(measles_date__isnull=False)
		fimm_count = fimm_reportings.count()

		drep_count = anc_reports.filter(delivery_date__isnull=False).count()

		mother_reg = {
			'district_id':district.MCTS_ID,
			'district_name':district.name,
			'count':anc_benefs.count(),
			'target':mreg_district_target,
			'percent': (float(anc_benefs.count())/float(mreg_district_target))*100 if mreg_district_target else 0
		}

		child_reg = {
			'district_id':district.MCTS_ID,
			'district_name':district.name,
			'count':imm_benefs.count(),
			'target':creg_district_target,
			'percent': (float(imm_benefs.count())/float(creg_district_target))*100 if creg_district_target else 0
		}
		full_imm = {
			'district_id':district.MCTS_ID,
			'district_name':district.name,
			'count':fimm_count,
			'target':fimm_target,
			'percent':(float(fimm_count)/float(fimm_target))*100 if fimm_target else 0	
		} 
		full_anc = {
			'district_id':district.MCTS_ID,
			'district_name':district.name,
			'count':fanc_count,
			'target':fanc_target,
			'percent':(float(fanc_count)/float(fanc_target))*100 if fanc_target else 0	
		} 
		del_rep = {
			'district_id':district.MCTS_ID,
			'district_name':district.name,
			'count':drep_count,
			'target':drep_target,
			'percent':(float(drep_count)/float(drep_target))*100 if drep_target else 0
		} 

		district_data = {
			"mother_reg":mother_reg, #{block id, name, count, target, %, sorted}
			"child_reg":child_reg,
			"full_imm":full_imm,
			"full_anc":full_anc,
			"del_rep":del_rep
		}

		data = {
			'district_data':district_data,
			'block_graph_data':block_graph_data,
			'block_data':block_data
		}

		return HttpResponse(json.dumps(data),  mimetype='application/json')
	else:
		return HttpResponseBadRequest('Method type not allowed. Only get is allowed.')
示例#22
0
文件: views.py 项目: komaliitm/Patedu
def GenerateReportPerVillage(month =None, year=None):
	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	now_utc = utcnow_aware()
	now = now_utc.astimezone(tz)
	if not month:
		month = now.month
	if not year:
		year = now.year

	f1 = open('MCTSDLPMCS_IMM_SMS_REPORT_PERVILLAGE'+str(month)+', '+str(year), 'w')
	f2 = open('MCTSDLPMCS_ANC_SMS_REPORT_PERVILLAGE'+str(month)+', '+str(year), 'w')
	cds = ContentDelivered.objects.filter(timestamp__year = year, timestamp__month=month, status=0)

	ancReport = {}
	ancNumber = 0
	immReport = {}
	immNumber = 0
	for cd in cds:
		msg_log = unicode(', MSG SENT: ','utf-8').encode('utf8')+cd.msg.encode('utf8')
		msg_log = ('TO:'+cd.benefeciary.notify_number+'-'+cd.benefeciary.first_name+', TYPE:'+Beneficiary.NUMBER_TYPE_REVERSE_MAP[str(cd.benefeciary.notify_number_type)]).encode('utf8')+msg_log
		if ANCBenef.objects.filter(id=cd.benefeciary.id).count() > 0:
			if not cd.benefeciary.subcenter.MCTS_ID in ancReport:
				ancReport[cd.benefeciary.subcenter.MCTS_ID] = []
			ancReport[cd.benefeciary.subcenter.MCTS_ID].append(msg_log)
			ancNumber = ancNumber + 1
		elif IMMBenef.objects.filter(id=cd.benefeciary.id).count() > 0:
			if not cd.benefeciary.subcenter.MCTS_ID in immReport:
				immReport[cd.benefeciary.subcenter.MCTS_ID] = []
			immReport[cd.benefeciary.subcenter.MCTS_ID].append(msg_log)
			immNumber = immNumber + 1
		else:
			continue
	
	# print ancNumber
	# print ancReport
	# print immNumber
	# print immReport

	f2.write("================== ANC SMS REPORT ==================\n")
	f2.write("================== "+ str(month)+', '+str(year) +" ==================\n")
	f2.write("================== TOTAL BENEFECIARIES TOUCHED: "+ str(ancNumber)+" ==================\n")
	for k,v in ancReport.iteritems():
		subcenter = None
		try:
			subcenter = SubCenter.objects.get(MCTS_ID= k)
		except ObjectDoesNotExist:
			continue
		f2.write("\n\n\nDISTRICT: "+subcenter.district.name+"\t BLOCK: "+subcenter.block.name+"\t SUBCENTER: "+subcenter.name+"\n\n")
		i= 1
		for cd in v:
			f2.write("S.No. "+str(i))
			f2.write(": "+cd+"\n")
			i = i + 1

	f1.write("================== IMMUNIZATION SMS REPORT ==================\n")
	f1.write("================== "+ str(month)+', '+str(year) +" ==================\n")
	f1.write("================== TOTAL BENEFECIARIES TOUCHED: "+ str(immNumber)+" ==================\n")
	for k,v in immReport.iteritems():
		subcenter = None
		try:
			subcenter = SubCenter.objects.get(MCTS_ID= k)
		except ObjectDoesNotExist:
			continue
		f1.write("\n\n\nDISTRICT: "+subcenter.district.name+"\t BLOCK: "+subcenter.block.name+"\t SUBCENTER: "+subcenter.name+"\n\n")
		i= 1
		for cd in v:
			f1.write("S.No. "+str(i))
			f1.write(": "+cd+"\n")
			i = i + 1

	f1.close()
	f2.close()
示例#23
0
文件: tasks.py 项目: komaliitm/Patedu
def analytics_aggregator_allblocks(district_mcts_id='36', rw=False):
	try:
		district = District.objects.get(MCTS_ID=district_mcts_id)
	except ObjectDoesNotExist:
		print "specified district does not exist"
		return

	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz) 
	
	today_date = today.date()
	anc_cutoff = today_date - timedelta(days=280)
	imm_cutoff = today_date - timedelta(days=365)
	yesterday_utc = today_utc - timedelta(days=1)

	dt_month = today.date().month
	dt_year = today.date().year

	fin_marker = today_date.replace(month = 4, day=1)
	if today_date.month < 4:
		fin_marker = fin_marker.replace(year=today_date.year-1)
	mreg_district_target = NHMTargets.objects.get(target_type='MREG', district=district, target_year=fin_marker.year).target_value
	creg_district_target = NHMTargets.objects.get(target_type='CREG', district=district, target_year=fin_marker.year).target_value
	district_population = PopulationData.objects.get(unit_type=District.__name__, MCTS_ID= district.MCTS_ID, year=fin_marker.year).population

	month_span = [1, 2, 3, 4, 5, 6, 12]
	for months in month_span:
		this_month_date = today.replace(hour=6, minute=0, second=0, day=1).astimezone(pytz.utc)
		since_months = this_month_date - relativedelta(months=(months-1))
		blocks = SubCenter.objects.filter(district=district).values('block_id').distinct()
		for block_entry in blocks:
			block = Block.objects.get(id=block_entry['block_id'])
			if not rw and AnalyticsData.objects.filter(block=block, since_months=months, month= this_month_date.month, year=this_month_date.year):
				continue
			subcenters = SubCenter.objects.filter(block=block)
			data = []
			num_good_anc = 0
			num_poor_anc = 0
			num_avg_anc = 0
			num_exc_anc = 0
			num_good_pnc = 0
			num_poor_pnc = 0
			num_avg_pnc = 0
			num_exc_pnc = 0
			num_good_imm = 0
			num_poor_imm = 0
			num_avg_imm = 0
			num_exc_imm = 0
			for sub in subcenters:
				sub_data = {}

				#total beneficiaries.
				anc_benefs = ANCBenef.objects.filter(subcenter = sub)
				pnc_benefs = PNCBenef.objects.filter(subcenter = sub)
				imm_benefs = IMMBenef.objects.filter(subcenter = sub)

				sub_data["Beneficiaries_anc"] = anc_benefs.filter(LMP__gte=anc_cutoff).count()
				sub_data["Beneficiaries_pnc"] = pnc_benefs.count()
				sub_data["Beneficiaries_imm"] = imm_benefs.filter(dob__gte=imm_cutoff).count()

				from mcts_transactions.views import ProcessSubcenterData, get_status, increment_count_on_status, get_reg_status
				data_anc = ProcessSubcenterData(anc_benefs, sub, since_months, Events.ANC_REG_VAL, months)
				data_pnc = ProcessSubcenterData(pnc_benefs, sub, since_months, Events.PNC_REG_VAL, months)
				data_imm = ProcessSubcenterData(imm_benefs, sub, since_months, Events.IMM_REG_VAL, months)

				mreg_status = 0
				creg_status = 0
				try:
					subc_population = PopulationData.objects.get(unit_type=SubCenter.__name__, MCTS_ID=sub.MCTS_ID, year=fin_marker.year).population
					mreg_target = ceil((mreg_district_target * subc_population) / (district_population) )
					creg_target = ceil((creg_district_target * subc_population) / (district_population) )	
					sub_data["mreg_target"] = mreg_target
					sub_data["creg_target"] = creg_target
					mreg_status = sub_data["Beneficiaries_anc"]/mreg_target if mreg_target else 0 
					creg_target = sub_data["Beneficiaries_imm"]/creg_target if creg_target else 0
				except:
					sub_data["mreg_target"] = 'NA'
					sub_data["creg_target"] = 'NA'
				

				sub_data["Adherence_anc"] = data_anc["Adherence"]
				sub_data["Adherence_pnc"] = data_pnc["Adherence"]
				sub_data["Adherence_imm"] = data_imm["Adherence"]
				sub_data["new_reg_anc"] = data_anc["new_reg"]
				sub_data["new_reg_pnc"] = data_pnc["new_reg"]
				sub_data["new_reg_imm"] = data_imm["new_reg"]
	 			sub_data["Overdue_anc"] = data_anc["Overdue"]
				sub_data["Overdue_pnc"] = data_pnc["Overdue"]
				sub_data["Overdue_imm"] = data_imm["Overdue"]
				sub_data["overdue_sg_anc"] = data_anc["overdue_sg"]
				sub_data["overdue_sg_pnc"] = data_pnc["overdue_sg"]
				sub_data["overdue_sg_imm"] = data_imm["overdue_sg"]
				sub_data["due_sg_anc"] = data_anc["due_sg"]
				sub_data["due_sg_pnc"] = data_pnc["due_sg"]
				sub_data["due_sg_imm"] = data_imm["due_sg"]
				sub_data["given_sg_anc"] = data_anc["given_sg"]
				sub_data["given_sg_pnc"] = data_pnc["given_sg"]
				sub_data["given_sg_imm"] = data_imm["given_sg"]
				sub_data["GivenServices_anc"] = data_anc["GivenServices"]
				sub_data["GivenServices_pnc"] = data_pnc["GivenServices"]
				sub_data["GivenServices_imm"] = data_imm["GivenServices"]
				sub_data["DueServices_anc"] = data_anc["DueServices"]
				sub_data["DueServices_pnc"] = data_pnc["DueServices"]
				sub_data["DueServices_imm"] = data_imm["DueServices"]
				sub_data["OverDueRate_anc"] = data_anc["OverDueRate"]
				sub_data["OverDueRate_pnc"] = data_pnc["OverDueRate"]
				sub_data["OverDueRate_imm"] = data_imm["OverDueRate"]
				sub_data["ProgressData_anc"] = data_anc["ProgressData"]
				sub_data["ProgressData_pnc"] = data_pnc["ProgressData"]
				sub_data["ProgressData_imm"] = data_imm["ProgressData"]

				status_anc, reason_anc = get_status(data_anc["OverDueRate"], 3, 5)
				status_pnc, reason_pnc = get_status(data_pnc["OverDueRate"], 3, 5)
				status_imm, reason_imm = get_status(data_imm["OverDueRate"], 3, 5)

				if sub_data["Beneficiaries_anc"] == 0 or sub_data["DueServices_anc"] < 3:
					if status_anc == 0:
						reason_anc += "& Low beneficiary registration or updation"
					else:
						status_anc = 0
						reason_anc += "But Low beneficiary registration or updation"
				if sub_data["Beneficiaries_pnc"] == 0 or sub_data["DueServices_pnc"] < 3:
					if status_pnc == 0:
						reason_pnc += "& Low beneficiary registration or updation"
					else:
						status_pnc = 0
						reason_pnc += "But Low beneficiary registration or updation"
				if sub_data["Beneficiaries_imm"] == 0 or sub_data["DueServices_imm"] < 3:
					if status_imm == 0:
						reason_imm += "& Low beneficiary registration or updation"
					else:
						status_imm = 0
						reason_imm += "But Low beneficiary registration or updation"

				status_anc, reason_anc = get_reg_status(mreg_status, status_anc, reason_anc, .4, .7)
				status_imm, reason_imm = get_reg_status(creg_status, status_imm, reason_imm, .4, .7)

				num_good_anc, num_avg_anc, num_poor_anc, num_exc_anc = increment_count_on_status(status_anc, num_good_anc, num_avg_anc, num_poor_anc, num_exc_anc)
				num_good_pnc, num_avg_pnc, num_poor_pnc, num_exc_pnc = increment_count_on_status(status_pnc, num_good_pnc, num_avg_pnc, num_poor_pnc, num_exc_pnc)
				num_good_imm, num_avg_imm, num_poor_imm, num_exc_imm = increment_count_on_status(status_imm, num_good_imm, num_avg_imm, num_poor_imm, num_exc_imm) 

				sub_data["status_anc"] = status_anc
				sub_data["status_pnc"] = status_pnc
				sub_data["status_imm"] = status_imm
				sub_data["reason_anc"] = reason_anc
				sub_data["reason_pnc"] = reason_pnc
				sub_data["reason_imm"] = reason_imm
				sub_data["status"] = ceil((status_anc + status_pnc + status_imm)/3 - 0.5)
				sub_data["Subcenter"] = sub.name
				sub_data["SubcenterId"] = sub.id

				AshaDetails = []
				cgs = Beneficiary.objects.all().filter(subcenter = sub).values("caregiver").distinct()
				for cg in cgs:
					if cg["caregiver"]:
						_cg = CareGiver.objects.get(id=cg["caregiver"])
						AshaDetails.append(_cg.first_name+':'+_cg.phone)

				sub_data["AshaDetails"] = AshaDetails
				
				ANMDetails = []
				cps = Beneficiary.objects.all().filter(subcenter = sub).values("careprovider").distinct()
				for cp in cps:
					if cp["careprovider"]:
						_cp = CareProvider.objects.get(id=cp["careprovider"])
						ANMDetails.append(_cp.first_name+':'+_cp.phone)

				sub_data["ANMDetails"] = ANMDetails

				# TODO remove dummy lat, long later
				_lat = block._lat if block._lat else 25.619626 
				_long = block._long if block._long else 79.180409
				sign = randint(1,2)
				if sign == 1:
					_lat = _lat + randint(1,100)*0.005
					_long = _long + randint(1,100)*0.005
				else:
					_lat = _lat - randint(1,100)*0.005
					_long = _long - randint(1,100)*0.005

				sub_data["lat"] = sub._lat if sub._lat else _lat
				sub_data["long"] = sub._long if sub._long else _long

				data.append(sub_data)
			block_data = {}
			block_data["data"] = data
			block_data["summary"] = {"Excellent":num_exc_anc, "Good":num_good_anc , "Poor":num_poor_anc ,"Average":num_avg_anc }	
			block_data["summary_anc"] = {"Excellent":num_exc_anc, "Good":num_good_anc , "Poor":num_poor_anc ,"Average":num_avg_anc }
			block_data["summary_pnc"] = {"Excellent":num_exc_pnc, "Good":num_good_pnc , "Poor":num_poor_pnc ,"Average":num_avg_pnc }
			block_data["summary_imm"] = {"Excellent":num_exc_imm, "Good":num_good_imm , "Poor":num_poor_imm ,"Average":num_avg_imm }
			block_data["blockid"] = block.id
			block_data["blockname"] = block.name
			existing_analytics = AnalyticsData.objects.filter(block=block, since_months=months, month= this_month_date.month, year=this_month_date.year)
			if existing_analytics:
				existing_analytics.delete()

			print "adding: "+str(block.id)+" , "+"months "
			ad = AnalyticsData.objects.create(block = block, data = json.dumps(block_data["data"]), summary=json.dumps(block_data["summary"]),\
		 		summary_anc=json.dumps(block_data["summary_anc"]), summary_imm=json.dumps(block_data["summary_imm"]),\
		 		summary_pnc=json.dumps(block_data["summary_pnc"]), since_months = months, month = this_month_date.month, year=this_month_date.year)
示例#24
0
def DashboardData(request, blockid = None):
	if blockid:
		blocks = Block.objects.filter(id=blockid)
		if blocks.count() == 0:
			return HttpResponseBadRequest('wrong block id provided in the request')
		blockname = blocks[0].name
	else:
		blocks = Block.objects.all()
		blockname = 'All'

	timezone = 'Asia/Kolkata'
	tz = pytz.timezone(timezone)
	today_utc = utcnow_aware()
	today = today_utc.astimezone(tz)

	this_month_date = today.replace(hour=6, minute=0, second=0, day=1).astimezone(pytz.utc)
	#process GET params
	since_months = int(request.GET.get('since_months')) if request.GET.get('since_months') else None
	if since_months > 12:
		since_months =12 	
	if since_months:
		months = since_months
		since_months = this_month_date - relativedelta(months=since_months)
	else:
		months = 12
		since_months = this_month_date - relativedelta(months=12)

	data = []
	summary = {"Good":0, "Poor":0, "Average":0}
	summary_anc = {"Good":0, "Poor":0, "Average":0}
	summary_pnc = {"Good":0, "Poor":0, "Average":0}
	summary_imm = {"Good":0, "Poor":0, "Average":0}
	# num_good_anc = 0
	# num_poor_anc = 0
	# num_avg_anc = 0
	# num_good_pnc = 0
	# num_poor_pnc = 0
	# num_avg_pnc = 0
	# num_good_imm = 0
	# num_poor_imm = 0
	# num_avg_imm = 0
	from common.models import AnalyticsData
	from mcts_transactions.tasks import analytics_aggregator_allblocks
	for block in blocks:
		analytics_data = AnalyticsData.objects.filter(block=block, since_months=months, month= this_month_date.month, year=this_month_date.year)
		if not analytics_data:
			continue
			analytics_aggregator_allblocks.delay()
			return HttpResponseNotAllowed('Check after 5 mins. Data generation in progress.') 
		data += json.loads(analytics_data[0].data)
		summary["Good"] += json.loads(analytics_data[0].summary)["Good"]
		summary["Poor"] += json.loads(analytics_data[0].summary)["Poor"]
		summary["Average"] += json.loads(analytics_data[0].summary)["Average"]

		summary_anc["Good"] += json.loads(analytics_data[0].summary_anc)["Good"]
		summary_anc["Poor"] += json.loads(analytics_data[0].summary_anc)["Poor"]
		summary_anc["Average"] += json.loads(analytics_data[0].summary_anc)["Average"]

		summary_pnc["Good"] += json.loads(analytics_data[0].summary_pnc)["Good"]
		summary_pnc["Poor"] += json.loads(analytics_data[0].summary_pnc)["Poor"]
		summary_pnc["Average"] += json.loads(analytics_data[0].summary_pnc)["Average"]

		summary_imm["Good"] += json.loads(analytics_data[0].summary_imm)["Good"]
		summary_imm["Poor"] += json.loads(analytics_data[0].summary_imm)["Poor"]
		summary_imm["Average"] += json.loads(analytics_data[0].summary_imm)["Average"]

		# #find all the subcenters in the block
		# subs = SubCenter.objects.filter(block=block)
		# for sub in subs:
		# 	sub_data = {}

		# 	#total beneficiaries.
		# 	anc_benefs = ANCBenef.objects.filter(subcenter = sub)
		# 	pnc_benefs = PNCBenef.objects.filter(subcenter = sub)
		# 	imm_benefs = IMMBenef.objects.filter(subcenter = sub)

		# 	sub_data["Beneficiaries_anc"] = anc_benefs.count()
		# 	sub_data["Beneficiaries_pnc"] = pnc_benefs.count()
		# 	sub_data["Beneficiaries_imm"] = imm_benefs.count()

		# 	data_anc = ProcessSubcenterData(anc_benefs, sub, since_months, Events.ANC_REG_VAL, months)
		# 	data_pnc = ProcessSubcenterData(pnc_benefs, sub, since_months, Events.PNC_REG_VAL, months)
		# 	data_imm = ProcessSubcenterData(imm_benefs, sub, since_months, Events.IMM_REG_VAL, months)

		# 	sub_data["Beneficiaries_anc"] = anc_benefs.count()
		# 	sub_data["Beneficiaries_pnc"] = pnc_benefs.count()
		# 	sub_data["Beneficiaries_imm"] = imm_benefs.count()
		# 	sub_data["Adherence_anc"] = data_anc["Adherence"]
		# 	sub_data["Adherence_pnc"] = data_pnc["Adherence"]
		# 	sub_data["Adherence_imm"] = data_imm["Adherence"]
		# 	sub_data["new_reg_anc"] = data_anc["new_reg"]
		# 	sub_data["new_reg_pnc"] = data_pnc["new_reg"]
		# 	sub_data["new_reg_imm"] = data_imm["new_reg"]
 	# 		sub_data["Overdue_anc"] = data_anc["Overdue"]
		# 	sub_data["Overdue_pnc"] = data_pnc["Overdue"]
		# 	sub_data["Overdue_imm"] = data_imm["Overdue"]
		# 	sub_data["overdue_sg_anc"] = data_anc["overdue_sg"]
		# 	sub_data["overdue_sg_pnc"] = data_pnc["overdue_sg"]
		# 	sub_data["overdue_sg_imm"] = data_imm["overdue_sg"]
		# 	sub_data["GivenServices_anc"] = data_anc["GivenServices"]
		# 	sub_data["GivenServices_pnc"] = data_pnc["GivenServices"]
		# 	sub_data["GivenServices_imm"] = data_imm["GivenServices"]
		# 	sub_data["OverDueRate_anc"] = data_anc["OverDueRate"]
		# 	sub_data["OverDueRate_pnc"] = data_pnc["OverDueRate"]
		# 	sub_data["OverDueRate_imm"] = data_imm["OverDueRate"]
		# 	sub_data["ProgressData_anc"] = data_anc["ProgressData"]
		# 	sub_data["ProgressData_pnc"] = data_pnc["ProgressData"]
		# 	sub_data["ProgressData_imm"] = data_imm["ProgressData"]

		# 	status_anc = get_status(data_anc["OverDueRate"], 5, 7)
		# 	status_pnc = get_status(data_pnc["OverDueRate"], 5, 7)
		# 	status_imm = get_status(data_imm["OverDueRate"], 5, 7)
			
		# 	num_good_anc, num_avg_anc, num_poor_anc = increment_count_on_status(status_anc, num_good_anc, num_avg_anc, num_poor_anc)
		# 	num_good_pnc, num_avg_pnc, num_poor_pnc = increment_count_on_status(status_pnc, num_good_pnc, num_avg_pnc, num_poor_pnc)
		# 	num_good_imm, num_avg_imm, num_poor_imm = increment_count_on_status(status_imm, num_good_imm, num_avg_imm, num_poor_imm) 

		# 	sub_data["status_anc"] = status_anc
		# 	sub_data["status_pnc"] = status_pnc
		# 	sub_data["status_imm"] = status_imm
		# 	from math import ceil
		# 	sub_data["status"] = ceil((status_anc + status_pnc + status_imm)/3 - 0.5)
		# 	sub_data["Subcenter"] = sub.name
		# 	sub_data["SubcenterId"] = sub.id

		# 	AshaDetails = []
		# 	cgs = Beneficiary.objects.all().filter(subcenter = sub).values("caregiver").distinct()
		# 	for cg in cgs:
		# 		if cg["caregiver"]:
		# 			_cg = CareGiver.objects.get(id=cg["caregiver"])
		# 			AshaDetails.append(_cg.first_name+':'+_cg.phone)

		# 	sub_data["AshaDetails"] = AshaDetails
			
		# 	ANMDetails = []
		# 	cps = Beneficiary.objects.all().filter(subcenter = sub).values("careprovider").distinct()
		# 	for cp in cps:
		# 		if cp["careprovider"]:
		# 			_cp = CareProvider.objects.get(id=cp["careprovider"])
		# 			ANMDetails.append(_cp.first_name+':'+_cp.phone)

		# 	sub_data["ANMDetails"] = ANMDetails


		# 	sub_data["lat"] = sub._lat if sub._lat else block._lat
		# 	sub_data["long"] = sub._long if sub._long else block._long

		# 	#TODO remove dummy lat, long later
		# 	#_lat = 25.619626
		# 	#_long = 79.180409
		# 	#sign = randint(1,2)
		# 	#if sign == 1:
		# 	#	sub_data["lat"] = _lat + randint(1,100)*0.01
		# 	#	sub_data["long"] = _long + randint(1,100)*0.01
		# 	#else:
		# 	#	sub_data["lat"] = _lat - randint(1,100)*0.01
		# 	#	sub_data["long"] = _long - randint(1,100)*0.01

		# 	data.append(sub_data)

	block_data = {}
	block_data["data"] = data
	block_data["summary"] = summary
	block_data["summary_anc"] = summary_anc
	block_data["summary_pnc"] = summary_pnc
	block_data["summary_imm"] = summary_imm
	block_data["blockid"] = blockid
	block_data["blockname"] = blockname
	
	return HttpResponse(json.dumps(block_data), mimetype="application/json")