Exemplo n.º 1
0
    def local_reindex(self):
        """Reindex all local tasks."""

        query = getUtility(ITaskQuery)
        intids = getUtility(IIntIds)

        # Get all tasks and forwardings currently in the global index
        indexed_tasks = [task.int_id for task in query.get_tasks_for_client(
                client=get_client_id())]

        catalog = getToolByName(self, 'portal_catalog')
        tasks = catalog(object_provides=ITask.__identifier__)
        log = self.mklog()

        # Update the existing tasks
        for task in tasks:
            obj = task.getObject()
            int_id = intids.getId(obj)
            index_task(obj, None)
            if int_id in indexed_tasks:
                indexed_tasks.remove(int_id)
            log('Obj %s updated in the globalindex.\n' % (obj))

        # Clear tasks in the globalindex who's not-existing anymore.
        if len(indexed_tasks):
            for int_id in indexed_tasks:
                task = query.get_task_by_oguid('%s:%i' % (
                        get_client_id(), int_id))

                log('ERROR: Task(%s) with the id: %i does not exist in the'
                    'catalog. It should be manually removed.\n' % (
                        task, task.task_id)
                    )
        return True
Exemplo n.º 2
0
    def _sync_remote_request(
        self, target_client_id, viewname, path='', data={}, headers={}):

        if get_client_id() == target_client_id:
            self.local_reindex()
        else:
            info = getUtility(IContactInformation)
            target = info.get_client_by_id(target_client_id)

            if not target:
                raise ClientNotFound()

            headers = headers.copy()
            data = data.copy()

            mtool = getToolByName(self.context, 'portal_membership')
            member = mtool.getAuthenticatedMember()

            key = 'X-OGDS-AC'
            if key not in headers.keys() and member:
                headers[key] = member.getId()

            headers['X-OGDS-CID'] = get_client_id()

            viewname = viewname.startswith(
                '@@') and viewname or '@@%s' % viewname
            if path:
                url = os.path.join(target.site_url, path, viewname)
            else:
                url = os.path.join(target.site_url, viewname)

            r = requests.post(url, data=data, headers=headers)

            for line in r.iter_lines():
                self.context.REQUEST.RESPONSE.write('%s\n' % line)
Exemplo n.º 3
0
    def local_reindex(self):
        """Reindex all local tasks."""

        query = getUtility(ITaskQuery)
        intids = getUtility(IIntIds)

        # Get all tasks and forwardings currently in the global index
        indexed_tasks = [
            task.int_id
            for task in query.get_tasks_for_client(client=get_client_id())
        ]

        catalog = getToolByName(self, 'portal_catalog')
        tasks = catalog(object_provides=ITask.__identifier__)
        log = self.mklog()

        # Update the existing tasks
        for task in tasks:
            obj = task.getObject()
            int_id = intids.getId(obj)
            index_task(obj, None)
            if int_id in indexed_tasks:
                indexed_tasks.remove(int_id)
            log('Obj %s updated in the globalindex.\n' % (obj))

        # Clear tasks in the globalindex who's not-existing anymore.
        if len(indexed_tasks):
            for int_id in indexed_tasks:
                task = query.get_task_by_oguid('%s:%i' %
                                               (get_client_id(), int_id))

                log('ERROR: Task(%s) with the id: %i does not exist in the'
                    'catalog. It should be manually removed.\n' %
                    (task, task.task_id))
        return True
Exemplo n.º 4
0
def documents_list_helper(context, items):
    urlstring = ''
    lastindex = len(items) - 1
    for i, item in enumerate(items):
        if lastindex == i:
            urlstring = urlstring + '<span><a href="./@@resolve_oguid?oguid='+\
                        get_client_id()+':'+str(item['intid'])+'">'+\
                        item['title']+'</a></span>'
        else:
            urlstring = urlstring + '<span><a href="./@@resolve_oguid?oguid='+\
                        get_client_id()+':'+str(item['intid'])+'">'+\
                        item['title']+', </a></span>'
    return urlstring
Exemplo n.º 5
0
        def _get_issuer():
            info = getUtility(IContactInformation)
            task = ITask(self.context)

            client_id = get_client_id()
            predecessors = self.get_predecessor_task()

            if predecessors and predecessors[0].task_type != "forwarding_task_type":
                client_id = predecessors[0].client_id
            else:
                client_id = get_client_id()

            client = client_title_helper(task, client_id)

            return client + " / " + info.render_link(task.issuer)
Exemplo n.º 6
0
    def custom_url_parameters(self):
        info = getUtility(IContactInformation)
        home_clients = tuple(info.get_assigned_clients())

        # is the user assigned to exactly one client?
        if len(home_clients) == 1:
            default = home_clients[0].client_id
        else:
            default = None

        # read the client from the request
        client_id = self.request.get('client',
                                     self.request.get('form.widgets.client'),
                                     default)
        if isinstance(client_id, list) and len(client_id) == 1:
            client_id = client_id[0]

        # it should not be the current client
        if client_id == get_client_id():
            client_id = None

        if client_id:
            # verify that the user is assigned to the requested client
            if client_id not in [client.client_id for client in home_clients]:
                raise RuntimeError(
                    'Expected current user to be assigned to the '
                    'client "%s" read from request' % client_id)

            else:
                return '?client=%s' % client.client_id

        return ''
Exemplo n.º 7
0
    def test_documents_task_transport_selected_docs(self):
        intids = getUtility(IIntIds)

        task, documents = self._create_task(self.portal,
                                            with_docs=True,
                                            return_docs=True)
        target = self._create_task(self.portal)
        sql_task = getUtility(ITaskQuery).get_task(intids.getId(task),
                                                   get_client_id())

        doc_transporter = getUtility(ITaskDocumentsTransporter)
        ids = [intids.getId(documents[0]), intids.getId(documents[3])]
        intids_mapping = doc_transporter.copy_documents_from_remote_task(
            sql_task, target, documents=ids)

        self.assertEquals([aa.Title
                           for aa in target.getFolderContents()].sort(),
                          ['Doc 1', 'Doc 4'].sort())

        pair1 = intids_mapping.items()[0]
        pair2 = intids_mapping.items()[0]

        self.assertEquals(
            intids.getObject(pair1[0]).Title(),
            intids.getObject(pair1[1]).Title())

        self.assertEquals(
            intids.getObject(pair2[0]).Title(),
            intids.getObject(pair2[1]).Title())
