Example #1
0
    def copy_documents_from_remote_task(self, task, target,
                                        documents=None, comment=None):

        transporter = Transporter()
        data = dispatch_json_request(
            task.admin_unit_id,
            '@@task-documents-extract',
            path=task.physical_path,
            data={'documents': json.dumps(documents)})

        intids_mapping = {}
        intids = getUtility(IIntIds)

        for item in data:
            obj = transporter.create(item, target)

            # Set custom initial version comment
            if comment:
                Versioner(obj).set_custom_initial_version_comment(comment)

            oldintid = IAnnotations(obj)[ORIGINAL_INTID_ANNOTATION_KEY]
            newintid = intids.getId(obj)
            intids_mapping[oldintid] = newintid

        return intids_mapping
Example #2
0
    def create_forwarding(self):
        """Create a copy of the given forwarding in the request to
        the actual yearfolder."""

        yearfolder = self.get_yearfolder()
        transporter = Transporter()
        return transporter.receive(yearfolder, self.request)
Example #3
0
    def test_transport_to_returns_a_dict_with_the_path_to_the_new_object(self):
        source_dossier = create(Builder("dossier").titled(u"Source"))
        target_dossier = create(Builder("dossier").titled(u"Target"))
        document = create(Builder("document")
                          .within(source_dossier)
                          .titled(u'Fo\xf6')
                          .with_dummy_content())

        data = Transporter().transport_to(
            document, 'client1', '/'.join(target_dossier.getPhysicalPath()))
        transported_doc = self.portal.unrestrictedTraverse(
            data.get('path').encode('utf-8'))

        # data
        self.assertEquals(u'Fo\xf6', transported_doc.title)
        self.assertEquals('Test data', transported_doc.file.data)

        # behavior data
        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        # dublin core
        self.assertEquals(document.created(), transported_doc.created())
        self.assertEquals(TEST_USER_ID, transported_doc.Creator())
    def copy_documents_from_remote_task(self,
                                        task,
                                        target,
                                        documents=None,
                                        comment=None):

        transporter = Transporter()
        data = dispatch_json_request(task.admin_unit_id,
                                     '@@task-documents-extract',
                                     path=task.physical_path,
                                     data={'documents': json.dumps(documents)})

        intids_mapping = {}
        intids = getUtility(IIntIds)

        for item in data:
            obj = transporter.create(item, target)

            # Set custom initial version comment
            if comment:
                Versioner(obj).set_custom_initial_version_comment(comment)

            oldintid = IAnnotations(obj)[ORIGINAL_INTID_ANNOTATION_KEY]
            newintid = intids.getId(obj)
            intids_mapping[oldintid] = newintid

        return intids_mapping
    def render(self):
        if not self.context.is_submitted_document():
            raise NoSubmittedDocument()

        if self.context.is_checked_out():
            raise Unauthorized()

        with elevated_privileges():
            transporter = Transporter()
            transporter.update(self.context, self.request)

            portal_path = '/'.join(api.portal.get().getPhysicalPath())
            intids = getUtility(IIntIds)
            repository = api.portal.get_tool('portal_repository')
            comment = translate(_(
                u"Updated with a newer docment version from proposal's "
                "dossier."),
                                context=self.request)
            repository.save(obj=self.context, comment=comment)

            data = {
                'path':
                '/'.join(self.context.getPhysicalPath())[len(portal_path) +
                                                         1:],
                'intid':
                intids.queryId(self.context)
            }

        # Set correct content type for JSON response
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)
Example #6
0
    def store_copy_in_remote_yearfolder(self, refusing_unit_id):
        transporter = Transporter()
        jsondata = json.dumps(transporter.extract(self.context))
        request_data = {REQUEST_KEY: jsondata, }

        response = dispatch_json_request(
            refusing_unit_id, '@@store_refused_forwarding',
            data=request_data)

        if response.get('status') not in [
                STATUS_SUCCESSFULL, STATUS_ALLREADY_DONE]:
            raise Exception(
                'Storing the forwarding on remote yearfolder failed')

        remote_task = response.get('remote_task')
        if response.get('status') != STATUS_ALLREADY_DONE:
            # transport responses
            response_transporter = IResponseTransporter(self.context)
            response_transporter.send_responses(
                refusing_unit_id, remote_task)

            # transport documents
            for document in get_documents_of_task(self.context):
                transporter.transport_to(
                    document, refusing_unit_id, remote_task)

        return self.get_remote_task_url(refusing_unit_id, remote_task)
