示例#1
0
    def _apply_filter_by_client(self):
        # If the current context is a Client, filter Patients by Client UID
        if IClient.providedBy(self.context):
            client_uid = api.get_uid(self.context)
            self.contentFilter['getPrimaryReferrerUID'] = client_uid
            return

        # If the current user is a Client contact, filter the Patients in
        # accordance. For the rest of users (LabContacts), the visibility of
        # the patients depend on their permissions
        user = api.get_current_user()
        roles = user.getRoles()
        if 'Client' not in roles:
            return

        # Are we sure this a ClientContact?
        # May happen that this is a Plone member, w/o having a ClientContact
        # assigned or having a LabContact assigned... weird
        contact = api.get_user_contact(user)
        if not contact or ILabContact.providedBy(contact):
            return

        # Is the parent from the Contact a Client?
        client = api.get_parent(contact)
        if not client or not IClient.providedBy(client):
            return
        client_uid = api.get_uid(client)
        self.contentFilter['getPrimaryReferrerUID'] = client_uid
示例#2
0
    def _apply_filter_by_client(self):
        """
        If the user has the role Client, the user can not see batches
        from client objects he/she does not belong to.
        """
        # If the current context is a Client, filter Batches by Client UID
        if IClient.providedBy(self.context):
            client_uid = api.get_uid(self.context)
            self.contentFilter['getClientUID'] = client_uid
            return

        # If the current user is a Client contact, filter the Batches in
        # accordance. For the rest of users (LabContacts), the visibility of
        # the Batches depend on their permissions
        user = api.get_current_user()
        roles = user.getRoles()
        if 'Client' not in roles:
            return

        # Are we sure this a ClientContact?
        # May happen that this is a Plone member, w/o having a ClientContact
        # assigned or having a LabContact assigned... weird
        contact = api.get_user_contact(user)
        if not contact or ILabContact.providedBy(contact):
            return

        # Is the parent from the Contact a Client?
        client = api.get_parent(contact)
        if not client or not IClient.providedBy(client):
            return
        client_uid = api.get_uid(client)
        self.contentFilter['getClientUID'] = client_uid
示例#3
0
def get_client_from_chain(obj):
    """Returns the client the obj belongs to, if any, by looking to the
    acquisition chain
    """
    if IClient.providedBy(obj):
        return obj

    for obj in chain(obj):
        if IClient.providedBy(obj):
            return obj
    return None
示例#4
0
    def update(self):
        """Called before the listings renders
        """
        super(PatientsView, self).update()

        # Render the Add button. We need to do this here because patients live
        # inside site.patients folder
        self.context_actions = {}
        patients = api.get_portal().patients
        if security.check_permission(AddPatient, patients):
            self.context_actions = {
                _("Add"): {
                    "url": "createObject?type_name=Patient",
                    "icon": "++resource++bika.lims.images/add.png"}
            }

        # If the current user is a client contact, display those patients that
        # belong to same client or that do not belong to any client
        client = api.get_current_client()
        if client:
            query = dict(client_uid=[api.get_uid(client), "-1"])
            # We add UID "-1" to also include Patients w/o Client assigned
            self.contentFilter.update(query)
            for rv in self.review_states:
                rv["contentFilter"].update(query)

        # If the current context is a Client, remove the title column
        if IClient.providedBy(self.context):
            self.remove_column('getPrimaryReferrerTitle')
示例#5
0
def is_external_client(client):
    """Returns whether the client passed is an external client
    """
    if not IClient.providedBy(client):
        raise TypeError("Type not supported")

    return api.get_parent(client) == api.get_portal().clients
示例#6
0
 def Vocabulary_SampleType(self):
     vocabulary = CatalogVocabulary(self)
     vocabulary.catalog = 'bika_setup_catalog'
     folders = [self.bika_setup.bika_sampletypes]
     if IClient.providedBy(self.aq_parent):
         folders.append(self.aq_parent)
     return vocabulary(allow_blank=True, portal_type='SampleType')
