<s> from datetime import datetime , time <EOL> import logging <EOL> import uuid <EOL> import tempfile <EOL> from lxml import etree <EOL> from django . core . servers . basehttp import FileWrapper <EOL> from django . utils . decorators import method_decorator <EOL> from casexml . apps . phone . middleware import LAST_SYNCTOKEN_HEADER <EOL> from dimagi . utils . parsing import json_format_date <EOL> from django_digest . decorators import httpdigest <EOL> import json <EOL> from django . http import Http404 , HttpResponse <EOL> from django . core . cache import cache <EOL> from corehq . apps . api . domainapi import DomainAPI <EOL> from corehq . apps . api . es import ReportXFormES <EOL> from corehq . apps . domain . decorators import login_or_digest <EOL> from corehq . apps . fixtures . models import FixtureDataItem <EOL> from corehq . apps . groups . models import Group <EOL> from corehq . apps . users . models import CouchUser <EOL> from couchforms . models import XFormInstance <EOL> import localsettings <EOL> from pact . dot_data import get_dots_case_json <EOL> from pact . enums import ( PACT_DOMAIN , XMLNS_PATIENT_UPDATE , PACT_HP_GROUPNAME , PACT_PROVIDERS_FIXTURE_CACHE_KEY , <EOL> XMLNS_PATIENT_UPDATE_DOT ) <EOL> from pact . forms . patient_form import PactPatientForm <EOL> from pact . forms . weekly_schedule_form import ScheduleForm , DAYS_OF_WEEK <EOL> from pact . tasks import set_schedule_case_properties <EOL> from pact . utils import pact_script_fields , case_script_field , submit_xform , query_per_case_submissions_facet <EOL> from corehq . apps . app_manager . dbaccessors import get_latest_build_id <EOL> PACT_CLOUD_APPNAME = "<STR_LIT>" <EOL> PACT_CLOUDCARE_MODULE = "<STR_LIT>" <EOL> FORM_PROGRESS_NOTE = "<STR_LIT>" <EOL> FORM_DOT = "<STR_LIT>" <EOL> FORM_BLOODWORK = "<STR_LIT>" <EOL> FORM_ADDRESS = "<STR_LIT>" <EOL> def get_cloudcare_app ( ) : <EOL> """<STR_LIT>""" <EOL> from corehq . apps . cloudcare import api <EOL> app = api . get_cloudcare_app ( PACT_DOMAIN , PACT_CLOUD_APPNAME ) <EOL> app_id = app [ '<STR_LIT>' ] <EOL> pact_cloudcare = filter ( lambda x : x [ '<STR_LIT:name>' ] [ '<STR_LIT>' ] == PACT_CLOUDCARE_MODULE , app [ '<STR_LIT>' ] ) <EOL> forms = pact_cloudcare [ <NUM_LIT:0> ] [ '<STR_LIT>' ] <EOL> ret = dict ( ( f [ '<STR_LIT:name>' ] [ '<STR_LIT>' ] , ix ) for ( ix , f ) in enumerate ( forms ) ) <EOL> url_root = '<STR_LIT>' <EOL> ret [ '<STR_LIT>' ] = url_root <EOL> ret [ '<STR_LIT>' ] = PACT_DOMAIN <EOL> ret [ '<STR_LIT>' ] = app_id <EOL> latest_build_id = get_latest_build_id ( PACT_DOMAIN , app_id ) <EOL> if latest_build_id is not None : <EOL> ret [ '<STR_LIT>' ] = latest_build_id <EOL> ret [ '<STR_LIT>' ] = <NUM_LIT:0> <EOL> return ret <EOL> def get_cloudcare_url ( case_id , mode ) : <EOL> app_dict = get_cloudcare_app ( ) <EOL> url_root = app_dict [ '<STR_LIT>' ] <EOL> build_id = app_dict [ '<STR_LIT>' ] <EOL> module_id = app_dict [ '<STR_LIT>' ] <EOL> return url_root % dict ( form_id = app_dict [ mode ] , case_id = case_id , domain = PACT_DOMAIN , build_id = build_id , module_id = module_id ) <EOL> class PactFormAPI ( DomainAPI ) : <EOL> xform_es = ReportXFormES ( PACT_DOMAIN ) <EOL> @ classmethod <EOL> def allowed_domain ( self , domain ) : <EOL> return PACT_DOMAIN <EOL> @ classmethod <EOL> def api_version ( cls ) : <EOL> return "<STR_LIT:1>" <EOL> @ classmethod <EOL> def api_name ( cls ) : <EOL> return "<STR_LIT>" <EOL> @ method_decorator ( httpdigest ) <EOL> @ method_decorator ( login_or_digest ) <EOL> def get ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> db = XFormInstance . get_db ( ) <EOL> couch_user = CouchUser . from_django_user ( self . request . user ) <EOL> username = couch_user . raw_username <EOL> if hasattr ( localsettings , '<STR_LIT>' ) : <EOL> username = getattr ( localsettings , '<STR_LIT>' ) ( username ) <EOL> offset = <NUM_LIT:0> <EOL> limit_count = <NUM_LIT:200> <EOL> total_count = <NUM_LIT:0> <EOL> query = { <EOL> "<STR_LIT>" : { <EOL> "<STR_LIT>" : { <EOL> "<STR_LIT>" : { <EOL> "<STR_LIT>" : [ <EOL> { "<STR_LIT>" : { "<STR_LIT>" : "<STR_LIT>" } } , <EOL> { "<STR_LIT>" : { "<STR_LIT>" : "<STR_LIT>" } } , <EOL> { "<STR_LIT>" : { "<STR_LIT>" : username } } <EOL> ] <EOL> } , <EOL> "<STR_LIT>" : { "<STR_LIT>" : { } } <EOL> } <EOL> } , <EOL> "<STR_LIT>" : { "<STR_LIT>" : "<STR_LIT>" } , <EOL> "<STR_LIT:size>" : limit_count , <EOL> "<STR_LIT>" : [ '<STR_LIT>' ] <EOL> } <EOL> query [ '<STR_LIT>' ] = { } <EOL> query [ '<STR_LIT>' ] . update ( pact_script_fields ( ) ) <EOL> query [ '<STR_LIT>' ] . update ( case_script_field ( ) ) <EOL> res = self . xform_es . run_query ( query ) <EOL> my_patients_ever_submitted_query = query_per_case_submissions_facet ( PACT_DOMAIN , username ) <EOL> patients_res = self . xform_es . run_query ( my_patients_ever_submitted_query ) <EOL> active_patients = [ ] <EOL> for pt in [ ] : <EOL> case_id = pt [ '<STR_LIT>' ] <EOL> active_patients . append ( case_id ) <EOL> def return_iterator ( ) : <EOL> yield "<STR_LIT>" <EOL> for result in res [ '<STR_LIT>' ] [ '<STR_LIT>' ] : <EOL> data_row = result [ '<STR_LIT>' ] <EOL> try : <EOL> xml_str = db . fetch_attachment ( data_row [ '<STR_LIT>' ] , '<STR_LIT>' ) . replace ( "<STR_LIT>" , '<STR_LIT>' ) . replace ( "<STR_LIT>" , '<STR_LIT>' ) <EOL> yield xml_str <EOL> except Exception , ex : <EOL> logging . error ( "<STR_LIT>" % ex ) <EOL> yield "<STR_LIT>" <EOL> response = HttpResponse ( return_iterator ( ) , content_type = '<STR_LIT>' ) <EOL> return response <EOL> def sub_element ( root , tag , val ) : <EOL> sube = etree . SubElement ( root , tag ) <EOL> sube . text = val <EOL> def generate_meta_block ( couch_user , instance_id = None , timestart = None , timeend = None ) : <EOL> if timestart is None : <EOL> timestart = datetime . utcnow ( ) <EOL> if timeend is None : <EOL> timeend = datetime . utcnow ( ) <EOL> if instance_id is None : <EOL> instance_id = uuid . uuid4 ( ) . hex <EOL> meta_nsmap = { '<STR_LIT>' : '<STR_LIT>' } <EOL> meta_lxml = etree . Element ( "<STR_LIT>" % meta_nsmap [ '<STR_LIT>' ] , nsmap = meta_nsmap ) <EOL> sub_element ( meta_lxml , '<STR_LIT>' % meta_nsmap [ '<STR_LIT>' ] , '<STR_LIT>' ) <EOL> sub_element ( meta_lxml , '<STR_LIT>' % meta_nsmap [ '<STR_LIT>' ] , couch_user . get_id ) <EOL> sub_element ( meta_lxml , '<STR_LIT>' % meta_nsmap [ '<STR_LIT>' ] , timestart . strftime ( '<STR_LIT>' ) ) <EOL> sub_element ( meta_lxml , '<STR_LIT>' % meta_nsmap [ '<STR_LIT>' ] , timeend . strftime ( '<STR_LIT>' ) ) <EOL> sub_element ( meta_lxml , '<STR_LIT>' % meta_nsmap [ '<STR_LIT>' ] , instance_id ) <EOL> return meta_lxml <EOL> def prepare_case_update_xml_block ( casedoc , couch_user , update_dict , submit_date ) : <EOL> case_nsmap = { '<STR_LIT>' : '<STR_LIT>' } <EOL> def make_update ( update_elem , updates ) : <EOL> for k , v in updates . items ( ) : <EOL> if v is not None : <EOL> sub_element ( update_elem , '<STR_LIT>' % { '<STR_LIT>' : case_nsmap [ '<STR_LIT>' ] , '<STR_LIT>' : k } , v ) <EOL> case_lxml = etree . Element ( '<STR_LIT>' % case_nsmap [ '<STR_LIT>' ] , nsmap = case_nsmap , case_id = casedoc . _id , user_id = couch_user . _id , date_modified = submit_date . strftime ( "<STR_LIT>" ) ) <EOL> update_lxml = etree . SubElement ( case_lxml , '<STR_LIT>' % case_nsmap [ '<STR_LIT>' ] ) <EOL> make_update ( update_lxml , update_dict ) <EOL> return case_lxml <EOL> def recompute_dots_casedata ( casedoc , couch_user , submit_date = None , sync_token = None ) : <EOL> """<STR_LIT>""" <EOL> if getattr ( casedoc , '<STR_LIT>' , None ) in [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] : <EOL> update_dict = { } <EOL> dots_data = get_dots_case_json ( casedoc ) <EOL> update_dict [ '<STR_LIT>' ] = json . dumps ( dots_data ) <EOL> submit_case_update_form ( casedoc , update_dict , couch_user , submit_date = submit_date , xmlns = XMLNS_PATIENT_UPDATE_DOT , sync_token = sync_token ) <EOL> def submit_case_update_form ( casedoc , update_dict , couch_user , submit_date = None , xmlns = XMLNS_PATIENT_UPDATE , sync_token = None ) : <EOL> """<STR_LIT>""" <EOL> if submit_date is None : <EOL> submit_date = datetime . utcnow ( ) <EOL> form = etree . Element ( "<STR_LIT:data>" , nsmap = { None : xmlns , '<STR_LIT>' : "<STR_LIT>" } ) <EOL> meta_block = generate_meta_block ( couch_user , timestart = submit_date , timeend = submit_date ) <EOL> form . append ( meta_block ) <EOL> update_block = prepare_case_update_xml_block ( casedoc , couch_user , update_dict , submit_date ) <EOL> form . append ( update_block ) <EOL> encounter_date = etree . XML ( '<STR_LIT>' % json_format_date ( datetime . utcnow ( ) ) ) <EOL> form . append ( encounter_date ) <EOL> submission_xml_string = etree . tostring ( form ) <EOL> if sync_token : <EOL> extra_meta = { LAST_SYNCTOKEN_HEADER : sync_token } <EOL> else : <EOL> extra_meta = None <EOL> return submit_xform ( '<STR_LIT>' , PACT_DOMAIN , submission_xml_string , extra_meta = extra_meta ) <EOL> def get_all_providers ( invalidate = False ) : <EOL> """<STR_LIT>""" <EOL> if invalidate : <EOL> cache . delete ( PACT_PROVIDERS_FIXTURE_CACHE_KEY ) <EOL> raw_cached_fixtures = cache . get ( PACT_PROVIDERS_FIXTURE_CACHE_KEY , None ) <EOL> if raw_cached_fixtures is None : <EOL> pact_hp_group = Group . by_name ( PACT_DOMAIN , PACT_HP_GROUPNAME ) <EOL> providers = FixtureDataItem . by_group ( pact_hp_group ) <EOL> cache . set ( PACT_PROVIDERS_FIXTURE_CACHE_KEY , json . dumps ( [ x . to_json ( ) for x in providers ] ) ) <EOL> return providers <EOL> else : <EOL> try : <EOL> json_data = json . loads ( raw_cached_fixtures ) <EOL> return [ FixtureDataItem . wrap ( x ) for x in json_data ] <EOL> except Exception , ex : <EOL> logging . error ( "<STR_LIT>" % ( PACT_PROVIDERS_FIXTURE_CACHE_KEY , ex ) ) <EOL> return [ ] <EOL> pass <EOL> class PactAPI ( DomainAPI ) : <EOL> @ classmethod <EOL> def allowed_domain ( self , domain ) : <EOL> return PACT_DOMAIN <EOL> @ classmethod <EOL> def api_version ( cls ) : <EOL> return "<STR_LIT:1>" <EOL> @ classmethod <EOL> def api_name ( cls ) : <EOL> return "<STR_LIT>" <EOL> http_method_names = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , ] <EOL> def get ( self , * args , ** kwargs ) : <EOL> from pact . models import PactPatientCase <EOL> if self . request . GET . get ( '<STR_LIT>' , None ) is None : <EOL> raise Http404 <EOL> case = PactPatientCase . get ( self . request . GET [ '<STR_LIT>' ] ) <EOL> if self . method is None : <EOL> return HttpResponse ( "<STR_LIT>" , status = <NUM_LIT> ) <EOL> elif self . method == "<STR_LIT>" : <EOL> scheds = case . get_schedules ( raw_json = True ) <EOL> if scheds is None : <EOL> scheds = [ ] <EOL> payload = json . dumps ( scheds ) <EOL> response = HttpResponse ( payload , content_type = "<STR_LIT:application/json>" ) <EOL> return response <EOL> elif self . method == '<STR_LIT>' : <EOL> providers = get_all_providers ( ) <EOL> providers = sorted ( providers , key = lambda x : x . fields_without_attributes [ '<STR_LIT>' ] ) <EOL> providers_by_id = dict ( <EOL> ( x . fields_without_attributes [ '<STR_LIT:id>' ] , x . fields_without_attributes ) <EOL> for x in providers <EOL> ) <EOL> case_providers = [ providers_by_id . get ( x , None ) for x in case . get_provider_ids ( ) ] <EOL> facilities = set ( ) <EOL> for prov in providers : <EOL> facility = prov . fields_without_attributes [ '<STR_LIT>' ] <EOL> if facility is None : <EOL> facility = '<STR_LIT>' <EOL> facilities . add ( facility ) <EOL> ret = { <EOL> '<STR_LIT>' : [ '<STR_LIT>' ] + sorted ( list ( facilities ) ) , <EOL> "<STR_LIT>" : [ x . fields_without_attributes for x in providers ] , <EOL> "<STR_LIT>" : case_providers , <EOL> } <EOL> resp = HttpResponse ( json . dumps ( ret ) , content_type = '<STR_LIT:application/json>' ) <EOL> return resp <EOL> else : <EOL> return HttpResponse ( "<STR_LIT>" , status = <NUM_LIT> ) <EOL> def post ( self , * args , ** kwargs ) : <EOL> from pact . models import PactPatientCase , CDotWeeklySchedule <EOL> pdoc = PactPatientCase . get ( self . request . GET [ '<STR_LIT>' ] ) <EOL> resp = HttpResponse ( ) <EOL> if self . method == "<STR_LIT>" : <EOL> if self . request . POST . has_key ( '<STR_LIT>' ) : <EOL> pdoc . rm_last_schedule ( ) <EOL> pdoc . save ( ) <EOL> resp . status_code = <NUM_LIT> <EOL> return resp <EOL> elif self . method == "<STR_LIT>" : <EOL> form = ScheduleForm ( data = self . request . POST ) <EOL> if form . is_valid ( ) : <EOL> sched = CDotWeeklySchedule ( ) <EOL> for day in DAYS_OF_WEEK : <EOL> if form . cleaned_data [ day ] != '<STR_LIT:None>' : <EOL> setattr ( sched , day , form . cleaned_data [ day ] ) <EOL> if form . cleaned_data [ '<STR_LIT>' ] == None : <EOL> sched . started = datetime . utcnow ( ) <EOL> else : <EOL> sched . started = datetime . combine ( form . cleaned_data [ '<STR_LIT>' ] , time . min ) <EOL> sched . comment = form . cleaned_data [ '<STR_LIT>' ] <EOL> sched . created_by = self . request . user . username <EOL> sched . deprecated = False <EOL> pdoc . set_schedule ( sched ) <EOL> pdoc . save ( ) <EOL> set_schedule_case_properties ( pdoc ) <EOL> resp . status_code = <NUM_LIT> <EOL> return resp <EOL> else : <EOL> resp . write ( str ( form . errors ) ) <EOL> resp . status_code = <NUM_LIT> <EOL> return resp <EOL> elif self . method == '<STR_LIT>' : <EOL> try : <EOL> submitted_provider_ids = json . loads ( self . request . POST [ '<STR_LIT>' ] ) <EOL> case_provider_ids = list ( pdoc . get_provider_ids ( ) ) <EOL> if submitted_provider_ids != case_provider_ids : <EOL> try : <EOL> submitted_len = len ( submitted_provider_ids ) <EOL> case_len = len ( case_provider_ids ) <EOL> if submitted_len < case_len : <EOL> for x in range ( case_len - submitted_len ) : <EOL> submitted_provider_ids . append ( '<STR_LIT>' ) <EOL> pdoc . update_providers ( self . request . couch_user , submitted_provider_ids ) <EOL> resp . write ( "<STR_LIT:success>" ) <EOL> resp . status_code = <NUM_LIT> <EOL> except Exception , ex : <EOL> resp . write ( "<STR_LIT>" % ex ) <EOL> resp . status_code = <NUM_LIT> <EOL> else : <EOL> resp . write ( "<STR_LIT>" ) <EOL> resp . status_code = <NUM_LIT> <EOL> except Exception , ex : <EOL> resp . write ( "<STR_LIT>" % ex ) <EOL> resp . status_code = <NUM_LIT> <EOL> return resp <EOL> elif self . method == "<STR_LIT>" : <EOL> form = PactPatientForm ( self . request , pdoc , data = self . request . POST ) <EOL> if form . is_valid ( ) : <EOL> update_data = form . clean_changed_data <EOL> submit_case_update_form ( pdoc , update_data , self . request . couch_user ) <EOL> resp . status_code = <NUM_LIT> <EOL> return resp <EOL> else : <EOL> resp . write ( str ( form . errors ) ) <EOL> resp . status_code = <NUM_LIT> <EOL> return resp <EOL> def head ( self , * args , ** kwargs ) : <EOL> raise NotImplementedError ( "<STR_LIT>" ) <EOL> @ method_decorator ( login_or_digest ) <EOL> def dispatch ( self , * args , ** kwargs ) : <EOL> req = args [ <NUM_LIT:0> ] <EOL> self . method = req . GET . get ( '<STR_LIT>' , None ) <EOL> ret = super ( PactAPI , self ) . dispatch ( * args , ** kwargs ) <EOL> return ret </s>