Example #7
0
    def store_copy_in_remote_yearfolder(self, refusing_unit_id):
        transporter = Transporter()
        jsondata = json.dumps(transporter.extract(self.context))
        request_data = {
            REQUEST_KEY: jsondata,
        }

        response = dispatch_json_request(refusing_unit_id,
                                         '@@store_refused_forwarding',
                                         data=request_data)

        if response.get('status') not in [
                STATUS_SUCCESSFULL, STATUS_ALLREADY_DONE
        ]:
            raise Exception(
                'Storing the forwarding on remote yearfolder failed')

        remote_task = response.get('remote_task')
        if response.get('status') != STATUS_ALLREADY_DONE:
            # transport responses
            response_transporter = IResponseTransporter(self.context)
            response_transporter.send_responses(refusing_unit_id, remote_task)

            # transport documents
            for document in get_documents_of_task(self.context):
                transporter.transport_to(document, refusing_unit_id,
                                         remote_task)

        return self.get_remote_task_url(refusing_unit_id, remote_task)
    def test_transport_to_returns_a_dict_with_the_path_to_the_new_object(self):
        source_dossier = create(Builder("dossier").titled(u"Source"))
        target_dossier = create(Builder("dossier").titled(u"Target"))
        document = create(Builder("document")
                          .within(source_dossier)
                          .titled(u'Fo\xf6')
                          .with_dummy_content())

        data = Transporter().transport_to(
            document, 'client1', '/'.join(target_dossier.getPhysicalPath()))
        transported_doc = self.portal.unrestrictedTraverse(
            data.get('path').encode('utf-8'))

        # data
        self.assertEquals(u'Fo\xf6', transported_doc.title)
        self.assertEquals('Test data', transported_doc.file.data)

        # behavior data
        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        # dublin core
        self.assertEquals(document.created(), transported_doc.created())
        self.assertEquals(TEST_USER_ID, transported_doc.Creator())
Example #9
0
    def create_forwarding(self):
        """Create a copy of the given forwarding in the request to
        the actual yearfolder."""

        yearfolder = self.get_yearfolder()
        transporter = Transporter()
        return transporter.receive(yearfolder, self.request)
Example #10
0
    def render(self):
        if not self.context.is_submitted_document():
            raise NoSubmittedDocument()

        if self.context.is_checked_out():
            raise Unauthorized()

        with elevated_privileges():
            transporter = Transporter()
            transporter.update(self.context, self.request)

            portal_path = '/'.join(api.portal.get().getPhysicalPath())
            intids = getUtility(IIntIds)
            repository = api.portal.get_tool('portal_repository')
            comment = translate(
                _(u"Updated with a newer docment version from proposal's "
                    "dossier."),
                context=self.request)
            repository.save(obj=self.context, comment=comment)

            data = {
                'path': '/'.join(self.context.getPhysicalPath())[
                    len(portal_path) + 1:],
                'intid': intids.queryId(self.context)
                }

        # Set correct content type for JSON response
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)
Example #11
0
def accept_task_with_successor(dossier, predecessor_oguid, response_text):
    predecessor = Task.query.by_oguid(predecessor_oguid)

    # Transport the original task (predecessor) to this dossier. The new
    # response and task change is not yet done and will be done later. This
    # is necessary for beeing as transaction aware as possible.
    transporter = Transporter()
    successor = transporter.transport_from(dossier, predecessor.admin_unit_id,
                                           predecessor.physical_path)
    successor_tc = ISuccessorTaskController(successor)

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

    # copy documents and map the intids
    doc_transporter = getUtility(ITaskDocumentsTransporter)

    comment = _(u'version_message_accept_task',
                default=u'Document copied from task (task accepted)')
    intids_mapping = doc_transporter.copy_documents_from_remote_task(
        predecessor, successor, comment=comment)

    # copy the responses
    response_transporter = IResponseTransporter(successor)
    response_transporter.get_responses(predecessor.admin_unit_id,
                                       predecessor.physical_path,
                                       intids_mapping=intids_mapping)

    # Move current responsible from predecessor task to successor
    center = notification_center()
    center.add_task_responsible(successor, successor.responsible)

    # First "accept" the successor task..
    accept_task_with_response(successor, response_text)

    transaction.savepoint()
    response_text = response_text or ''
    request_data = {
        'text': response_text.encode('utf-8'),
        'successor_oguid': successor_tc.get_oguid()
    }

    response = dispatch_request(predecessor.admin_unit_id,
                                '@@accept_task_workflow_transition',
                                path=predecessor.physical_path,
                                data=request_data)

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

    # Connect the predecessor and the successor task. This needs to be done
    # that late for preventing a deadlock because of the locked tasks table.
    successor_tc.set_predecessor(predecessor_oguid)

    return successor