示例#7
0
    def _initFormParams(self):
        mtool = getToolByName(self.context, 'portal_membership')
        addPortalMessage = self.context.plone_utils.addPortalMessage
        can_add_patients = mtool.checkPermission(AddPatient, self.context)

        if not can_add_patients and IClient.providedBy(self.context):
            # The user logged in is a Contact from this Client?
            # Tip: when a client contact is created, bika.lims assigns that
            # contact as the owner of the client, so he/she can access to the
            # Client he/she is owner of but not to the rest of Clients.
            # See bika.lims.browser.contact._link_user(userid)
            client = self.context
            owners = client.users_with_local_role('Owner')
            member = mtool.getAuthenticatedMember()
            can_add_patients = member.id in owners

        if can_add_patients:
            # TODO Performance tweak. Is this really needed?
            clients = self.context.clients.objectIds()
            if clients:
                add_patient_url = '{}/patients/createObject?type_name=Patient'\
                                  .format(self.portal_url)
                self.context_actions[_b('Add')] = {
                    'url': add_patient_url,
                    'icon': '++resource++bika.lims.images/add.png'
                }
            else:
                msg = _("Cannot create patients without any system clients "
                        "configured.")
                addPortalMessage(self.context.translate(msg))

        if mtool.checkPermission(ViewPatients, self.context):
            self.review_states[0]['transitions'].append({'id': 'deactivate'})
            self.review_states.append({
                'id': 'inactive',
                'title': _b('Dormant'),
                'contentFilter': {
                    'inactive_state': 'inactive'
                },
                'transitions': [
                    {
                        'id': 'activate'
                    },
                ],
                'columns': self.get_columns()
            })
            self.review_states.append({
                'id': 'all',
                'title': _b('All'),
                'contentFilter': {},
                'transitions': [
                    {
                        'id': 'empty'
                    },
                ],
                'columns': self.get_columns()
            })
            stat = self.request.get("%s_review_state" % self.form_id,
                                    'default')
            self.show_select_column = stat != 'all'
示例#8
0
    def update(self):
        """Called before the listings renders
        """
        super(PatientsView, self).update()

        # Render the Add button. We need to do this here because patients live
        # inside site.patients folder
        self.context_actions = {}
        patients = api.get_portal().patients
        if security.check_permission(AddPatient, patients):
            self.context_actions = {
                _("Add"): {
                    "url": "createObject?type_name=Patient",
                    "icon": "++resource++bika.lims.images/add.png"
                }
            }

        # If the current user is a client contact, display those patients that
        # belong to same client or that do not belong to any client
        client = api.get_current_client()
        if client:
            query = dict(client_uid=[api.get_uid(client), "-1"])
            # We add UID "-1" to also include Patients w/o Client assigned
            self.contentFilter.update(query)
            for rv in self.review_states:
                rv["contentFilter"].update(query)

        # If the current context is a Client, remove the title column
        if IClient.providedBy(self.context):
            self.remove_column('getPrimaryReferrerTitle')
示例#9
0
    def folderitems(self, **kwargs):
        items = super(ARImportsView, self).folderitems()
        for x in range(len(items)):
            if 'obj' not in items[x]:
                continue
            obj = items[x]['obj']
            items[x]['Title'] = obj.title_or_id()
            if items[x]['review_state'] == 'invalid':
                items[x]['replace']['Title'] = "<a href='%s/edit'>%s</a>" % (
                    obj.absolute_url(), items[x]['Title'])
            else:
                items[x]['replace']['Title'] = "<a href='%s/view'>%s</a>" % (
                    obj.absolute_url(), items[x]['Title'])
            items[x]['Creator'] = obj.Creator()
            items[x]['Filename'] = obj.getFilename()
            parent = obj.aq_parent
            items[x]['Client'] = parent if IClient.providedBy(parent) else ''
            items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % (
                parent.absolute_url(), parent.Title())
            items[x]['DateCreated'] = ulocalized_time(obj.created(),
                                                      long_format=True,
                                                      time_only=False,
                                                      context=obj)
            date = getTransitionDate(obj, 'validate')
            items[x]['DateValidated'] = date if date else ''
            date = getTransitionDate(obj, 'import')
            items[x]['DateImported'] = date if date else ''

        return items
    def folderitems(self, **kwargs):
        items = super(SampleImportsView, self).folderitems()
        for x in range(len(items)):
            if 'obj' not in items[x]:
                continue
            obj = items[x]['obj']
            # NOTE: Some about obj that returns the brains and not the object
            # it could be that folderitems has been changange on the listing
            # this is a hack for to make it work
            if api.is_brain(obj):
                obj = obj.getObject()
            # End of NOTE

            items[x]['Title'] = obj.title_or_id()
            if items[x]['review_state'] == 'invalid':
                items[x]['replace']['Title'] = "<a href='%s/edit'>%s</a>" % (
                    obj.absolute_url(), items[x]['Title'])
            else:
                items[x]['replace']['Title'] = "<a href='%s/view'>%s</a>" % (
                    obj.absolute_url(), items[x]['Title'])
            items[x]['Creator'] = obj.Creator()
            items[x]['Filename'] = obj.getFilename()
            parent = obj.aq_parent
            items[x]['Client'] = parent if IClient.providedBy(parent) else ''
            items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % (
                parent.absolute_url(), parent.Title())
            items[x]['DateCreated'] = ulocalized_time(
                obj.created(), long_format=True, time_only=False, context=obj)
            date = getTransitionDate(obj, 'validate')
            items[x]['DateValidated'] = date if date else ''
            date = getTransitionDate(obj, 'import')
            items[x]['DateImported'] = date if date else ''

        return items