Exemplo n.º 8
0
    def custom_url_parameters(self):
        info = getUtility(IContactInformation)
        home_clients = tuple(info.get_assigned_clients())

        # is the user assigned to exactly one client?
        if len(home_clients) == 1:
            default = home_clients[0].client_id
        else:
            default = None

        # read the client from the request
        client_id = self.request.get(
            'client', self.request.get('form.widgets.client'),
            default)
        if isinstance(client_id, list) and len(client_id) == 1:
            client_id = client_id[0]

        # it should not be the current client
        if client_id == get_client_id():
            client_id = None

        if client_id:
            # verify that the user is assigned to the requested client
            if client_id not in [client.client_id for client in home_clients]:
                raise RuntimeError(
                    'Expected current user to be assigned to the '
                    'client "%s" read from request' % client_id)

            else:
                return '?client=%s' % client.client_id

        return ''
Exemplo n.º 9
0
    def get_base_query(self):
        """Returns the base search query (sqlalchemy)
        """

        query_util = getUtility(ITaskQuery)
        return query_util._get_tasks_for_assigned_client_query(
            get_client_id(), self.sort_on, self.sort_order)
Exemplo n.º 10
0
    def test_documents_task_transport_selected_docs(self):
        intids = getUtility(IIntIds)

        task, documents = self._create_task(
            self.portal, with_docs=True, return_docs=True)
        target = self._create_task(self.portal)
        sql_task = getUtility(ITaskQuery).get_task(
            intids.getId(task), get_client_id())

        doc_transporter = getUtility(ITaskDocumentsTransporter)
        ids = [intids.getId(documents[0]), intids.getId(documents[3])]
        intids_mapping = doc_transporter.copy_documents_from_remote_task(
            sql_task, target, documents=ids)

        self.assertEquals(
            [aa.Title for aa in target.getFolderContents()].sort(),
            ['Doc 1', 'Doc 4'].sort())

        pair1 = intids_mapping.items()[0]
        pair2 = intids_mapping.items()[0]

        self.assertEquals(
            intids.getObject(pair1[0]).Title(),
            intids.getObject(pair1[1]).Title()
            )

        self.assertEquals(
            intids.getObject(pair2[0]).Title(),
            intids.getObject(pair2[1]).Title()
            )
Exemplo n.º 11
0
    def get_task_rows(self):
        """Returns a dict of task-rows (tuples of cells) of all open tasks on
        the current client:

        incoming -- open tasks assigned to the current client
        outgoing -- open tasks assigned to another client
        """

        clientid = get_client_id()

        incoming_query = Session().query(Task)
        incoming_query = incoming_query.filter(
            Task.assigned_client == clientid)
        incoming_query = self._extend_task_query(incoming_query)

        incoming = []
        for task in incoming_query.all():
            incoming.append(self.get_row_for_item(
                    task,
                    display_issuer_client=True))

        outgoing_query = Session().query(Task)
        outgoing_query = outgoing_query.filter(Task.client_id == clientid)
        outgoing_query = self._extend_task_query(outgoing_query)

        outgoing = []
        for task in outgoing_query.all():
            outgoing.append(self.get_row_for_item(
                    task, display_responsible_client=True))

        return {'incoming': incoming,
                'outgoing': outgoing}
Exemplo n.º 12
0
    def get_task_rows(self):
        """Returns a dict of task-rows (tuples of cells) of all open tasks on
        the current client:

        incoming -- open tasks assigned to the current client
        outgoing -- open tasks assigned to another client
        """

        clientid = get_client_id()

        incoming_query = Session().query(Task)
        incoming_query = incoming_query.filter(
            Task.assigned_client == clientid)
        incoming_query = self._extend_task_query(incoming_query)

        incoming = []
        for task in incoming_query.all():
            incoming.append(
                self.get_row_for_item(task, display_issuer_client=True))

        outgoing_query = Session().query(Task)
        outgoing_query = outgoing_query.filter(Task.client_id == clientid)
        outgoing_query = self._extend_task_query(outgoing_query)

        outgoing = []
        for task in outgoing_query.all():
            outgoing.append(
                self.get_row_for_item(task, display_responsible_client=True))

        return {'incoming': incoming, 'outgoing': outgoing}
Exemplo n.º 13
0
    def get_base_query(self):
        """Returns the base search query (sqlalchemy)
        """

        query_util = getUtility(ITaskQuery)
        return query_util._get_tasks_for_assigned_client_query(
            get_client_id(), self.sort_on, self.sort_order)
Exemplo n.º 14
0
    def render(self):

        tasks = get_selected_items(self.context, self.request)
        tasks = [tt for tt in tasks]

        if not tasks:
            msg = _(
                u'error_no_items', default=u'You have not selected any Items')
            IStatusMessage(self.request).addStatusMessage(msg, type='error')
            if self.request.get('orig_template'):
                return self.request.RESPONSE.redirect(
                    self.request.form['orig_template'])
            else:
                return self.request.RESPONSE.redirect(
                    self.context.absolute_url())

        task_attributes = [
            {'id':'title', 'title':_('label_task_title')},
            {'id':'review_state', 'title':_('review_state'),
             'transform':StringTranslater(
                self.context.REQUEST, 'plone').translate},
            {'id':'deadline', 'title':_('label_deadline'),
             'transform':format_datetime, 'style':get_date_style()},
            {'id':'completed', 'title':_('label_completed'),
             'transform':format_datetime, 'style':get_date_style()},
            {'id': 'containing_dossier', 'title':_('label_dossier_title')},
            {'id':'issuer', 'title':_('label_issuer'),
             'transform':readable_author},
            {'id':'responsible', 'title':_('label_responsible'),
             'transform':readable_author},
            {'id':'task_type', 'title':_('label_task_type'),
             'transform':task_type_helper},
            {'id':'client_id', 'title':_('label_client_id')},
            {'id':'sequence_number', 'title':_('label_sequence_number')},
        ]

        reporter = XLSReporter(
            self.context.REQUEST,
            task_attributes,
            tasks,
            sheet_title=translate(
                _('label_tasks', default=u'Tasks'), context=self.request),
            footer='%s %s' % (
                datetime.now().strftime('%d.%m.%Y %H:%M'), get_client_id())
            )

        data = reporter()
        if not data:
            msg = _(u'Could not generate the report')
            IStatusMessage(self.request).addStatusMessage(
                msg, type='error')
            return self.request.RESPONSE.redirect(self.context.absolute_url())

        response = self.request.RESPONSE

        response.setHeader('Content-Type', 'application/vnd.ms-excel')
        set_attachment_content_disposition(self.request, "task_report.xls")

        return data