Example #12
0
def accept_task_with_successor(dossier, predecessor_oguid, response_text):
    predecessor = Task.query.by_oguid(predecessor_oguid)

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

    # Transport the original task (predecessor) to this dossier. The new
    # response and task change is not yet done and will be done later. This
    # is necessary for beeing as transaction aware as possible.
    transporter = Transporter()
    successor = transporter.transport_from(
        dossier, predecessor.admin_unit_id, predecessor.physical_path)
    successor_tc = ISuccessorTaskController(successor)

    # copy documents and map the intids
    doc_transporter = getUtility(ITaskDocumentsTransporter)

    comment = _(u'version_message_accept_task',
               default=u'Document copied from task (task accepted)')
    intids_mapping = doc_transporter.copy_documents_from_remote_task(
        predecessor, successor, comment=comment)

    # copy the responses
    response_transporter = IResponseTransporter(successor)
    response_transporter.get_responses(predecessor.admin_unit_id,
                                       predecessor.physical_path,
                                       intids_mapping=intids_mapping)

    # Move current responsible from predecessor task to successor
    center = notification_center()
    center.add_task_responsible(successor, successor.responsible)

    # First "accept" the successor task..
    accept_task_with_response(successor, response_text)

    transaction.savepoint()
    response_text = response_text or ''
    request_data = {'text': response_text.encode('utf-8'),
                    'successor_oguid': successor_tc.get_oguid()}

    response = dispatch_request(predecessor.admin_unit_id,
                                '@@accept_task_workflow_transition',
                                path=predecessor.physical_path,
                                data=request_data)

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

    # Connect the predecessor and the successor task. This needs to be done
    # that late for preventing a deadlock because of the locked tasks table.
    successor_tc.set_predecessor(predecessor_oguid)

    return successor
    def __call__(self):
        transporter = Transporter()
        data = []

        for doc in self.get_documents():
            data.append(transporter.extract(doc))

        # Set correct content type for JSON response
        self.request.response.setHeader("Content-type", "application/json")

        return json.dumps(data)
Example #14
0
    def __call__(self):
        transporter = Transporter()
        data = []

        for doc in self.get_documents():
            data.append(transporter.extract(doc))

        # Set correct content type for JSON response
        self.request.response.setHeader("Content-type", "application/json")

        return json.dumps(data)
    def test_transport_to_with_elevated_privileges(self):
        self.login(self.administrator)
        target_path = '/'.join(self.protected_dossier.getPhysicalPath())

        self.login(self.regular_user)
        with self.assertRaises(Unauthorized):
            Transporter().transport_to(self.task, 'plone', target_path)

        self.login(self.regular_user)
        Transporter().transport_to(
            self.task, 'plone', target_path,
            view='transporter-privileged-receive-object')
Example #16
0
    def __call__(self):
        data = self.request.get('data', None)
        assert data is not None, 'Bad request: no delivery data found'
        data = json.loads(data)

        if self.is_already_delivered(data):
            return ok_response()

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

        if not member.checkPermission('Add portal content', self.context):
            raise Unauthorized()

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

        # Create the delivered documents:
        transporter = Transporter()
        documents = []

        message = _(
            u'version_message_resolved_task',
            default=u'Document copied from task (task resolved)')

        if data.get(
            'transition') == 'task-transition-in-progress-tested-and-closed':
            message = _(
                u'version_message_closed_task',
                default=u'Document copied from task (task closed)')

        for item in data['documents']:
            doc = transporter.create(item, self.context)
            Versioner(doc).set_custom_initial_version_comment(message)

            # append `RE:` prefix to the document title
            doc.title = '%s: %s' % (
                translate(
                    _(u'answer_prefix', default=u'RE'),
                    context=self.context.REQUEST),
                doc.title)

            documents.append(doc)
            notify(ObjectAddedEvent(doc))

        # Change workflow state of predecessor task:
        util.change_task_workflow_state(
            self.context, data['transition'], text=data['text'],
            added_object=documents)

        return ok_response()
