Ejemplo n.º 1
0
    def get_linked_document_for(self, document):
        """
        Execute the corresponding smart links conditions for the document
        provided and return the resulting document queryset.
        """
        if document.document_type.pk not in self.document_types.values_list(
                'pk', flat=True):
            raise Exception(
                _('This smart link is not allowed for the selected '
                  'document\'s type.'))

        smart_link_query = Q()

        for condition in self.conditions.filter(enabled=True):
            template = Template(template_string=condition.expression)

            condition_query = Q(
                **{
                    '%s__%s' % (condition.foreign_document_data, condition.operator):
                    template.render(context={'document': document})
                })
            if condition.negated:
                condition_query = ~condition_query

            if condition.inclusion == INCLUSION_AND:
                smart_link_query &= condition_query
            elif condition.inclusion == INCLUSION_OR:
                smart_link_query |= condition_query

        if smart_link_query:
            return Document.objects.filter(smart_link_query)
        else:
            return Document.objects.none()
Ejemplo n.º 2
0
 def get_dynamic_label(self, document):
     """
     If the smart links was created using a template label instead of a
     static label, resolve the template and return the result.
     """
     if self.dynamic_label:
         try:
             template = Template(template_string=self.dynamic_label)
             return template.render(context={'document': document})
         except Exception as exception:
             return _('Error generating dynamic label; %s' %
                      force_text(s=exception))
     else:
         return None
Ejemplo n.º 3
0
def widget_event_actor_link(context, attribute=None):
    entry = context['object']

    ContentType = apps.get_model(
        app_label='contenttypes', model_name='ContentType'
    )

    if attribute:
        entry = getattr(entry, attribute)

    if entry.actor == entry.target:
        label = _('System')
        url = None
    else:
        label = entry.actor
        content_type = ContentType.objects.get_for_model(model=entry.actor)

        url = reverse(
            viewname='events:events_for_object', kwargs={
                'app_label': content_type.app_label, 'model': content_type.model,
                'object_id': entry.actor.pk
            }
        )

    if url:
        return Template(
            template_string='<a href="{{ url }}">{{ label }}</a>'
        ).render(context={'label': entry.actor, 'url': url})
    else:
        return label
Ejemplo n.º 4
0
class ObjectLinkWidget(object):
    template_string = '<a href="{{ url }}">{{ object_type }}{{ label }}</a>'

    def __init__(self):
        self.template = Template(template_string=self.template_string)

    def render(self, name=None, value=None):
        label = ''
        object_type = ''
        url = None

        if value:
            label = force_text(value)
            object_type = '{}: '.format(value._meta.verbose_name)
            try:
                url = value.get_absolute_url()
            except AttributeError:
                url = None

            if getattr(value, 'is_staff', None) or getattr(value, 'is_superuser', None):
                # Don't display a anchor to for the user details view for
                # superusers and staff, the details view filters them. Staff
                # and admin users are not manageable by the normal user views.
                url = '#'
                return '{}{}'.format(object_type, label)

        return self.template.render(
            context={
                'label': label, 'object_type': object_type,
                'url': url or '#'
            }
        )
Ejemplo n.º 5
0
 def evaluate_condition(self, workflow_instance):
     if self.has_condition():
         return Template(template_string=self.condition).render(
             context={'workflow_instance': workflow_instance}
         ).strip()
     else:
         return True
Ejemplo n.º 6
0
 def get_rendered_string(self, preserve_extension=False):
     if preserve_extension:
         filename, extension = os.path.splitext(self.document.label)
         return '{} ({}){}'.format(
             filename, self.get_rendered_timestamp(), extension
         )
     else:
         return Template(
             template_string='{{ instance.document }} - {{ instance.timestamp }}'
         ).render(context={'instance': self})
Ejemplo n.º 7
0
 def execute(self, context):
     for document_page in context['document'].pages_valid:
         context['document_page'] = document_page
         if self.evaluate_condition(
                 context=context,
                 condition=self.form_data['page_condition']):
             DocumentPageOCRContent.objects.update_or_create(
                 document_page=document_page,
                 defaults={
                     'content':
                     Template(template_string=self.form_data['page_content']
                              ).render(context=context)
                 })