示例#11
0
    def update(self):
        """Before template render hook
        """
        super(BatchFolderContentsView, self).update()

        if self.context.portal_type == "BatchFolder":
            self.request.set("disable_border", 1)

        # By default, only users with AddBatch permissions for the current
        # context can add batches.
        self.context_actions = {
            _("Add"): {
                "url": "createObject?type_name=Batch",
                "permission": AddBatch,
                "icon": "++resource++bika.lims.images/add.png"
            }
        }

        # If current user is a client contact and current context is not a
        # Client, then modify the url for Add action so the Batch gets created
        # inside the Client object to which the current user belongs. The
        # reason is that Client contacts do not have privileges to create
        # Batches inside portal/batches
        if not IClient.providedBy(self.context):
            # Get the client the current user belongs to
            client = api.get_current_client()
            if client and check_permission(AddBatch, client):
                add_url = self.context_actions[_("Add")]["url"]
                add_url = "{}/{}".format(api.get_url(client), add_url)
                self.context_actions[_("Add")]["url"] = add_url
                del (self.context_actions[_("Add")]["permission"])
示例#12
0
    def folderitems(self, **kwargs):
        items = super(ARImportsView, self).folderitems()
        for x in range(len(items)):
            if 'obj' not in items[x]:
                continue
            obj = items[x]['obj']
            items[x]['Title'] = obj.title_or_id()
            if items[x]['review_state'] == 'invalid':
                items[x]['replace']['Title'] = "<a href='%s/edit'>%s</a>" % (
                    obj.absolute_url(), items[x]['Title'])
            else:
                items[x]['replace']['Title'] = "<a href='%s/view'>%s</a>" % (
                    obj.absolute_url(), items[x]['Title'])
            items[x]['Creator'] = obj.Creator()
            items[x]['Filename'] = obj.getFilename()
            parent = obj.aq_parent
            items[x]['Client'] = parent if IClient.providedBy(parent) else ''
            items[x]['replace']['Client'] = "<a href='%s'>%s</a>" % (
                parent.absolute_url(), parent.Title())
            items[x]['DateCreated'] = ulocalized_time(
                obj.created(), long_format=True, time_only=False, context=obj)
            date = getTransitionDate(obj, 'validate')
            items[x]['DateValidated'] = date if date else ''
            date = getTransitionDate(obj, 'import')
            items[x]['DateImported'] = date if date else ''

        return items
示例#13
0
    def __call__(self, context):

        if IClient.providedBy(context):
            return context

        # Try to get the client from selected Batch
        batch = BatchDefaultFieldValue(self.request)(context)
        client = batch and batch.getClient() or None
        if client:
            return client

        # Try to get the client from selected Patient
        patient = PatientDefaultFieldValue(self.request)(context)
        client = patient and patient.getClient() or None
        if client:
            return client

        # Try to get the client from selected Doctor
        doctor = DoctorDefaultFieldValue(self.request)(context)
        client = doctor and doctor.getPrimaryReferrer() or None
        if client:
            return client

        # Try with client object explicitly defined in request
        return self.get_object_from_request_field("Client")