Example #17
0
    def render(self):
        data = self.request.get('data', None)
        assert data is not None, 'Bad request: no delivery data found'
        data = json.loads(data)

        if self.is_already_delivered(data):
            return ok_response()

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

        if not member.checkPermission('Add portal content', self.context):
            raise Unauthorized()

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

        # Create the delivered documents:
        transporter = Transporter()
        documents = []

        message = _(
            u'version_message_resolved_task',
            default=u'Document copied from task (task resolved)')

        if data.get(
            'transition') == 'task-transition-in-progress-tested-and-closed':
            message = _(
                u'version_message_closed_task',
                default=u'Document copied from task (task closed)')

        with CustomInitialVersionMessage(message, self.context.REQUEST):
            for item in data['documents']:
                doc = transporter.create(item, self.context)

                # append `RE:` prefix to the document title
                doc.title = '%s: %s' % (
                    translate(
                        _(u'answer_prefix', default=u'RE'),
                        context=self.context.REQUEST),
                    doc.title)

                documents.append(doc)
                notify(ObjectAddedEvent(doc))

        # Change workflow state of predecessor task:
        util.change_task_workflow_state(
            self.context, data['transition'], text=data['text'],
            added_object=documents)

        return ok_response()
    def test_transport_from_copies_the_object_inclusive_metadata_and_dublin_core_data(self):
        self.login(self.regular_user)

        transported_doc = Transporter().transport_from(
            self.empty_dossier, 'plone', '/'.join(self.document.getPhysicalPath()))

        self.assertEquals(self.document.title, transported_doc.title)
        self.assertEquals(self.document.file.data, transported_doc.file.data)

        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        self.assertEquals(self.document.created(), transported_doc.created())
        self.assertEquals(self.document.Creator(), transported_doc.Creator())
Example #19
0
 def execute(self):
     #XXX handle errors when executing across admin units.
     Transporter().transport_to(self.document,
                                self.excerpt.admin_unit_id,
                                '',
                                view='update-dossier-excerpt',
                                oguid=self.excerpt.oguid.id)
    def test_transport_to_does_not_break_deadline_datatype(self):
        self.login(self.regular_user)

        Transporter().transport_to(self.task, 'plone', '/'.join(self.empty_dossier.getPhysicalPath()))

        new_task, = self.empty_dossier.objectValues()
        self.assertFalse(isinstance(new_task.deadline, datetime))
    def test_transport_from_copies_the_object_inclusive_metadata_and_dublin_core_data(self):
        self.login(self.regular_user)

        transported_doc = Transporter().transport_from(
            self.empty_dossier, 'plone', '/'.join(self.document.getPhysicalPath()))

        self.assertEquals(self.document.title, transported_doc.title)
        self.assertEquals(self.document.file.data, transported_doc.file.data)

        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        self.assertEquals(self.document.created(), transported_doc.created())
        self.assertEquals(self.document.Creator(), transported_doc.Creator())
Example #22
0
    def execute(self):
        submitted_version = self.document.get_current_version_id()

        record = IHistory(self.proposal).append_record(
            u'document_updated',
            document_title=self.document.title,
            submitted_version=submitted_version,
        )
        history_data = advancedjson.dumps({
            'submitted_version': submitted_version,
            'uuid': record.uuid,
        })

        ProposalDocumentUpdatedActivity(self.proposal, self.proposal.REQUEST,
                                        self.document.title,
                                        submitted_version).record()

        Transporter().transport_to(
            self.document,
            self.submitted_document.submitted_admin_unit_id,
            self.submitted_document.submitted_physical_path,
            view='update-submitted-document',
            history_data=history_data)

        submitted_document = SubmittedDocument.query.get_by_source(
            self.proposal, self.document)
        submitted_document.submitted_version = submitted_version