Exemplo n.º 15
0
def indexed_task_link(item, display_client=False):
    """Renders a indexed task item (globalindex sqlalchemy object) either
    with a link to the effective task (if the user has access) or just with
    the title.
    """

    site = getSite()

    css_class = get_css_class(item)

    # get the contact information utlity and the client
    info = queryUtility(IContactInformation)
    if info:
        client = info.get_client_by_id(item.client_id)
    if not info or not client:
        return '<span class="%s">%s</span>' % (css_class, item.title)

    # has the user access to the target task?
    has_access = False
    mtool = getToolByName(site, 'portal_membership')
    member = mtool.getAuthenticatedMember()

    if member:
        principals = set(member.getGroups() + [member.getId()])
        allowed_principals = set(item.principals)

        # Administrators always have access, but the global role 'Administrator'
        # doesn't get indexed in task.principals in task indexer.
        # TODO: Avoid hardcoding 'og_administratoren'
        allowed_principals.add(u'og_administratoren')

        has_access = len(principals & allowed_principals) > 0

    # is the target on a different client? we need to make a popup if
    # it is...
    if item.client_id != get_client_id():
        link_target = ' target="_blank"'
        url = '%s/%s' % (client.public_url, item.physical_path)
    else:
        link_target = ''
        url = client.public_url + '/' + item.physical_path

    # embed the client
    if display_client:
        client_html = ' <span class="discreet">(%s)</span>' % client.title
    else:
        client_html = ''

    # create breadcrumbs including the (possibly remote) client title
    breadcrumb_titles = "[%s] > %s" % (client.title, item.breadcrumb_title)

    # render the full link if he has acccess
    inner_html = ''.join(('<span class="rollover-breadcrumb %s" \
                                 title="%s">%s</span>'                                                       % \
                    (css_class, breadcrumb_titles, item.title), client_html))
    if has_access:
        return '<a href="%s"%s>%s</a>' % (url, link_target, inner_html)
    else:
        return inner_html
Exemplo n.º 16
0
    def get_indexed_data(self):
        """Returns the indexed data of the adapted task.
        """

        intids = getUtility(IIntIds)
        iid = intids.getId(self.task)

        query = getUtility(ITaskQuery)
        return query.get_task(iid, get_client_id())
Exemplo n.º 17
0
    def _sqlalchemy_task_link(self, item):
        """Renders a indexed task item (globalindex sqlalchemy object) either
        with a link to the effective task (if the user has access) or just with
        the title.
        We have two different types of a task. task-object providing the
        ITask-interface is handled in the _object_task_link.
        """

        css_class = self.get_css_class(item)

        # get the client which the task cames from
        info = queryUtility(IContactInformation)
        if info:
            client = info.get_client_by_id(item.client_id)
        if not info or not client:
            return '<span class="%s">%s</span>' % (css_class, item.title)

        # has the user access to the target task?
        has_access = False
        mtool = getToolByName(self.context, 'portal_membership')
        member = mtool.getAuthenticatedMember()

        if member:
            principals = set(member.getGroups() + [member.getId()])
            allowed_principals = set(item.principals)
            has_access = len(principals & allowed_principals) > 0

        # If the target is on a different client we need to make a popup
        if item.client_id != get_client_id():
            link_target = ' target="_blank"'
            url = '%s/%s' % (client.public_url, item.physical_path)
        else:
            link_target = ''
            url = client.public_url + '/' + item.physical_path

        # create breadcrumbs including the (possibly remote) client title
        breadcrumb_titles = "[%s] > %s" % (client.title, item.breadcrumb_title)

        # Client and user info
        info_html = ' <span class="discreet">(%s / %s)</span>' % (
            client_title_helper(item, item.assigned_client),
            info.render_link(item.responsible),
        )

        # Link to the task object
        task_html = '<span class="%s">%s</span>' % \
                        (css_class, item.title)

        # Render the full link if we have acccess
        if has_access:
            inner_html = '<a href="%s"%s title="%s">%s</a> %s' % (
                url, link_target, breadcrumb_titles, task_html, info_html)
        else:
            inner_html = '%s %s' % (task_html, info_html)

        # Add the task-state css and return it
        return self._task_state_wrapper(item, inner_html)
Exemplo n.º 18
0
    def is_user_assigned_to_client(self, client_id=None):
        """Returns `True` if the authenticated user is assigned to
        this client.
        """

        info = getUtility(IContactInformation)
        if not client_id:
            client_id = get_client_id()

        return info.is_client_assigned(client_id=client_id)
Exemplo n.º 19
0
    def get_oguid(self):
        """Returns the oguid of the adapted task.
        A gouid is the client id and the intid seperated by ":".
        Example: "m1:2331"
        """

        intids = getUtility(IIntIds)
        iid = intids.getId(self.task)

        return '%s:%s' % (get_client_id(), str(iid))
Exemplo n.º 20
0
    def is_client_assigned(self, userid=None, client_id=None):
        """Return True if the specified user is in the user_group
        of the specified client"""

        if not client_id:
            client_id = get_client_id()

        if not userid:
            member = getToolByName(getSite(), "portal_membership").getAuthenticatedMember()
            userid = member.getId()

        return self._is_client_assigned(userid, client_id)