示例#14
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
示例#15
0
    def getClient(self):
        """Returns the Client the object is bound to, if any
        """
        # Look in the acquisition chain
        for obj in chain(self):
            if IClient.providedBy(obj):
                return obj

        # Look in Schema
        client_field = self.Schema().get("Client", default=None)
        if client_field:
            client = client_field.get(self)
            client = api.get_object(client, None)
            if client and IClient.providedBy(client):
                return client

        # No client bound
        return None
示例#16
0
 def get_client_uid(self):
     instance = self.context.aq_parent
     while not IPloneSiteRoot.providedBy(instance):
         if IClient.providedBy(instance):
             return instance.UID()
         if IBatch.providedBy(instance):
             client = instance.getClient()
             if client:
                 return client.UID()
示例#17
0
 def get_client_uid(self):
     instance = self.context.aq_parent
     while not IPloneSiteRoot.providedBy(instance):
         if IClient.providedBy(instance):
             return instance.UID()
         if IBatch.providedBy(instance):
             client = instance.getClient()
             if client:
                 return client.UID()
示例#18
0
    def get_current_client(self):
        """Returns the current client
        """
        client = api.get_current_client()
        if client:
            return client

        if IClient.providedBy(self.context):
            return self.context
        return None
示例#19
0
    def folderitem(self, obj, item, index):
        obj = api.get_object(obj)
        item["Description"] = obj.Description()
        item["replace"]["Title"] = get_link(item["url"], item["Title"])

        parent = api.get_parent(obj)
        if IClient.providedBy(parent):
            item["Owner"] = api.get_title(parent)
        else:
            item["Owner"] = self.context.bika_setup.laboratory.Title()
        return item
示例#20
0
 def getClient(self):
     """Returns the client the Doctor is assigned to, if any
     """
     # The schema's field PrimaryReferrer is only used to allow the user to
     # assign the doctor to a client in edit form. The entered value is used
     # in ObjectModifiedEventHandler to move the doctor to the Client's
     # folder, so the value stored in the Schema's is not used anymore
     # See https://github.com/senaite/senaite.core/pull/152
     client = self.aq_parent
     if IClient.providedBy(client):
         return client
     return None
示例#21
0
 def getClient(self):
     """ Retrieves the Client for which the current Batch is attached to
         Tries to retrieve the Client from the Schema property, but if not
         found, searches for linked ARs and retrieve the Client from the
         first one. If the Batch has no client, returns None.
     """
     client = self.Schema().getField('Client').get(self)
     if client:
         return client
     client = self.aq_parent
     if IClient.providedBy(client):
         return client
示例#22
0
 def __call__(self):
     plone.protect.CheckAuthenticator(self.request)
     curr_user = api.get_current_user()
     contact = api.get_user_contact(curr_user, contact_types=['Contact'])
     parent = contact and contact.getParent() or None
     if parent and not IClient.providedBy(parent):
         parent = None
     ret = {'ClientTitle': parent and parent.Title() or '',
            'ClientID': parent and parent.getClientID() or '',
            'ClientSysID': parent and parent.id or '',
            'ClientUID': parent and parent.UID() or '',}
     return json.dumps(ret)
示例#23
0
 def getClient(self):
     """ Retrieves the Client for which the current Batch is attached to
         Tries to retrieve the Client from the Schema property, but if not
         found, searches for linked ARs and retrieve the Client from the
         first one. If the Batch has no client, returns None.
     """
     client = self.Schema().getField('Client').get(self)
     if client:
         return client
     client = self.aq_parent
     if IClient.providedBy(client):
         return client
示例#24
0
 def __call__(self):
     plone.protect.CheckAuthenticator(self.request)
     curr_user = api.get_current_user()
     contact = api.get_user_contact(curr_user, contact_types=['Contact'])
     parent = contact and contact.getParent() or None
     if parent and not IClient.providedBy(parent):
         parent = None
     ret = {'ClientTitle': parent and parent.Title() or '',
            'ClientID': parent and parent.getClientID() or '',
            'ClientSysID': parent and parent.id or '',
            'ClientUID': parent and parent.UID() or '',}
     return json.dumps(ret)
示例#25
0
 def getClient(self):
     """Retrieves the Client the current Batch is assigned to
     """
     # We override here getClient from ClientAwareMixin because te schema's
     # field Client is only used to allow the user to assign the batch to a
     # client in edit form. The entered value is used in
     # ObjectModifiedEventHandler to move the batch to the Client's folder,
     # so the value stored in the Schema's is not used anymore
     # See https://github.com/senaite/senaite.core/pull/1450
     client = self.aq_parent
     if IClient.providedBy(client):
         return client
     return None