Example #23
0
    def test_transports_tasks_correctly(self):
        source_dossier = create(Builder("dossier").titled(u"Source"))
        target_dossier = create(Builder("dossier").titled(u"Target"))
        task = create(
            Builder("task").within(source_dossier).titled(u'Fo\xf6').having(
                deadline=date(2014, 7, 1)))

        transported_task = Transporter().transport_from(
            source_dossier, 'client1', '/'.join(task.getPhysicalPath()))
    def __call__(self):
        if not self.context.is_submitted_document():
            raise NoSubmittedDocument()

        if self.context.is_checked_out():
            raise Unauthorized()

        submitted_proposal = aq_parent(aq_inner(self.context))
        history_data = advancedjson.loads(self.request.get('history_data'))

        with elevated_privileges():
            transporter = Transporter()
            transporter.update(self.context, self.request)

            IHistory(submitted_proposal).append_record(
                u'document_updated',
                document_title=self.context.title,
                submitted_version=history_data['submitted_version'],
                uuid=history_data['uuid'])

            ProposalDocumentUpdatedActivity(
                submitted_proposal, self.request, self.context.title,
                history_data['submitted_version']).record()

            portal_path = '/'.join(api.portal.get().getPhysicalPath())
            intids = getUtility(IIntIds)

            comment = translate(_(
                u"Updated with a newer docment version from proposal's "
                "dossier."),
                                context=self.request)
            Versioner(self.context).create_version(comment)

            data = {
                'path':
                '/'.join(self.context.getPhysicalPath())[len(portal_path) +
                                                         1:],
                'intid':
                intids.queryId(self.context)
            }

        # Set correct content type for JSON response
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)
Example #25
0
    def __call__(self):
        oguid_str = self.request.get('oguid')
        if not oguid_str:
            raise NotFound()

        oguid = Oguid.parse(oguid_str)

        with elevated_privileges():
            document = oguid.resolve_object()
            if document.is_checked_out():
                raise Unauthorized()

            transporter = Transporter()
            transporter.update(document, self.request)

            comment = translate(_(u"Updated with a newer excerpt version."),
                                context=self.request)
            Versioner(document).create_version(comment)
        return json.dumps({})
Example #26
0
    def test_transport_from_copies_the_object_inclusive_metadata_and_dublin_core_data(self):
        dossier = create(Builder("dossier").titled(u"Dossier"))
        document = create(Builder("document")
                          .within(dossier)
                          .titled(u'Testdocument')
                          .with_dummy_content())

        transported_doc = Transporter().transport_from(
            dossier, 'client1', '/'.join(document.getPhysicalPath()))

        self.assertEquals('Testdocument', transported_doc.title)
        self.assertEquals('Test data', transported_doc.file.data)

        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        self.assertEquals(document.created(), transported_doc.created())
        self.assertEquals(TEST_USER_ID, transported_doc.Creator())
    def test_transports_tasks_correctly(self):
        self.login(self.regular_user)

        Transporter().transport_from(
            self.empty_dossier, 'plone', '/'.join(self.subtask.getPhysicalPath()))

        new_task, = self.empty_dossier.objectValues()

        self.assertEquals(self.task.title, self.task.title)
        self.assertEquals(self.task.responsible, new_task.responsible)
        self.assertEquals(self.task.issuer, new_task.issuer)
    def test_transport_from_copies_the_object_inclusive_metadata_and_dublin_core_data(self):
        dossier = create(Builder("dossier").titled(u"Dossier"))
        document = create(Builder("document")
                          .within(dossier)
                          .titled(u'Testdocument')
                          .with_dummy_content())

        transported_doc = Transporter().transport_from(
            dossier, 'client1', '/'.join(document.getPhysicalPath()))

        self.assertEquals('Testdocument', transported_doc.title)
        self.assertEquals('Test data', transported_doc.file.data)

        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        self.assertEquals(document.created(), transported_doc.created())
        self.assertEquals(TEST_USER_ID, transported_doc.Creator())
Example #29
0
    def render(self):
        oguid_str = self.request.get('oguid')
        if not oguid_str:
            raise NotFound()

        oguid = Oguid.parse(oguid_str)

        with elevated_privileges():
            document = oguid.resolve_object()
            if document.is_checked_out():
                raise Unauthorized()

            transporter = Transporter()
            transporter.update(document, self.request)

            repository = api.portal.get_tool('portal_repository')
            comment = translate(_(u"Updated with a newer excerpt version."),
                                context=self.request)
            repository.save(obj=document, comment=comment)
        return json.dumps({})
 def test_cannot_submit_new_document_versions_outside_proposals(self):
     self.login(self.regular_user)
     url_tool = api.portal.get_tool(name="portal_url")
     physical_path = '/'.join(url_tool.getRelativeContentPath(
         self.document))
     with self.assertRaises(NoSubmittedDocument):
         Transporter().transport_to(
             self.document,
             get_current_admin_unit().id(),
             physical_path,
             view='update-submitted-document',
         )