Exemplo n.º 21
0
    def is_client_assigned(self, userid=None, client_id=None):
        """Return True if the specified user is in the user_group
        of the specified client"""

        if not client_id:
            client_id = get_client_id()

        if not userid:
            member = getToolByName(
                getSite(), 'portal_membership').getAuthenticatedMember()
            userid = member.getId()

        return self._is_client_assigned(userid, client_id)
Exemplo n.º 22
0
    def is_user_in_inbox_group(self, userid=None, client_id=None):
        if not client_id:
            client_id = get_client_id()

        if not userid:
            member = getToolByName(getSite(), "portal_membership").getAuthenticatedMember()
            userid = member.getId()

        client = self.get_client_by_id(client_id)
        if client:
            return self.is_group_member(client.inbox_group_id, userid)
        else:
            return False
Exemplo n.º 23
0
    def _sync_remote_request(self,
                             target_client_id,
                             viewname,
                             path='',
                             data={},
                             headers={}):

        if get_client_id() == target_client_id:
            self.local_reindex()
        else:
            info = getUtility(IContactInformation)
            target = info.get_client_by_id(target_client_id)

            if not target:
                raise ClientNotFound()

            headers = headers.copy()
            data = data.copy()

            mtool = getToolByName(self.context, 'portal_membership')
            member = mtool.getAuthenticatedMember()

            key = 'X-OGDS-AC'
            if key not in headers.keys() and member:
                headers[key] = member.getId()

            headers['X-OGDS-CID'] = get_client_id()

            viewname = viewname.startswith(
                '@@') and viewname or '@@%s' % viewname
            if path:
                url = os.path.join(target.site_url, path, viewname)
            else:
                url = os.path.join(target.site_url, viewname)

            r = requests.post(url, data=data, headers=headers)

            for line in r.iter_lines():
                self.context.REQUEST.RESPONSE.write('%s\n' % line)
Exemplo n.º 24
0
    def get_task(self):
        intids = getUtility(IIntIds)
        membership = getToolByName(self.context, 'portal_membership')
        oguid = self.request.get('oguid')

        clientid, iid = oguid.split(':')
        if clientid != get_client_id():
            raise NotFound

        task = intids.getObject(int(iid))
        if not membership.checkPermission('Add portal content', task):
            raise NotFound

        return task
Exemplo n.º 25
0
    def get_task(self):
        intids = getUtility(IIntIds)
        membership = getToolByName(self.context, 'portal_membership')
        oguid = self.request.get('oguid')

        clientid, iid = oguid.split(':')
        if clientid != get_client_id():
            raise NotFound

        task = intids.getObject(int(iid))
        if not membership.checkPermission('Add portal content', task):
            raise NotFound

        return task
Exemplo n.º 26
0
    def is_user_in_inbox_group(self, userid=None, client_id=None):
        if not client_id:
            client_id = get_client_id()

        if not userid:
            member = getToolByName(
                getSite(), 'portal_membership').getAuthenticatedMember()
            userid = member.getId()

        client = self.get_client_by_id(client_id)
        if client:
            return self.is_group_member(client.inbox_group_id, userid)
        else:
            return False
Exemplo n.º 27
0
    def list_assigned_users(self, client_id=None):
        """Lists all users assigned to a client.
        """
        if not client_id:
            client_id = get_client_id()

        if not client_id:
            logger.warn("can't list assigned users, without a client_id")
            return []

        session = create_session()
        users = session.query(Group).join(Client.users_group).filter(Client.client_id == client_id).first().users

        return users
Exemplo n.º 28
0
    def is_user_in_inbox_group(self, userid=None, client_id=None):
        if not client_id:
            client_id = get_client_id()

        if not userid:
            member = getToolByName(
                getSite(), 'portal_membership').getAuthenticatedMember()
            userid = member.getId()

        if self.get_client_by_id(client_id) and self.get_user(userid) in \
                self.get_client_by_id(client_id).inbox_group.users:
            return True

        return False
Exemplo n.º 29
0
    def update(self):
        """put default value for relatedItems into request - the added
           objects will later be moved insed the forwarding
        """
        paths = self.request.get('paths', [])

        if not (paths or
                self.request.form.get('form.widgets.relatedItems', [])
        or '@@autocomplete-search' in self.request.get('ACTUAL_URL', '')):
            # add status message and redirect current window back to inbox
            # but ONLY if we're not in a z3cform_inline_validation or
            # autocomplete-search request!
            IStatusMessage(self.request).addStatusMessage(
                _(u'error_no_document_selected',
                  u'Error: Please select at least one document to forward'),
                type='error')
            redir_url = self.request.get('orig_template',
                        self.context.absolute_url())
            self.request.RESPONSE.redirect(redir_url)

        if paths:
            self.request.set('form.widgets.relatedItems', paths)

        # put default value for issuer into request
        if not self.request.get('form.widgets.issuer', None):
            self.request.set('form.widgets.issuer',
                             u'inbox:%s' % get_client_id())

        # put the default responsible into the request
        if not self.request.get('form.widgets.responsible_client', None):
            client = get_client_id()
            self.request.set('form.widgets.responsible_client', client)
            self.request.set('form.widgets.responsible',
                             [(u'inbox:%s' % client).encode('utf-8')])

        AddForm.update(self)
Exemplo n.º 30
0
    def render(self):
        oguid = self.request.get('oguid')
        clientid, iid = oguid.split(':')

        if clientid != get_client_id():
            # wrong client. redirect to right one.
            info = getUtility(IContactInformation)
            client = info.get_client_by_id(clientid)

            url = '%s/@@resolve_oguid?oguid=%s' % (client.public_url, oguid)
            return self.request.RESPONSE.redirect(url)

        obj = self._get_object(int(iid))

        return self.request.RESPONSE.redirect(obj.absolute_url())
