Ejemplo n.º 1
0
def _linkUser(self, user):
    """Set the UID of the current Contact in the User properties and update
    all relevant own properties.
    """
    logger.warn("MONKEY PATCHING __linkUser")
    KEY = "linked_contact_uid"

    username = user.getId()
    contact = self.getContactByUsername(username)

    # User is linked to another contact (fix in UI)
    if contact and contact.UID() != self.UID():
        raise ValueError("User '{}' is already linked to Contact '{}'".format(
            username, contact.Title()))

    # User is linked to multiple other contacts (fix in Data)
    if isinstance(contact, list):
        raise ValueError(
            "User '{}' is linked to multiple Contacts: '{}'".format(
                username, ",".join(map(lambda x: x.Title(), contact))))

    # XXX: Does it make sense to "remember" the UID as a User property?
    tool = user.getTool()
    try:
        user.getProperty(KEY)
    except ValueError:
        logger.info("Adding User property {}".format(KEY))
        tool.manage_addProperty(KEY, "", "string")

    # Set the UID as a User Property
    uid = self.UID()
    user.setMemberProperties({KEY: uid})
    logger.info("Linked Contact UID {} to User {}".format(
        user.getProperty(KEY), username))

    # Set the Username
    self.setUsername(user.getId())

    # Update the Email address from the user
    self.setEmailAddress(user.getProperty("email"))

    # somehow the `getUsername` index gets out of sync
    self.reindexObject()

    # N.B. Local owner role and client group applies only to client
    #      contacts, but not lab contacts.
    if IClient.providedBy(self.aq_parent):
        # Grant local Owner role
        self._addLocalOwnerRole(username)
        # Add user to "Clients" group
        self._addUserToGroup(username, group="Clients")

        # SENAITE.HEALTH-specific!
        # Add user to "InternalClients" group
        if is_internal_client(self.aq_parent):
            self._addUserToGroup(username, group="InternalClients")

    return True
Ejemplo n.º 2
0
 def Import(self):
     print "EOOO"
     s_t = ''
     c_t = 'lab'
     bucket = {}
     pc = getToolByName(self.context, 'portal_catalog')
     bsc = getToolByName(self.context, 'bika_setup_catalog')
     # collect up all values into the bucket
     for row in self.get_rows(3):
         c_t = row['Client_title'] if row['Client_title'] else 'lab'
         if c_t not in bucket:
             bucket[c_t] = {}
         s_t = row['SampleType_title'] if row['SampleType_title'] else s_t
         if s_t not in bucket[c_t]:
             bucket[c_t][s_t] = []
         service = bsc(portal_type='AnalysisService', title=row['service'])
         if not service:
             service = bsc(portal_type='AnalysisService',
                           getKeyword=row['service'])
         try:
             service = service[0].getObject()
             bucket[c_t][s_t].append({
             'keyword': service.getKeyword(),
             'min': row.get('min','0'),
             'max': row.get('max','0'),
             'minpanic': row.get('minpanic','0'),
             'maxpanic': row.get('maxpanic','0'),
             'error': row.get('error','0'),
             })
         except IndexError:
             warning = "Error with service name %s on sheet %s. Service not uploaded."
             logger.warning(warning, row.get('service', ''), self.sheetname)
     # write objects.
     for c_t in bucket:
         if c_t == 'lab':
             folder = self.context.bika_setup.bika_analysisspecs
         else:
             folder = pc(portal_type='Client', title=c_t)
             if (not folder or len(folder) != 1):
                 logger.warn("Client %s not found. Omiting client specifications." % c_t)
                 continue
             folder = folder[0].getObject()
         for s_t in bucket[c_t]:
             resultsrange = bucket[c_t][s_t]
             sampletype = bsc(portal_type='SampleType', title=s_t)[0]
             _id = folder.invokeFactory('AnalysisSpec', id=tmpID())
             obj = folder[_id]
             obj.edit(
                 title=sampletype.Title,
                 ResultsRange=resultsrange)
             obj.setSampleType(sampletype.UID)
             obj.unmarkCreationFlag()
             renameAfterCreation(obj)