示例#26
0
 def get_client_from_query(self, query, purge=False):
     """Resolves the client from the query passed-in
     """
     keys = ["getPrimaryReferrerUID", "getClientUID", "getParentUID", "UID"]
     for key in keys:
         uid = query.get(key)
         if not api.is_uid(uid) or uid == "0":
             continue
         client = api.get_object_by_uid(uid)
         if IClient.providedBy(client):
             if purge:
                 # Remove the key:value from the query
                 del (query[key])
             return client
     return None
示例#27
0
    def __call__(self, context, mode, field, default):
        state = default if default else 'hidden'
        fieldName = field.getName()
        if fieldName != 'Client':
            return state
        parent = self.context.aq_parent

        if IBatch.providedBy(parent):
            if parent.getClient():
                return 'hidden'

        if IClient.providedBy(parent):
            return 'hidden'

        return state
示例#28
0
def get_client(obj):
    """Returns the client the object passed-in belongs to, if any

    This walks the acquisition chain up until we find something which provides
    either IClient or IClientAwareMixin
    """
    for obj in chain(obj):
        if IClient.providedBy(obj):
            return obj
        elif IClientAwareMixin.providedBy(obj):
            # ClientAwareMixin can return a Client, even if there is no client
            # in the acquisition chain
            return obj.getClient()

    return None
    def __call__(self, context, mode, field, default):
        state = default if default else 'hidden'
        fieldName = field.getName()
        if fieldName != 'Client':
            return state
        parent = self.context.aq_parent

        if IBatch.providedBy(parent):
            if parent.getClient():
                return 'hidden'

        if IClient.providedBy(parent):
            return 'hidden'

        return state
示例#30
0
def try_share_unshare(obj):
    """Tries to share or unshare the object based on the type of its client
    """
    client = resolve_client(obj)
    if not IClient.providedBy(client):
        # This object does not (yet) have a client assigned, do nothing
        return

    if is_internal_client(client):
        # Try to share the obj. Note this transition will only take place if
        # the guard for "share" evaluates to True.
        doActionFor(obj, "share")
    else:
        # Try to unshare the obj. Note this transition will only take place
        # if the guard for "share" evaluates to True.
        doActionFor(obj, "unshare")
示例#31
0
    def get_current_client(self, default=None):
        """Returns the client the current user belongs to
        """
        user = api.get_current_user()
        roles = user.getRoles()
        if 'Client' not in roles:
            return default

        contact = api.get_user_contact(user)
        if not contact or ILabContact.providedBy(contact):
            return default

        client = api.get_parent(contact)
        if not client or not IClient.providedBy(client):
            return default

        return client
示例#32
0
    def get_current_client(self, default=None):
        """Returns the client the current user belongs to
        """
        user = api.get_current_user()
        roles = user.getRoles()
        if 'Client' not in roles:
            return default

        contact = api.get_user_contact(user)
        if not contact or ILabContact.providedBy(contact):
            return default

        client = api.get_parent(contact)
        if not client or not IClient.providedBy(client):
            return default

        return client
示例#33
0
    def get_obj_title(self, obj):
        """Returns the title of the object to be displayed as breadcrumb
        """
        if not api.is_object(obj):
            # Some objects (e.g. portal_registry) are not supported
            return obj.Title()

        title = api.get_title(obj)
        if IClient.providedBy(obj.aq_parent):
            # Objects from inside Client folder are always stored directly, w/o
            # subfolders, making it difficult for user to know if what is
            # looking at is a Sample, a Batch or a Contact. Append the name of
            # the portal type
            pt_title = self.get_portal_type_title(obj)
            if pt_title:
                title = "{} ({})".format(title, _(pt_title))
        return title
示例#34
0
 def get_client(self, schema, fieldnames):
     """All Client Contact fields must be restricted to show only relevant
     Contacts.  During creation the batch can be in some weird states
     and is located inside some odd contexs (TempFolder, PortalFactory),
     so some wiggling required.  We also can't use schema field accessors
     directly, as it causes recursion.
     """
     client = None
     # If heirarchy does not exist we're in early creation; skip body.
     if hasattr(self, 'context') and hasattr(self.context, 'aq_parent'):
         parent = self.context.aq_parent
         while not IPloneSiteRoot.providedBy(parent):
             if IClient.providedBy(parent):
                 client = parent
                 break
             parent = parent.aq_parent
     return client