Exemplo n.º 31
0
    def test_documents_task_transport(self):
        intids = getUtility(IIntIds)

        task = self._create_task(self.portal, with_docs=True)
        target = self._create_task(self.portal)

        sql_task = getUtility(ITaskQuery).get_task(intids.getId(task),
                                                   get_client_id())

        doc_transporter = getUtility(ITaskDocumentsTransporter)
        doc_transporter.copy_documents_from_remote_task(sql_task, target)

        self.assertEquals([aa.Title
                           for aa in target.getFolderContents()].sort(),
                          ['Doc 1', 'Doc 2', 'Doc 3', 'Doc 4'].sort())
Exemplo n.º 32
0
    def list_assigned_users(self, client_id=None):
        """Lists all users assigned to a client.
        """
        if not client_id:
            client_id = get_client_id()

        if not client_id:
            logger.warn("can't list assigned users, without a client_id")
            return []

        session = create_session()
        users = session.query(Group).join(Client.users_group).filter(
            Client.client_id == client_id).first().users

        return users
Exemplo n.º 33
0
    def get_base_query(self):
        """Returns the base search query (sqlalchemy)i
        """

        portal_state = self.context.unrestrictedTraverse("@@plone_portal_state")
        userid = portal_state.member().getId()

        query_util = getUtility(ITaskQuery)

        # show all tasks assigned to this user ..
        query = query_util._get_tasks_for_responsible_query(userid, self.sort_on, self.sort_order)

        # .. and assigned to the current client
        query = query.filter_by(assigned_client=get_client_id())
        return query
Exemplo n.º 34
0
    def update(self):
        """put default value for relatedItems into request - the added
           objects will later be moved insed the forwarding
        """
        paths = self.request.get('paths', [])

        if not (paths or self.request.form.get('form.widgets.relatedItems', [])
                or '@@autocomplete-search' in self.request.get(
                    'ACTUAL_URL', '')):
            # add status message and redirect current window back to inbox
            # but ONLY if we're not in a z3cform_inline_validation or
            # autocomplete-search request!
            IStatusMessage(self.request).addStatusMessage(_(
                u'error_no_document_selected',
                u'Error: Please select at least one document to forward'),
                                                          type='error')
            redir_url = self.request.get('orig_template',
                                         self.context.absolute_url())
            self.request.RESPONSE.redirect(redir_url)

        if paths:
            self.request.set('form.widgets.relatedItems', paths)

        # put default value for issuer into request
        if not self.request.get('form.widgets.issuer', None):
            self.request.set('form.widgets.issuer',
                             u'inbox:%s' % get_client_id())

        # put the default responsible into the request
        if not self.request.get('form.widgets.responsible_client', None):
            client = get_client_id()
            self.request.set('form.widgets.responsible_client', client)
            self.request.set('form.widgets.responsible',
                             [(u'inbox:%s' % client).encode('utf-8')])

        AddForm.update(self)
Exemplo n.º 35
0
    def test_documents_task_transport(self):
        intids = getUtility(IIntIds)

        task = self._create_task(self.portal, with_docs=True)
        target = self._create_task(self.portal)

        sql_task = getUtility(ITaskQuery).get_task(
            intids.getId(task), get_client_id())

        doc_transporter = getUtility(ITaskDocumentsTransporter)
        doc_transporter.copy_documents_from_remote_task(
            sql_task, target)

        self.assertEquals(
            [aa.Title for aa in target.getFolderContents()].sort(),
            ['Doc 1', 'Doc 2', 'Doc 3', 'Doc 4'].sort())
Exemplo n.º 36
0
    def get_base_query(self):
        """Returns the base search query (sqlalchemy)i
        """

        portal_state = self.context.unrestrictedTraverse(
            '@@plone_portal_state')
        userid = portal_state.member().getId()

        query_util = getUtility(ITaskQuery)

        # show all tasks assigned to this user ..
        query = query_util._get_tasks_for_responsible_query(
            userid, self.sort_on, self.sort_order)

        # .. and assigned to the current client
        query = query.filter_by(assigned_client=get_client_id())
        return query
Exemplo n.º 37
0
    def key_value_provider(self):
        """yield the items

        key = client id
        value = client title
        """

        info = getUtility(IContactInformation)
        current_client_id = get_client_id()
        mtool = getToolByName(getSite(), 'portal_membership')
        member = mtool.getAuthenticatedMember()

        for client in info.get_assigned_clients():
            if current_client_id != client.client_id:
                inbox_group = client.inbox_group
                if inbox_group in member.getGroups():
                    yield (client.client_id, client.title)
Exemplo n.º 38
0
def assign_forwarding_to_dossier(
    context, forwarding_oguid, dossier, response_text):

    forwarding = getUtility(ITaskQuery).get_task_by_oguid(forwarding_oguid)

    forwarding_obj = context.unrestrictedTraverse(
        forwarding.physical_path.encode('utf-8'))

    # we need all task field values from the forwarding
    fielddata = {}
    for fieldname in ITask.names():
        value = ITask.get(fieldname).get(forwarding_obj)
        fielddata[fieldname] = value

    # lets create a new task - the successor task
    task = createContentInContainer(
        dossier, 'opengever.task.task', **fielddata)

    successor_tc_task = ISuccessorTaskController(task)

    # copy documents and map the intids
    intids_mapping = _copy_documents_from_forwarding(forwarding_obj, task)

    # copy the responses
    response_transporter = IResponseTransporter(task)
    response_transporter.get_responses(
        get_client_id(),
        '/'.join(forwarding_obj.getPhysicalPath()),
        intids_mapping=intids_mapping)

    # close and store the forwarding in yearfolder
    change_task_workflow_state(
        forwarding_obj,
        'forwarding-transition-assign-to-dossier',
        text=response_text,
        successor_oguid=successor_tc_task.get_oguid())

    inbox = aq_parent(aq_inner(forwarding_obj))
    yearfolder = _get_yearfolder(inbox)
    clipboard = inbox.manage_cutObjects((forwarding_obj.getId(),))
    yearfolder.manage_pasteObjects(clipboard)

    # successor
    successor_tc_task.set_predecessor(forwarding_oguid)

    return task