Ejemplo n.º 3
0
def set_field_value(instance, field_name, value):
    """Sets the value to a Schema field
    """
    if field_name == "id":
        logger.warn("Assignment of id is not allowed")
        return
    logger.info("Field {} = {}".format(field_name, repr(value)))
    instance = api.get_object(instance)
    field = instance.Schema() and instance.Schema().getField(field_name) or None
    if not field:
        api.fail("No field {} found for {}".format(field_name, repr(instance)))
    field.set(instance, value)
Ejemplo n.º 4
0
def translate_i18n(i18n_msg):
    """Safely translate and convert to UTF8, any zope i18n msgid returned from
    senaite health's message factory
    """
    text = to_unicode(i18n_msg)
    try:
        request = api.get_request()
        domain = getattr(i18n_msg, "domain", "senaite.health")
        text = translate(text, domain=domain, context=request)
    except UnicodeDecodeError:
        logger.warn("{} couldn't be translated".format(text))
    return to_utf8(text)
Ejemplo n.º 5
0
    def get_portal_type(self, query):
        """Return the portal type from the query passed-in
        """
        portal_types = self.get_portal_types(query)
        if not portal_types:
            logger.warn("No portal types: {}".format(repr(portal_types)))
            return None

        if len(portal_types) > 1:
            logger.warn("Multiple portal types: {}".format(repr(portal_types)))
            return None

        return portal_types[0]
Ejemplo n.º 6
0
def update_workflow(workflow_id, settings):
    logger.info("Updating workflow '{}' ...".format(workflow_id))
    wf_tool = api.get_tool("portal_workflow")
    workflow = wf_tool.getWorkflowById(workflow_id)
    if not workflow:
        logger.warn("Workflow '{}' not found [SKIP]".format(workflow_id))
    states = settings.get("states", {})
    for state_id, values in states.items():
        update_workflow_state(workflow, state_id, values)

    transitions = settings.get("transitions", {})
    for transition_id, values in transitions.items():
        update_workflow_transition(workflow, transition_id, values)
Ejemplo n.º 7
0
    def __call__(self):
        plone.protect.CheckAuthenticator(self.request)
        PatientUID = self.request.get('PatientUID', '')
        PatientID = self.request.get('PatientID', '')
        ret = {
            'PatientID': '',
            'PatientUID': '',
            'ClientPatientID': '',
            'ClientID': '',
            'ClientUID': '',
            'ClientTitle': '',
            'ClientSysID': '',
            'PatientFullname': '',
            'PatientBirthDate': '',
            'PatientGender': 'dk',
            'PatientMenstrualStatus': ''
        }

        proxies = None
        if PatientUID:
            try:
                bpc = getToolByName(self.context, CATALOG_PATIENTS)
                proxies = bpc(UID=PatientUID)
            except ParseError:
                pass
        elif PatientID:
            logger.warn("Search of Patient by ID!!!")
            try:
                bpc = getToolByName(self.context, CATALOG_PATIENTS)
                proxies = bpc(id=PatientID)
            except ParseError:
                pass

        if not proxies:
            return json.dumps(ret)
        patient = proxies[0]
        ret = {
            'PatientID': patient.getPatientID,
            'PatientUID': patient.UID,
            'ClientPatientID': patient.getClientPatientID,
            'ClientUID': patient.getPrimaryReferrerUID,
            'ClientTitle': patient.getPrimaryReferrerTitle,
            'ClientSysID': patient.getPrimaryReferrerID,
            'PatientFullname': patient.Title,
            'PatientBirthDate': self.ulocalized_time(patient.getBirthDate),
            'PatientGender': patient.getGender,
            'PatientMenstrualStatus': patient.getMenstrualStatus
        }
        return json.dumps(ret)
Ejemplo n.º 8
0
def get_client_aware_html_image(obj):
    """Renders an icon based on the client the object belongs to
    """
    if is_from_external_client(obj):
        icon_info = ("lock.png", _("Private, from an external client"))

    elif is_from_internal_client(obj):
        if api.get_review_status(obj) == "shared":
            icon_info = ("share.png", _("Shared, from an internal client"))
        else:
            icon_info = ("share_lock.png",
                         _("From an internal client, but not shared"))
    else:
        logger.warn("No client assigned for {}".format(repr(obj)))
        icon_info = ("exclamation_red.png", _("No client assigned"))

    return get_html_image(icon_info[0], title=icon_info[1])