Example #31
0
    def test_transport_to_with_elevated_privileges(self):
        source = create(Builder("dossier").titled(u"Source"))
        target = create(Builder("dossier").titled(u"Target"))
        target_path = '/'.join(target.getPhysicalPath())
        task = create(Builder("task")
                      .within(source)
                      .titled(u'Fo\xf6')
                      .having(deadline=date(2014, 7, 1)))

        create(Builder('user').named('Hugo', 'Boss'))
        api.user.grant_roles(username=u'hugo.boss',
                             obj=source,
                             roles=['Contributor', 'Editor', 'Reader'])
        self.login(u'hugo.boss')

        with self.assertRaises(Unauthorized):
            Transporter().transport_to(task, 'client1', target_path)

        Transporter().transport_to(
            task, 'client1', target_path,
            view='transporter-privileged-receive-object')
    def test_transport_to_returns_a_dict_with_the_path_to_the_new_object(self):
        self.login(self.regular_user)

        data = Transporter().transport_to(
            self.document, 'plone', '/'.join(self.empty_dossier.getPhysicalPath()))

        transported_doc = self.portal.unrestrictedTraverse(data.get('path').encode('utf-8'))

        # data
        self.assertEquals(self.document.title, transported_doc.title)
        self.assertEquals(self.document.file.data, transported_doc.file.data)

        # behavior data
        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        # dublin core
        self.assertEquals(self.document.created(), transported_doc.created())
        self.assertEquals(self.document.Creator(), transported_doc.Creator())
    def test_transport_to_returns_a_dict_with_the_path_to_the_new_object(self):
        self.login(self.regular_user)

        data = Transporter().transport_to(
            self.document, 'plone', '/'.join(self.empty_dossier.getPhysicalPath()))

        transported_doc = self.portal.unrestrictedTraverse(data.get('path').encode('utf-8'))

        # data
        self.assertEquals(self.document.title, transported_doc.title)
        self.assertEquals(self.document.file.data, transported_doc.file.data)

        # behavior data
        self.assertEquals(u'unprotected',
                          IClassification(transported_doc).classification)
        self.assertEquals(u'unchecked',
                          IClassification(transported_doc).public_trial)

        # dublin core
        self.assertEquals(self.document.created(), transported_doc.created())
        self.assertEquals(self.document.Creator(), transported_doc.Creator())
Example #34
0
    def render(self):
        oguid_str = self.request.get('oguid')
        if not oguid_str:
            raise NotFound()

        oguid = Oguid.parse(oguid_str)

        with elevated_privileges():
            document = oguid.resolve_object()
            if document.is_checked_out():
                raise Unauthorized()

            transporter = Transporter()
            transporter.update(document, self.request)

            repository = api.portal.get_tool('portal_repository')
            comment = translate(
                _(u"Updated with a newer excerpt version."),
                context=self.request)
            repository.save(obj=document, comment=comment)
        return json.dumps({})
Example #35
0
    def test_cannot_submit_new_document_versions_outside_proposals(self):
        document = create(
            Builder('document').within(
                self.dossier).titled(u'Another Document').with_dummy_content())

        url_tool = api.portal.get_tool(name="portal_url")
        physical_path = '/'.join(url_tool.getRelativeContentPath(document))

        with self.assertRaises(NoSubmittedDocument):
            Transporter().transport_to(self.document,
                                       get_current_admin_unit().id(),
                                       physical_path,
                                       view='update-submitted-document')
 def test_transport_to_does_not_break_deadline_datatype(self):
     source = create(Builder("dossier").titled(u"Source"))
     target = create(Builder("dossier").titled(u"Target"))
     target_path = '/'.join(target.getPhysicalPath())
     task = create(
         Builder("task").within(source).titled(u'Fo\xf6').having(
             deadline=date(2014, 7, 1)), )
     Transporter().transport_to(
         task,
         'client1',
         target_path,
         view='transporter-privileged-receive-object')
     self.assertFalse(isinstance(target.getFirstChild().deadline, datetime))
    def __call__(self):
        if not self.context.is_submitted_document():
            raise NoSubmittedDocument()

        if self.context.is_checked_out():
            raise Unauthorized()

        submitted_proposal = aq_parent(aq_inner(self.context))
        history_data = advancedjson.loads(self.request.get('history_data'))

        with elevated_privileges():
            transporter = Transporter()
            transporter.update(self.context, self.request)

            IHistory(submitted_proposal).append_record(
                u'document_updated',
                document_title=self.context.title,
                submitted_version=history_data['submitted_version'],
                uuid=history_data['uuid']
            )

            portal_path = '/'.join(api.portal.get().getPhysicalPath())
            intids = getUtility(IIntIds)

            comment = translate(
                _(u"Updated with a newer docment version from proposal's "
                  "dossier."), context=self.request)
            Versioner(self.context).create_version(comment)

            data = {
                'path': '/'.join(self.context.getPhysicalPath())[
                    len(portal_path) + 1:],
                'intid': intids.queryId(self.context)
                }

        # Set correct content type for JSON response
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)
    def refuse_forwarding(self, forwarding):
        self.portal.REQUEST.set(REQUEST_KEY,
                                json.dumps(Transporter().extract(forwarding)))

        self.portal.REQUEST.set('review_state', 'forwarding-state-refused')
        response = self.portal.unrestrictedTraverse('store_refused_forwarding')()
        response = json.loads(response)

        if response.get('remote_task'):
            copy = self.portal.restrictedTraverse(
                response.get('remote_task').encode('utf-8'))
        else:
            copy = None
        return response.get('status'), copy