Exemplo n.º 39
0
        def _get_issuer():
            info = getUtility(IContactInformation)
            task = ITask(self.context)

            if info.is_one_client_setup():
                return info.render_link(task.issuer)

            client_id = get_client_id()
            predecessors = self.get_predecessor_task()

            if predecessors and \
                predecessors[0].task_type != 'forwarding_task_type':
                client_id = predecessors[0].client_id

            client = client_title_helper(task, client_id)

            return client + ' / ' + info.render_link(task.issuer)
Exemplo n.º 40
0
    def _extend_task_query(self, query):
        """Extends a globalindex task query.
        """

        # sort by deadline
        query = query.order_by(asc(Task.deadline))

        # list only open tasks
        query = query.filter(Task.review_state.in_(OPEN_TASK_STATES))

        # If a task has a successor task, list only one of them.
        # List only the one which is assigned to this client.
        query = query.filter(
            or_(and_(Task.predecessor == None, Task.successors == None),
                Task.client_id == get_client_id()))

        return query
Exemplo n.º 41
0
        def _get_issuer():
            info = getUtility(IContactInformation)
            task = ITask(self.context)

            if info.is_one_client_setup():
                return info.render_link(task.issuer)

            client_id = get_client_id()
            predecessors = self.get_predecessor_task()

            if predecessors and \
                predecessors[0].task_type != 'forwarding_task_type':
                client_id = predecessors[0].client_id

            client = client_title_helper(task, client_id)

            return client + ' / ' + info.render_link(task.issuer)
Exemplo n.º 42
0
    def updateWidgets(self):
        super(AdvancedSearchForm, self).updateWidgets()

        self.fields['responsible'].widgetFactory[INPUT_MODE] \
            = AutocompleteFieldWidget
        self.fields['checked_out'].widgetFactory[INPUT_MODE] \
            = AutocompleteFieldWidget
        self.fields['issuer'].widgetFactory[INPUT_MODE] \
            = AutocompleteFieldWidget
        self.fields['object_provides'].widgetFactory[INPUT_MODE] \
            = radio.RadioFieldWidget
        self.fields['dossier_review_state'].widgetFactory[INPUT_MODE] \
            = checkbox.CheckBoxFieldWidget
        self.fields['task_review_state'].widgetFactory[INPUT_MODE] \
            = checkbox.CheckBoxFieldWidget

        self.context.REQUEST.set('client', get_client_id())
        date_fields = [
            'start_1',
            'start_2',
            'end_1',
            'end_2',
            'deadline_1',
            'deadline_2',
            'receipt_date_1',
            'receipt_date_2',
            'delivery_date_1',
            'delivery_date_2',
            'document_date_1',
            'document_date_2',
        ]

        for field in date_fields:
            self.fields.get(
                field).widgetFactory[INPUT_MODE] = DatePickerFieldWidget

        searchableText = self.widgets["searchableText"]
        searchableText.value = self.request.get('SearchableText')

        for k, v in self.field_mapping().items():
            for name in v:
                if self.widgets.get(name, None):
                    self.widgets.get(name, None).addClass(k)

        self.set_object_provides_field_description()
Exemplo n.º 43
0
    def updateWidgets(self):
        super(AdvancedSearchForm, self).updateWidgets()

        self.fields['responsible'].widgetFactory[INPUT_MODE] \
            = AutocompleteFieldWidget
        self.fields['checked_out'].widgetFactory[INPUT_MODE] \
            = AutocompleteFieldWidget
        self.fields['issuer'].widgetFactory[INPUT_MODE] \
            = AutocompleteFieldWidget
        self.fields['object_provides'].widgetFactory[INPUT_MODE] \
            = radio.RadioFieldWidget
        self.fields['dossier_review_state'].widgetFactory[INPUT_MODE] \
            = checkbox.CheckBoxFieldWidget
        self.fields['task_review_state'].widgetFactory[INPUT_MODE] \
            = checkbox.CheckBoxFieldWidget

        self.context.REQUEST.set('client', get_client_id())
        date_fields = [
            'start_1',
            'start_2',
            'end_1',
            'end_2',
            'deadline_1',
            'deadline_2',
            'receipt_date_1',
            'receipt_date_2',
            'delivery_date_1',
            'delivery_date_2',
            'document_date_1',
            'document_date_2',
        ]

        for field in date_fields:
            self.fields.get(
                field).widgetFactory[INPUT_MODE] = DatePickerFieldWidget

        searchableText = self.widgets["searchableText"]
        searchableText.value = self.request.get('SearchableText')

        for k, v in self.field_mapping().items():
            for name in v:
                if self.widgets.get(name, None):
                    self.widgets.get(name, None).addClass(k)

        self.set_object_provides_field_description()
Exemplo n.º 44
0
def assign_forwarding_to_dossier(context, forwarding_oguid, dossier,
                                 response_text):

    forwarding = getUtility(ITaskQuery).get_task_by_oguid(forwarding_oguid)

    forwarding_obj = context.unrestrictedTraverse(
        forwarding.physical_path.encode('utf-8'))

    # we need all task field values from the forwarding
    fielddata = {}
    for fieldname in ITask.names():
        value = ITask.get(fieldname).get(forwarding_obj)
        fielddata[fieldname] = value

    # lets create a new task - the successor task
    task = createContentInContainer(dossier, 'opengever.task.task',
                                    **fielddata)

    successor_tc_task = ISuccessorTaskController(task)

    # copy documents and map the intids
    intids_mapping = _copy_documents_from_forwarding(forwarding_obj, task)

    # copy the responses
    response_transporter = IResponseTransporter(task)
    response_transporter.get_responses(get_client_id(),
                                       '/'.join(
                                           forwarding_obj.getPhysicalPath()),
                                       intids_mapping=intids_mapping)

    # close and store the forwarding in yearfolder
    change_task_workflow_state(forwarding_obj,
                               'forwarding-transition-assign-to-dossier',
                               text=response_text,
                               successor_oguid=successor_tc_task.get_oguid())

    inbox = aq_parent(aq_inner(forwarding_obj))
    yearfolder = _get_yearfolder(inbox)
    clipboard = inbox.manage_cutObjects((forwarding_obj.getId(), ))
    yearfolder.manage_pasteObjects(clipboard)

    # successor
    successor_tc_task.set_predecessor(forwarding_oguid)

    return task