示例#35
0
 def get_client(self, schema, fieldnames):
     """All Client Contact fields must be restricted to show only relevant
     Contacts.  During creation the batch can be in some weird states
     and is located inside some odd contexs (TempFolder, PortalFactory),
     so some wiggling required.  We also can't use schema field accessors
     directly, as it causes recursion.
     """
     client = None
     # If heirarchy does not exist we're in early creation; skip body.
     if hasattr(self, 'context') and hasattr(self.context, 'aq_parent'):
         parent = self.context.aq_parent
         while not IPloneSiteRoot.providedBy(parent):
             if IClient.providedBy(parent):
                 client = parent
                 break
             parent = parent.aq_parent
     return client
示例#36
0
 def isVisible(self, field, mode="view", default="visible"):
     if mode == "add":
         parent = self.context.aq_parent
         if IClient.providedBy(parent):
             # Note we return "hidden" here instead of "invisible": we want
             # the field to be auto-filled and processed on submit
             return "hidden"
         if IBatch.providedBy(parent) and parent.getClient():
             # The Batch has a Client assigned already!
             # Note we can have Batches without a client assigned
             return "hidden"
     elif mode == "edit":
         # This is already managed by wf permission, but is **never** a good
         # idea to allow the user to change the Client from an AR (basically
         # because otherwise, we'd need to move the object from one client
         # folder to another!).
         return "invisible"
     return default
示例#37
0
def getClient(self):
    """Returns the Client from the Batch passed-in, if any
    """
    parent = self.aq_parent
    if IClient.providedBy(parent):
        # The Batch belongs to an External Client
        return parent

    elif IPatient.providedBy(parent):
        # The Batch belongs to a Patient
        return parent.getClient()

    parent = self.getField("Client").get(self)
    if parent:
        # The Batch belongs to an Internal Client
        return parent

    # The Batch belongs to the laboratory (no Client assigned)
    return None
示例#38
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
示例#39
0
    def __call__(self):
        mtool = getToolByName(self.context, 'portal_membership')
        can_add_doctors = mtool.checkPermission(AddDoctor, self.context)
        if can_add_doctors:
            add_doctors_url = '{}/doctors/createObject?type_name=Doctor' \
                .format(self.portal_url)
            self.context_actions[_('Add')] = {
                'url': add_doctors_url,
                'icon': '++resource++bika.lims.images/add.png'
            }
        if mtool.checkPermission(ManageDoctors, self.context):
            self.review_states[0]['transitions'].append({'id':'deactivate'})
            self.review_states.append(
                {'id':'inactive',
                 'title': _('Dormant'),
                 'contentFilter': {'is_active': False},
                 'transitions': [{'id':'activate'}, ],
                 'columns': self.columns.keys()})
            self.review_states.append(
                {'id':'all',
                 'title': _('All'),
                 'contentFilter':{},
                 'transitions':[{'id':'empty'}],
                 'columns': self.columns.keys()})
            stat = self.request.get("%s_review_state"%self.form_id, 'default')
            self.show_select_column = stat != 'all'

        # If the current context is a Client, filter Doctors by Client UID
        if IClient.providedBy(self.context):
            client_uid = api.get_uid(self.context)
            self.contentFilter['getPrimaryReferrerUID'] = client_uid

        # If the current user is a client contact, do not display the doctors
        # assigned to other clients
        elif self.get_user_client_uid():
            client_uid = self.get_user_client_uid()
            self.contentFilter['getPrimaryReferrerUID'] = [client_uid, None]

        return super(DoctorsView, self).__call__()