Example #39
0
    def execute(self):
        Transporter().transport_to(
            self.document,
            self.submitted_document.submitted_admin_unit_id,
            self.submitted_document.submitted_physical_path,
            view='update-submitted-document')

        session = create_session()
        proposal_model = self.proposal.load_model()

        submitted_version = self.document.get_current_version()
        submitted_document = SubmittedDocument.query.get_by_source(
            self.proposal, self.document)
        submitted_document.submitted_version = submitted_version

        session.add(
            DocumentUpdated(proposal=proposal_model,
                            submitted_document=submitted_document,
                            submitted_version=submitted_version,
                            document_title=self.document.title))
Example #40
0
def accept_forwarding_with_successor(
    context, predecessor_oguid, response_text, dossier=None):

    # the predessecor (the forwarding on the remote client)
    predecessor = Task.query.by_oguid(predecessor_oguid)

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

    # transport the remote forwarding to the inbox or actual yearfolder
    transporter = Transporter()
    inbox = get_current_inbox(context)
    if dossier:
        yearfolder = get_current_yearfolder(inbox=inbox)
        successor_forwarding = transporter.transport_from(
            yearfolder, predecessor.admin_unit_id, predecessor.physical_path)
    else:
        successor_forwarding = transporter.transport_from(
            inbox, predecessor.admin_unit_id, predecessor.physical_path)

    # Replace the issuer with the current inbox
    successor_forwarding.issuer = get_current_org_unit().inbox().id()

    successor_tc = ISuccessorTaskController(successor_forwarding)

    # copy documents and map the intids
    doc_transporter = getUtility(ITaskDocumentsTransporter)

    comment = _(
        u'version_message_accept_forwarding',
        default=u'Document copied from forwarding (forwarding accepted)')
    intids_mapping = doc_transporter.copy_documents_from_remote_task(
        predecessor, successor_forwarding, comment=comment)

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

    # Remove current responsible from predecessor and add issuer
    # and responsible to successor's watcher.
    center = notification_center()
    center.remove_task_responsible(Oguid.parse(predecessor_oguid),
                                   successor_forwarding.responsible)
    center.add_task_responsible(successor_forwarding,
                                successor_forwarding.responsible)
    center.add_task_issuer(successor_forwarding, successor_forwarding.issuer)

    # 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

        # Predefine the task_type to avoid tasks with an invalid task_type
        fielddata['task_type'] = FORWARDING_SUCCESSOR_TYPE

        # 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_current_admin_unit().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 = dispatch_request(predecessor.admin_unit_id,
                                '@@store_forwarding_in_yearfolder',
                                path=predecessor.physical_path,
                                data=request_data)

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

    if dossier:
        # Update watchers for created successor forwarding and task
        center = notification_center()
        center.remove_task_responsible(successor_forwarding, task.responsible)
        center.add_task_responsible(task, task.responsible)

        # 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