Exemplo n.º 45
0
    def _extend_task_query(self, query):
        """Extends a globalindex task query.
        """

        # sort by deadline
        query = query.order_by(asc(Task.deadline))

        # list only open tasks
        query = query.filter(Task.review_state.in_(OPEN_TASK_STATES))

        # If a task has a successor task, list only one of them.
        # List only the one which is assigned to this client.
        query = query.filter(
            or_(
                and_(Task.predecessor == None, Task.successors == None),
                Task.client_id == get_client_id()))

        return query
    def key_value_provider(self):
        """yield the items

        key = client id
        value = client title
        """

        info = getUtility(IContactInformation)
        current_client_id = get_client_id()
        mtool = getToolByName(getSite(), 'portal_membership')
        member = mtool.getAuthenticatedMember()

        for client in info.get_assigned_clients():
            if current_client_id != client.client_id:
                inbox_group = client.inbox_group
                if inbox_group in member.getGroups():
                    yield (client.client_id,
                           client.title)
Exemplo n.º 47
0
    def render(self):
        # set responsible
        self.context.responsible_client = get_client_id()
        self.context.responsible = u'inbox:%s' % (
            self.context.responsible_client)

        # create a response in the task
        add_simple_response(
            self.context,
            field_changes=(
                (ITask['responsible'], self.context.responsible),
                (ITask['responsible_client'],
                 self.context.responsible_client),),
            transition=u'forwarding-transition-refuse')

        notify(ObjectModifiedEvent(self.context))

        return self.request.RESPONSE.redirect('.')
Exemplo n.º 48
0
    def assigned_tasks(self):
        """
        Get tasks that have been created on a different client and
        are assigned to this client's inbox.
        """
        query_util = getUtility(ITaskQuery)
        query = query_util._get_tasks_for_responsible_query(
            get_current_inbox_principal(self.context))

        query = query.filter(Task.review_state.in_(OPEN_TASK_STATES))

        # If a task has a successor task, it should only list one of them,
        # the one which is physically one the current client.
        query = query.filter(
            or_(
                and_(Task.predecessor == None, Task.successors == None),
                Task.client_id == get_client_id()))

        return query.all()[:5]
Exemplo n.º 49
0
    def build_query(self):
        """Builds the query based on `get_base_query()` method of config.
        Returns the query object.
        """

        # initalize config
        self.config.update_config()

        # get the base query from the config
        query = self.config.get_base_query()
        query = self.validate_base_query(query)

        # If a task has a successor task, list only one of them.
        # List the only the one which is assigned to this client.
        query = query.filter(
            or_(
                and_(Task.predecessor == None, Task.successors == None),
                Task.client_id == get_client_id()))

        # ordering
        query = self.extend_query_with_ordering(query)

        # filter
        if self.config.filter_text:
            query = self.extend_query_with_textfilter(
                query, self.config.filter_text)

        # reviewstate-filter
        review_state_filter = self.request.get(
            self.config.state_filter_name, None)

        if review_state_filter == 'false':
            review_state_filter = False
        else:
            review_state_filter = True

        query = self.extend_query_with_statefilter(query, review_state_filter)

        # batching
        if self.config.batching_enabled and not self.config.lazy:
            query = self.extend_query_with_batching(query)

        return query
Exemplo n.º 50
0
    def build_query(self):
        """Builds the query based on `get_base_query()` method of config.
        Returns the query object.
        """

        # initalize config
        self.config.update_config()

        # get the base query from the config
        query = self.config.get_base_query()
        query = self.validate_base_query(query)

        # If a task has a successor task, list only one of them.
        # List the only the one which is assigned to this client.
        query = query.filter(
            or_(and_(Task.predecessor == None, Task.successors == None),
                Task.client_id == get_client_id()))

        # ordering
        query = self.extend_query_with_ordering(query)

        # filter
        if self.config.filter_text:
            query = self.extend_query_with_textfilter(query,
                                                      self.config.filter_text)

        # reviewstate-filter
        review_state_filter = self.request.get(self.config.state_filter_name,
                                               None)

        if review_state_filter == 'false':
            review_state_filter = False
        else:
            review_state_filter = True

        query = self.extend_query_with_statefilter(query, review_state_filter)

        # batching
        if self.config.batching_enabled and not self.config.lazy:
            query = self.extend_query_with_batching(query)

        return query
Exemplo n.º 51
0
def get_site_url():
    """Compatibility function to retrieve the `site_url` for the current
    admin_unit (>= 3.0) or client (< 3.0).
    """
    try:
        # >= 3.0
        from opengever.ogds.base.utils import get_current_admin_unit
        site_url = get_current_admin_unit().site_url
    except ImportError:
        # 2.7 - 2.9
        from opengever.ogds.base.utils import get_client_id
        from opengever.ogds.base.interfaces import IContactInformation
        from zope.component import getUtility

        client_id = get_client_id()
        info = getUtility(IContactInformation)
        client = info.get_client_by_id(client_id)
        site_url = client.site_url

    return site_url
Exemplo n.º 52
0
def client_id(obj):
    return get_client_id()