Ejemplo n.º 9
0
def _unlinkUser(self):
    """Remove the UID of the current Contact in the User properties and
    update all relevant own properties.
    """
    logger.warn("MONKEY PATCHING __unlinkUser")
    KEY = "linked_contact_uid"

    # Nothing to do if no user is linked
    if not self.hasUser():
        return False

    user = self.getUser()
    username = user.getId()

    # Unset the UID from the User Property
    user.setMemberProperties({KEY: ""})
    logger.info("Unlinked Contact UID from User {}".format(
        user.getProperty(KEY, "")))

    # Unset the Username
    self.setUsername(None)

    # Unset the Email
    self.setEmailAddress(None)

    # somehow the `getUsername` index gets out of sync
    self.reindexObject()

    # N.B. Local owner role and client group applies only to client
    #      contacts, but not lab contacts.
    if IClient.providedBy(self.aq_parent):
        # Revoke local Owner role
        self._delLocalOwnerRole(username)
        # Remove user from "Clients" group
        self._delUserFromGroup(username, group="Clients")

        # SENAITE.HEALTH-specific!
        # Remove user from "InternalClients" group
        if is_internal_client(self.aq_parent):
            self._delUserFromGroup(username, group="InternalClients")

    return True
Ejemplo n.º 10
0
def move_patients_to_clients(portal):
    """
    Moves patients with a Client assigned to the folder of the Client they
    belong to.
    """
    logger.info("Moving Patients inside Clients...")

    # We'll need this to update workflow mappings just after the move
    wf_tool = api.get_tool("portal_workflow")
    workflow = wf_tool.getWorkflowById("senaite_health_patient_workflow")

    # Allow Patient content type inside Clients
    allow_patients_inside_clients(portal)

    # Map patient uids against batches' clients
    patients_to_clients = dict()
    query = dict(portal_type="Batch")
    for batch_brain in api.search(query, BIKA_CATALOG):
        client_id = batch_brain.getClientID
        if not client_id:
            continue
        patient_uid = batch_brain.getPatientUID
        if not patient_uid:
            continue
        client_ids = patients_to_clients.get(patient_uid, [])
        client_ids.append(client_id)
        patients_to_clients[patient_uid] = list(set(client_ids))

    # Look through Patients and move them inside Clients
    start = time.time()
    clients_map = dict()
    patients_folder = portal.patients
    patients_origin = aq_inner(patients_folder)

    total = patients_folder.objectCount()
    for num, (p_id, patient) in enumerate(patients_folder.items()):
        if num and num % 100 == 0:
            end = time.time()
            logger.info(
                "Moving Patients inside Clients: {}/{}: ({:.2f}s)".format(
                    num, total, (end - start)))
            start = time.time()

        client_uid = patient.getField("PrimaryReferrer").getRaw(patient)
        if client_uid:
            # Update role mappings first (for workflow changes to take effect)
            workflow.updateRoleMappingsFor(patient)

            # Try to find out the Client from the Batch(es) assigned to patient
            client_ids = patients_to_clients.get(api.get_uid(patient), [])
            if len(client_ids) > 1:
                # Clinical Cases for this Patient belong to different clients,
                # so this Patient must remain not bound to any Client
                logger.warn("Patient with client assigned, but batches from "
                            "others: {}".format(p_id))

            else:
                client = clients_map.get(client_uid, None)
                if client is None:
                    client = api.get_object_by_uid(client_uid)
                    clients_map[client_uid] = client

                if client_ids and client_ids[0] != client.getClientID():
                    # Assigned client does not match with those from the batches
                    logger.warn(
                        "Patient with client assigned that does not "
                        "match with the client from batches: {}".format(p_id))

                else:
                    # Move Patient inside the client
                    #cp = patients_folder.manage_cutObjects(p_id)
                    #client.manage_pasteObjects(cp)
                    move_obj(patient, client)

    logger.info("Moving Patients inside Clients [DONE]")