Example #41
0
    def deliver_documents_and_complete_task(self, formdata, response):
        """Delivers the selected documents to the predecesser task and
        complete the task:

        - Copy the documents to the predecessor task (no new responses)
        - Execute workflow transition (no new response)
        - Add a new response indicating the workflow transition, the added
        documents and containing the entered response text.
        """

        # add documents to the response
        response.added_object = PersistentList()

        predecessor = Task.query.by_oguid(self.context.predecessor)

        transporter = Transporter()
        intids = getUtility(IIntIds)

        data = {'documents': [],
                'text': formdata['text'],
                'transition': formdata['transition']}

        related_ids = []
        if getattr(self.context, 'relatedItems'):
            related_ids = [item.to_id for item in self.context.relatedItems]

        for doc_intid in formdata['documents']:
            doc = intids.getObject(int(doc_intid))
            data['documents'].append(transporter.extract(doc))

            # add a releation when a document from the dossier was selected
            if int(doc_intid) not in related_ids:
                # check if its a relation
                if aq_parent(aq_inner(doc)) != self.context:
                    # add relation to doc on task
                    if self.context.relatedItems:
                        self.context.relatedItems.append(
                            RelationValue(int(doc_intid)))
                    else:
                        self.context.relatedItems = [
                            RelationValue(int(doc_intid))]

                    # add response change entry for this relation
                    if not response.relatedItems:
                        response.relatedItems = [RelationValue(int(doc_intid))]
                    else:
                        response.relatedItems.append(
                            RelationValue(int(doc_intid)))

                    # set relation flag
                    doc._v__is_relation = True
                    response.add_change('relatedItems',
                        _(u'label_related_items', default=u"Related Items"),
                        '',
                        linked(doc, doc.Title()))

                else:
                    # add entry to the response for this document
                    response.added_object.append(RelationValue(int(doc_intid)))
            else:
                # append only the relation on the response
                doc._v__is_relation = True
                response.add_change('relatedItems',
                    _(u'label_related_items', default=u"Related Items"),
                    '',
                    linked(doc, doc.Title()))

        request_data = {'data': json.dumps(data)}
        response = dispatch_request(
            predecessor.admin_unit_id,
            '@@complete_successor_task-receive_delivery',
            predecessor.physical_path,
            data=request_data)

        if response.read().strip() != 'OK':
            raise Exception('Delivering documents and updating task failed '
                            'on remote client %s.' % predecessor.admin_unit_id)
Example #42
0
 def execute(self):
     return Transporter().transport_to(
         self.source, self.target_admin_unit_id, self.target_path,
         view='recieve-excerpt-document', **self.kwargs)
Example #43
0
 def execute(self):
     return Transporter().transport_to(
         self.source, self.target_admin_unit_id, self.target_path,
         **self.kwargs)
Example #44
0
    def deliver_documents_and_complete_task(self, formdata, response):
        """Delivers the selected documents to the predecesser task and
        complete the task:

        - Copy the documents to the predecessor task (no new responses)
        - Execute workflow transition (no new response)
        - Add a new response indicating the workflow transition, the added
        documents and containing the entered response text.
        """

        predecessor = Task.query.by_oguid(self.context.predecessor)

        transporter = Transporter()
        intids = getUtility(IIntIds)

        data = {
            'documents': [],
            'text': formdata['text'],
            'transition': formdata['transition']
        }

        related_ids = []
        if getattr(self.context, 'relatedItems'):
            related_ids = [item.to_id for item in self.context.relatedItems]

        for doc_intid in formdata['documents']:
            doc = intids.getObject(int(doc_intid))
            data['documents'].append(transporter.extract(doc))

            # add a releation when a document from the dossier was selected
            if int(doc_intid) not in related_ids:
                # check if its a relation
                if aq_parent(aq_inner(doc)) != self.context:
                    # add relation to doc on task
                    if self.context.relatedItems:
                        self.context.relatedItems.append(
                            RelationValue(int(doc_intid)))
                    else:
                        self.context.relatedItems = [
                            RelationValue(int(doc_intid))
                        ]

                    # add response change entry for this relation
                    response.add_related_item(RelationValue(int(doc_intid)))

                    # set relation flag
                    doc._v__is_relation = True
                    response.add_change(
                        'relatedItems', '', linked(doc, doc.Title()),
                        _(u'label_related_items', default=u"Related Items"))

                else:
                    # add entry to the response for this document
                    response.added_objects.append(RelationValue(
                        int(doc_intid)))
            else:
                # append only the relation on the response
                doc._v__is_relation = True
                response.add_change(
                    'relatedItems', '', linked(doc, doc.Title()),
                    _(u'label_related_items', default=u"Related Items"))

        request_data = {'data': json.dumps(data)}
        response = dispatch_request(
            predecessor.admin_unit_id,
            '@@complete_successor_task-receive_delivery',
            predecessor.physical_path,
            data=request_data)

        response_body = response.read()
        if response_body.strip() != 'OK':
            raise Exception('Delivering documents and updating task failed '
                            'on remote client %s.' % predecessor.admin_unit_id)
Example #45
0
 def execute(self):
     return Transporter().transport_to(self.source,
                                       self.target_admin_unit_id,
                                       self.target_path,
                                       view='recieve-submitted-document')