Exemplo n.º 53
0
    def create(self, paths=[]):
        """generate the task templates"""

        if 'abort' in self.request.keys():
            return self.request.RESPONSE.redirect(self.context.absolute_url())

        templates = []

        for path in paths:
            templates.append(self.context.restrictedTraverse(path))

        if len(templates) == 0:
            IStatusMessage(self.request).addStatusMessage(_(
                u'message_no_templates_selected',
                default=u'You have not selected any templates'),
                                                          type="info")

            return self.request.RESPONSE.redirect(self.context.absolute_url())

        # Create main task
        templatefolder = aq_parent(aq_inner(templates[0]))

        highest_deadline = max([temp.deadline for temp in templates])

        data = dict(
            title=templatefolder.title,
            issuer=self.replace_interactive_user('current_user'),
            responsible=self.replace_interactive_user('current_user'),
            responsible_client=get_client_id(),
            task_type='direct-execution',
            deadline=date.today() +
            timedelta(highest_deadline + MAIN_TASK_DEADLINE_DELTA),
        )

        main_task = createContent('opengever.task.task', **data)
        notify(ObjectCreatedEvent(main_task))
        main_task = addContentToContainer(self.context,
                                          main_task,
                                          checkConstraints=True)

        # set marker Interfaces
        alsoProvides(main_task, IFromTasktemplateGenerated)

        # set the main_task in to the in progress state
        wft = getToolByName(self.context, 'portal_workflow')
        wft.doActionFor(main_task, 'task-transition-open-in-progress')

        # create subtasks
        for template in templates:
            deadline = date.today() + timedelta(template.deadline)

            data = dict(
                title=template.title,
                issuer=self.replace_interactive_user(template.issuer),
                responsible=self.replace_interactive_user(
                    template.responsible),
                task_type=template.task_type,
                text=template.text,
                deadline=deadline,
            )

            if template.responsible_client == 'interactive_users':
                info = getUtility(IContactInformation)
                responsible_assigned_clients = tuple(
                    info.get_assigned_clients(data['responsible']))
                current_client = get_current_client()
                if not responsible_assigned_clients or \
                        current_client in responsible_assigned_clients:
                    data['responsible_client'] = current_client.client_id
                else:
                    data['responsible_client'] = \
                        responsible_assigned_clients[0].client_id
            else:
                data['responsible_client'] = template.responsible_client

            task = createContent('opengever.task.task', **data)
            notify(ObjectCreatedEvent(task))
            task = addContentToContainer(main_task,
                                         task,
                                         checkConstraints=True)
            alsoProvides(task, IFromTasktemplateGenerated)
            task.reindexObject()

        IStatusMessage(self.request).addStatusMessage(_(
            u'message_tasks_created', default=u'tasks created'),
                                                      type="info")

        return self.request.RESPONSE.redirect('%s#tasks' %
                                              self.context.absolute_url())
Exemplo n.º 54
0
def client_voc_cachekey(method, self):
    """A cache key depending on the vocabulary name and the current client id.
    """
    return '%s:%s:%s' % (getattr(self, 'grokcore.component.directive.name'),
                      get_client_id(), getUtility(ISyncStamp).get_sync_stamp())
Exemplo n.º 55
0
def get_current_inbox_principal(context):

    return 'inbox:%s' % get_client_id()
Exemplo n.º 56
0
def accept_forwarding_with_successor(context,
                                     predecessor_oguid,
                                     response_text,
                                     dossier=None):

    # the predessecor (the forwarding on the remote client)
    predecessor = getUtility(ITaskQuery).get_task_by_oguid(predecessor_oguid)

    # get the inbox
    cat = getToolByName(context, 'portal_catalog')
    inboxes = cat(portal_type="opengever.inbox.inbox")

    if len(inboxes) == 0:
        raise Unauthorized()
    else:
        inbox = inboxes[0].getObject()

    # transport the remote forwarding to the inbox or actual yearfolder
    transporter = getUtility(ITransporter)
    if dossier:
        yearfolder = _get_yearfolder(inbox, )
        successor_forwarding = transporter.transport_from(
            yearfolder, predecessor.client_id, predecessor.physical_path)
    else:
        successor_forwarding = transporter.transport_from(
            inbox, predecessor.client_id, predecessor.physical_path)

    # Replace the issuer with the current inbox
    successor_forwarding.issuer = u'inbox:%s' % get_client_id()

    # Set the "X-CREATING-SUCCESSOR" flag for preventing the event handler
    # from creating additional responses per added document.
    successor_forwarding.REQUEST.set('X-CREATING-SUCCESSOR', True)

    successor_tc = ISuccessorTaskController(successor_forwarding)

    # copy documents and map the intids
    doc_transporter = getUtility(ITaskDocumentsTransporter)
    with CustomInitialVersionMessage(
            _(u'version_message_accept_forwarding',
              default=u'Document copied from forwarding (forwarding accepted)'
              ), context.REQUEST):
        intids_mapping = doc_transporter.copy_documents_from_remote_task(
            predecessor, successor_forwarding)

    # copy the responses
    response_transporter = IResponseTransporter(successor_forwarding)
    response_transporter.get_responses(predecessor.client_id,
                                       predecessor.physical_path,
                                       intids_mapping=intids_mapping)

    # if a dossier is given means that a successor task must
    # be created in a new or a existing dossier
    if dossier:
        # we need all task field values from the forwarding
        fielddata = {}
        for fieldname in ITask.names():
            value = ITask.get(fieldname).get(successor_forwarding)
            fielddata[fieldname] = value

        # lets create a new task - the successor task
        task = createContentInContainer(dossier, 'opengever.task.task',
                                        **fielddata)

        # copy documents and map the intids

        intids_mapping = _copy_documents_from_forwarding(
            successor_forwarding, task)

        # copy the responses
        response_transporter = IResponseTransporter(task)
        response_transporter.get_responses(
            get_client_id(),
            '/'.join(successor_forwarding.getPhysicalPath()),
            intids_mapping=intids_mapping)

        # successor
        successor_tc_task = ISuccessorTaskController(task)

    transaction.savepoint()

    # Close the predessecor forwarding
    response_text = response_text or ''
    request_data = {
        'response_text': response_text.encode('utf-8'),
        'successor_oguid': successor_tc.get_oguid(),
        'transition': 'forwarding-transition-accept'
    }

    response = remote_request(predecessor.client_id,
                              '@@store_forwarding_in_yearfolder',
                              path=predecessor.physical_path,
                              data=request_data)

    if response.read().strip() != 'OK':
        raise Exception('Adding the response and changing the '
                        'workflow state on the predecessor forwarding '
                        'failed.')

    if dossier:
        # when a successor task exists, we close also the successor forwarding
        change_task_workflow_state(
            successor_forwarding,
            'forwarding-transition-accept',
            text=response_text,
            successor_oguid=successor_tc_task.get_oguid())

    # create the succssor relations
    successor_tc.set_predecessor(predecessor_oguid)
    if dossier:
        successor_tc_task.set_predecessor(successor_tc.get_oguid())
        return task
    return successor_forwarding