Ejemplo n.º 8
0
    def render_field(self, field_name, context):
        try:
            result = Template(
                template_string=self.form_data.get(field_name, '')).render(
                    context=context)
        except Exception as exception:
            raise WorkflowStateActionError(
                _('%(field_name)s template error: %(exception)s') % {
                    'field_name': field_name,
                    'exception': exception
                })

        logger.debug('%s template result: %s', field_name, result)

        return result
Ejemplo n.º 9
0
    def send_document(self,
                      document,
                      to,
                      subject='',
                      body='',
                      as_attachment=False,
                      _user=None):
        """
        Send a document using this user mailing profile.
        """
        context_dictionary = {
            'link':
            furl(setting_project_url.value).join(
                document.get_absolute_url()).tostr(),
            'document':
            document
        }

        body_template = Template(template_string=body)
        body_html_content = body_template.render(context=context_dictionary)

        subject_template = Template(template_string=subject)
        subject_text = strip_tags(
            subject_template.render(context=context_dictionary))

        attachments = []
        if as_attachment:
            with document.open() as file_object:
                attachments.append({
                    'content': file_object.read(),
                    'filename': document.label,
                    'mimetype': document.file_mimetype
                })

        return self.send(attachments=attachments,
                         body=body_html_content,
                         subject=subject_text,
                         to=to,
                         _event_action_object=document,
                         _user=_user)
Ejemplo n.º 10
0
 def evaluate_condition(self, context, condition=None):
     if condition:
         return Template(template_string=condition).render(
             context=context).strip()
     else:
         return False
Ejemplo n.º 11
0
    def index_document(self,
                       document,
                       acquire_lock=True,
                       index_instance_node_parent=None):
        # Start transaction after the lock in case the locking backend uses
        # the database.
        try:
            if acquire_lock:
                lock = LockingBackend.get_instance().acquire_lock(
                    self.get_lock_string())
        except LockError:
            raise
        else:
            try:
                logger.debug('IndexTemplateNode; Indexing document: %s',
                             document)

                if not index_instance_node_parent:
                    # I'm the root
                    with transaction.atomic():
                        index_instance_root_node = self.get_instance_root_node(
                        )

                        for child in self.get_children():
                            child.index_document(document=document,
                                                 acquire_lock=False,
                                                 index_instance_node_parent=
                                                 index_instance_root_node)
                elif self.enabled:
                    with transaction.atomic():
                        logger.debug(
                            'IndexTemplateNode; non parent: evaluating')
                        logger.debug('My parent template is: %s', self.parent)
                        logger.debug('My parent instance node is: %s',
                                     index_instance_node_parent)
                        logger.debug(
                            'IndexTemplateNode; Evaluating template: %s',
                            self.expression)

                        try:
                            template = Template(
                                template_string=self.expression)
                            result = template.render(
                                context={'document': document})
                        except Exception as exception:
                            logger.debug('Evaluating error: %s', exception)
                            error_message = _(
                                'Error indexing document: %(document)s; expression: '
                                '%(expression)s; %(exception)s') % {
                                    'document': document,
                                    'expression': self.expression,
                                    'exception': exception
                                }
                            logger.debug(error_message)
                        else:
                            logger.debug('Evaluation result: %s', result)

                            if result:
                                index_instance_node, created = self.index_instance_nodes.get_or_create(
                                    parent=index_instance_node_parent,
                                    value=result)

                                if self.link_documents:
                                    index_instance_node.documents.add(document)

                                for child in self.get_children():
                                    child.index_document(
                                        document=document,
                                        acquire_lock=False,
                                        index_instance_node_parent=
                                        index_instance_node)
            finally:
                if acquire_lock:
                    lock.release()
Ejemplo n.º 12
0
 def get_rendered_timestamp(self):
     return Template(
         template_string='{{ instance.timestamp }}'
     ).render(
         context={'instance': self}
     )
Ejemplo n.º 13
0
 def __init__(self):
     self.template = Template(template_string=self.template_string)
Ejemplo n.º 14
0
 def get_lookup_values(self):
     template = Template(template_string=self.lookup)
     return MetadataType.comma_splitter(
         template.render(context=MetadataLookup.get_as_context())
     )
Ejemplo n.º 15
0
 def get_default_value(self):
     template = Template(template_string=self.default)
     return template.render()
Ejemplo n.º 16
0
 def get_url_for(self, document):
     return Template(template_string=self.template).render(
         context={'document': document})