Entry 3272

stuff

   

Submitted by anonymous on March 1, 2010 at 3:23 p.m.
Language: Python. Code size: 10.6 KB.

class ManualCaseElement(XsltElement):
    content = ContentInfo.Template
    legalAttrs = {
        'registerServiceURI' : AttributeInfo.UriReferenceAvt(
            required=1, description="The URI of the integration engine to direct MRN registration requests to"),        
        'backfillServiceURI' : AttributeInfo.UriReferenceAvt(
            required=1, description="The URI of the integration engine to direct backfill requests to"),        
        'directory' : AttributeInfo.UriReferenceAvt(
            required=1, description="The directory on the local system to use as a workspace"),        
        'user' : AttributeInfo.StringAvt(
            required=1, description="The repository username for the target server"),
        'password' : AttributeInfo.StringAvt(
            required=1, description="The password associated with the repository username for the target server"),
        'dataFeedRegistry' : AttributeInfo.StringAvt(
            required=1, description="A path (in this repository) to the data feed registry"),
        'host' : AttributeInfo.StringAvt(
            required=1, description="The hostname of the target server"),
        'port' : AttributeInfo.StringAvt(
            required=0, description="The RPC port of the target server",default='8803'),
        'ccfId' : AttributeInfo.StringAvt(
            required=1, description="The case identifier (CCFID of the patient involved)"),
        'patientName' : AttributeInfo.StringAvt(
            required=1, description="Patient's name"),
        'caseDateTime' : AttributeInfo.StringAvt(
            required=1, description="The date/time of the case"),
        'physicianID' : AttributeInfo.StringAvt(
            required=1, description="The identifier of the physician"),
        'physicianName' : AttributeInfo.StringAvt(
            required=1, description="The name of the physician"),
        'procedure' : AttributeInfo.StringAvt(
            required=0, description="The procedure performed (summary)"),
    }

    def instantiate(self, context, processor):
        context.setProcessState(self)
        repo               = context.processor._repository
        directory          = self._directory.evaluate(context)
        user               = self._user.evaluate(context)
        password           =  self._password.evaluate(context)
        host               = self._host.evaluate(context)
        registry           = self._dataFeedRegistry.evaluate(context)
        ccfId              = self._ccfId.evaluate(context)        
        patientName        = self._patientName.evaluate(context)        
        caseDate           = self._caseDateTime.evaluate(context)
        physicianID        = self._physicianID.evaluate(context)
        physicianName      = self._physicianName.evaluate(context)
        procedure          = self._procedure.evaluate(context)
        registerServiceURI = self._registerServiceURI.evaluate(context)
        backfillServiceURI = self._backfillServiceURI.evaluate(context)
        
        print "Changing to directory ", directory
        os.chdir(directory)
        
        #Create cooresponding case document keyed off manual entry
        generatedId = str(UuidAsString(GenerateUuid()))
        uriPrefix = ('tag:info@semanticdb.ccf.org,' + date.today().isoformat() +':OPTimeCase:')
        uri = unicode(uriPrefix + generatedId)
        
        doc = amara.create_document()
        root=doc.xml_create_element(
              u"SurgicalCase",
              ns=OLD_CASE_NS,
              attributes={
                u'uri':uri,
              }
        )
        #stubs
        root.xml_append(doc.xml_create_element(u'state',ns=OLD_CASE_NS,content=u'abstraction-precoding'))
        # root.xml_append(doc.xml_create_element(u'patientLocation',ns=OLD_CASE_NS,content=u'unknown'))
        root.xml_append(doc.xml_create_element(u'precoders',ns=OLD_CASE_NS))
        root.xml_append(doc.xml_create_element(u'abstractors',ns=OLD_CASE_NS))
        # root.xml_append(doc.xml_create_element(u'bedSpace',ns=OLD_CASE_NS))
        root.xml_append(doc.xml_create_element(u'note',ns=OLD_CASE_NS))        
        root.xml_append(doc.xml_create_element(u'patientName',
                                               ns=OLD_CASE_NS,
                                               content=patientName))
        root.xml_append(doc.xml_create_element(u'surgeon',ns=OLD_CASE_NS,
                                               content=physicianName))
        root.xml_append(doc.xml_create_element(u'date',ns=OLD_CASE_NS,content=caseDate))
        root.xml_append(doc.xml_create_element(u'ccfId',ns=OLD_CASE_NS,content=ccfId))
        root.xml_append(doc.xml_create_element(u'procedure',ns=OLD_CASE_NS,
                                               content=procedure))
        root.xml_append(doc.xml_create_element(u'surgeonID',ns=OLD_CASE_NS,
                                               content=physicianID))
        
        print "New case xml: ", root.xml(indent=True)
        
        doc.xml_append(root)     

        caseDateOnly=caseDate.split('T')[0]
        prefix=caseDateOnly+'_'+ccfId
           
        updateRecordPath  = '/SemanticDB/CaseManagement/update-queue/%s_%s.xml'%(ccfId,generatedId)
        updateXUpdatePath = '/SemanticDB/CaseManagement/update-queue/%s_%s.xupdate'%(ccfId,generatedId)
        
        moveIn = False
        #Check if historical document exists in repository    
        if not repo.hasResource('/SemanticDB/CVIR/%s.xml'%ccfId):
            #This is a new patient, create minimal update-queue artifacts
            newDoc=createNewRecord(doc,directory)            
            print "New patient, creating %s"%updateRecordPath
            repo.createDocument(updateRecordPath,newDoc.xml(indent=True))

            newUpdateDoc = amara.create_document()
            root=newUpdateDoc.xml_create_element(
                    u"xu:modifications",
                    attributes={
                        u'version':u"1.0",
                        (u'ptrec:dummy',u'tag:info@semanticdb.ccf.org,2007:PatientRecordTerms#'):u'',
                    },
                    ns=XUPDATE_NS
            )
            appendRoot=newUpdateDoc.xml_create_element(
                u'xu:append',
                ns=XUPDATE_NS,
                attributes={
                  u'select':u'/ptrec:PatientRecord',
                }
            )
            newUpdateDoc.xml_append(root)
            root.xml_append(appendRoot)
            appendRoot.xml_append(newDoc.PatientRecord.Event)
            repo.createDocument(updateXUpdatePath,newUpdateDoc.xml(indent=True))
            print "### Created %s and %s ###"%(updateRecordPath,updateXUpdatePath) 
            
            registryRes = repo.fetchResource(registry)
            for feed in registryRes.asDom().xpath('//DataFeed'):
                name=feed.xpath('string(@name)')
                program=feed.xpath('string(@program)')
                interpreter=feed.xpath('string(@interpreter)')
                print "### Launching external data feed: %s (%s), case document update ###"%(name,program)    
                #Check to ensure the caseDate is formatted correctly 
                FromISO8601(caseDate)
                dtPortion = caseDate[:10]
                args = [interpreter, program, dtPortion.replace('-',''),ccfId,DEFAULT_WORKSPACE]
                os.spawnvp(os.P_WAIT,interpreter,args)
                xupdatePath = os.path.join(DEFAULT_WORKSPACE,'%s.xupdate'%ccfId)
                primaryRecordPath = '/SemanticDB/CVIR/%s.xml'%ccfId
                if os.path.exists(xupdatePath):
                    updateDataFeed(ccfId,xupdatePath,generatedId,newUpdateDoc)
                else:
                    print "### No data downloaded for %s/%s (date/ccfId): %s ###"%(caseDate,ccfId,xupdatePath)
                        
        else:
            #This is for an existing patient, so we want to bypass the new case list,
            #update the record, and move the case into the unassigned precoder list
            moveIn = True
            print "Existing patient, updating %s"%'/SemanticDB/CVIR/%s.xml'%ccfId
            patientRecordObj = repo.fetchResource('/SemanticDB/CVIR/%s.xml'%ccfId)
            ptRec = amara.parse(patientRecordObj.getContent())
            appendNewRecord(ptRec,doc)
            patientRecordObj.setContent(ptRec.xml(indent=True))
            print "### Updated /SemanticDB/CVIR/%s.xml with new case information ###"%(ccfId) 
        
        print "Moving case directly into unassigned precoding list?: ", moveIn
        if moveIn:
            caseFileName = '%s.case'%generatedId
            caseLiveDir = repo.fetchResource('/SemanticDB/CaseManagement/ConcurrentCases/live')
            proc = Processor.Processor()
            proc.appendStylesheet(InputSource.DefaultFactory.fromString(open('transformCaseDoc.xsl').read()))
            input = InputSource.DefaultFactory.fromString(root.xml(indent=True),
                                                          'urn:uuid:caseDocument')
            rt=proc.run(input)    
            caseLiveDir.createDocument(caseFileName,rt,docDef='/SemanticDB/CaseManagement/xslt/case2rdf.xsltdd')
        else:
            inboxRes = repo.fetchResource('/SemanticDB/CaseManagement/ConcurrentCases/inbox.xml')
            inboxCasesObj  = amara.parse(inboxRes.getContent(),prefixes={u'work': OLD_CASE_NS})
            appendCase(inboxCasesObj,doc)
            
            proc = Processor.Processor()
            proc.appendStylesheet(InputSource.DefaultFactory.fromString(open('transformCaseDoc.xsl').read()))
            input = InputSource.DefaultFactory.fromString(inboxCasesObj.xml(indent=True),
                                                          'urn:uuid:caseDocument')
            rt=proc.run(input)    
            inboxRes.setContent(rt)

def updateDataFeed(ccfId,xupdatePath,caseId,newUpdateDoc):
    """
    Merge incoming data from feed into skeletal record and primary record
    """
    #Update xupdate document
    try:
        externalXUpateDoc      = amara.parse(open(xupdatePath).read())        
        for xupOp in externalXUpateDoc.xml_xpath('/*/*'):
            newUpdateDoc.modifications.xml_append(xupOp)
        if CLEANUP:
            os.remove(xupdatePath)
    except Exception, e:
        import traceback, cStringIO
        st = cStringIO.StringIO()
        traceback.print_exc(file=st)
        error=st.getvalue()
        print error
        print ccfId, xupdatePath           
        print "Unable to communicate data feed XUpdate to the repository (for case: %s / %s)"%(caseId,ccfId)    

This snippet took 0.04 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).