示例#40
0
    def __init__(self, context, request):
        super(ARImportsView, self).__init__(context, request)
        request.set('disable_plone.rightcolumn', 1)
        alsoProvides(request, IContentListing)

        self.catalog = "portal_catalog"
        self.contentFilter = {
            'portal_type': 'ARImport',
            'cancellation_state': 'active',
            'sort_on': 'sortable_title',
        }
        self.context_actions = {}
        if IClient.providedBy(self.context):
            self.context_actions = {
                _('AR Import'): {
                    'url': 'arimport_add',
                    'icon': '++resource++bika.lims.images/add.png'}}
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.pagesize = 50
        self.form_id = "arimports"

        self.icon = \
            self.portal_url + "/++resource++bika.lims.images/arimport_big.png"
        self.title = self.context.translate(_("Analysis Request Imports"))
        self.description = ""

        self.columns = {
            'Title': {'title': _('Title')},
            'Client': {'title': _('Client')},
            'Filename': {'title': _('Filename')},
            'Creator': {'title': _('Date Created')},
            'DateCreated': {'title': _('Date Created')},
            'DateValidated': {'title': _('Date Validated')},
            'DateImported': {'title': _('Date Imported')},
            'state_title': {'title': _('State')},
        }
        self.review_states = [
            {'id': 'default',
             'title': _('Pending'),
             'contentFilter': {'review_state': ['invalid', 'valid']},
             'columns': ['Title',
                         'Creator',
                         'Filename',
                         'Client',
                         'DateCreated',
                         'DateValidated',
                         'DateImported',
                         'state_title']},
            {'id': 'imported',
             'title': _('Imported'),
             'contentFilter': {'review_state': 'imported'},
             'columns': ['Title',
                         'Creator',
                         'Filename',
                         'Client',
                         'DateCreated',
                         'DateValidated',
                         'DateImported',
                         'state_title']},
            {'id': 'cancelled',
             'title': _('Cancelled'),
             'contentFilter': {
                 'review_state': ['initial', 'invalid', 'valid', 'imported'],
                 'cancellation_state': 'cancelled'
             },
             'columns': ['Title',
                         'Creator',
                         'Filename',
                         'Client',
                         'DateCreated',
                         'DateValidated',
                         'DateImported',
                         'state_title']},
        ]
示例#41
0
    def __init__(self, context, request):
        super(BaseARImportsView, self).__init__(context, request)
        request.set('disable_plone.rightcolumn', 1)

        self.catalog = "portal_catalog"
        self.contentFilter = {
                'portal_type': 'ARImport',
                'sort_on':'sortable_title',
                }
        self.context_actions = {}
        if IClient.providedBy(self.context):
            self.context_actions = \
                {_('AR Import'):
                           {'url': 'arimport_add',
                            'icon': '++resource++bika.lims.images/add.png'}}
        self.show_sort_column = False
        self.show_select_row = False
        self.show_select_column = False
        self.pagesize = 50
        self.form_id = "arimports"

        self.icon = \
            self.portal_url + "/++resource++bika.lims.images/arimport_big.png"
        self.title = self.context.translate(_("Analysis Request Imports"))
        self.description = ""


        self.columns = {
            'title': {'title': _('Import')},
            'getClientTitle': {'title': _('Client')},
            'getDateImported': {'title': _('Date Imported')},
            'getStatus': {'title': _('Validity')},
            'getDateApplied': {'title': _('Date Submitted')},
            'state_title': {'title': _('State')},
        }
        self.review_states = [
            {'id':'default',
             'title': _('All'),
             'contentFilter':{},
             'columns': ['title',
                         'getClientTitle',
                         'getDateImported',
                         'getStatus',
                         'getDateApplied',
                         'state_title']},
            {'id':'imported',
             'title': _('Imported'),
             'contentFilter':{'review_state':'imported'},
             'columns': ['title',
                         'getClientTitle',
                         'getDateImported',
                         'getStatus']},
            {'id':'submitted',
             'title': _('Applied'),
             'contentFilter':{'review_state':'submitted'},
             'columns': ['title',
                         'getClientTitle',
                         'getDateImported',
                         'getStatus',
                         'getDateApplied']},
        ]
示例#42
0
 def is_client_context(self):
     """Returns whether the batch listing is displayed in IClient context
     or if the current user is a client contact
     """
     return api.get_current_client() or IClient.providedBy(self.context)
示例#43
0
 def filter_client_lookups(self, schema, client):
     if IClient.providedBy(client):
         ids = [c.getId() for c in client.objectValues('Contact')]
         for fn in ["Contact", "CCContact", "InvoiceContact"]:
             if fn in schema:
                 schema[fn].widget.base_query['id'] = ids