Ejemplo n.º 1
0
def download_action_id_content(request, act_id):
    action = get_object_or_404(Action, pk=int(act_id))
    step_index = int_arg(request.GET['step_index'])
    file_format = request.GET['format']

    # decode according mime type CSV or XLSX
    action_controller = ActionController(action)

    exporter = ActionDataExporter(action_controller, step_index)

    if not action_controller.is_current_step_valid:
        raise SuspiciousOperation(_("The step index is not valid"))

    if not action_controller.has_step_data(step_index):
        raise SuspiciousOperation(_("The step index has no data"))

    if file_format == 'csv':
        mime_type = 'text/csv'
        file_ext = ".csv"
        data = exporter.export_data_as_csv()
    elif file_format == 'xlsx':
        mime_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        file_ext = ".xlsx"
        data = exporter.export_data_as_xslx()
    else:
        raise SuspiciousOperation("Invalid format")

    file_name = "Action%sDataStep%i" % (act_id, step_index+1,) + file_ext

    response = StreamingHttpResponse(data, content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename="' + file_name + '"'
    response['Content-Length'] = exporter.size

    return response
Ejemplo n.º 2
0
def get_descriptor_values(request, des_id):
    """
    Get the list of values for a given descriptor and according to the current language.
    """
    results_per_page = int_arg(request.GET.get('more', 30))
    cursor = request.GET.get('cursor')
    limit = results_per_page

    sort_by = request.GET.get('sort_by', 'id')

    descriptor = get_object_or_404(Descriptor, id=int(des_id))

    if sort_by.startswith('-'):
        order_by = sort_by[1:]
        reverse = True
    elif sort_by.startswith('+'):
        order_by = sort_by[1:]
        reverse = False
    else:
        order_by = sort_by
        reverse = False

    prev_cursor, next_cursor, values_list = descriptor.get_values(
        order_by, reverse, cursor, limit)

    results = {
        'sort_by': sort_by,
        'prev': prev_cursor,
        'cursor': cursor,
        'next': next_cursor,
        'format': descriptor.format,
        'items': values_list,
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 3
0
def get_action_list_for_entity_id(request, ent_id):
    # @todo
    results_per_page = int_arg(request.GET.get('more', 30))
    cursor = json.loads(request.GET.get('cursor', 'null'))
    limit = results_per_page
    sort_by = json.loads(request.GET.get('sort_by', '[]'))

    # @todo how to manage permission to list only auth actions

    if not len(sort_by) or sort_by[-1] not in ('id', '+id', '-id'):
        order_by = sort_by + ['id']
    else:
        order_by = sort_by

    from main.cursor import CursorQuery
    cq = CursorQuery(ActionToEntity)

    # cq = ActionToEntity.objects.filter(entity_id=int(ent_id))

    # @todo filter for action relating
    cq.inner_join(Action, related_name='id', to_related_name='action_id', entity=int(ent_id))
    cq.filter(entity=int(ent_id))

    if request.GET.get('search'):
        search = json.loads(request.GET['search'])
        cq.filter(search)

    if request.GET.get('filters'):
        filters = json.loads(request.GET['filters'])
        cq.filter(filters)

    cq.cursor(cursor, order_by)
    cq.order_by(order_by).limit(limit)
    # print(cq.sql())
    action_list = []

    for action in cq:
        a = {
            'id': action.id,
            'entity': action.entity_id,
            'entity_type': action.entity_type_id,
            'type': action.type_id,
            'data': action.data,
            'completed': action.completed,
            'created_date': action.created_date.strftime("%Y-%m-%d %H:%M:%S")
        }

        action_list.append(a)

    results = {
        'perms': [],
        'items': action_list,
        'prev': cq.prev_cursor,
        'cursor': cursor,
        'next': cq.next_cursor,
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 4
0
def get_action_list(request):
    results_per_page = int_arg(request.GET.get('more', 30))
    cursor = json.loads(request.GET.get('cursor', 'null'))
    limit = results_per_page
    sort_by = json.loads(request.GET.get('sort_by', '[]'))

    # @todo how to manage permission to list only auth actions

    if not len(sort_by) or sort_by[-1] not in ('id', '+id', '-id'):
        order_by = sort_by + ['id']
    else:
        order_by = sort_by

    from main.cursor import CursorQuery
    cq = CursorQuery(Action)

    if request.GET.get('search'):
        search = json.loads(request.GET['search'])
        cq.filter(search)

    if request.GET.get('filters'):
        filters = json.loads(request.GET['filters'])
        cq.filter(filters)

    cq.cursor(cursor, order_by)
    cq.order_by(order_by).limit(limit)

    action_list = []

    for action in cq:
        a = {
            'id': action.id,
            'name': action.name,
            'action_type': action.action_type_id,
            'data': action.data,
            'user': action.user.username,
            'completed': action.completed,
            'created_date': action.created_date.strftime("%Y-%m-%d %H:%M:%S")
        }

        action_list.append(a)

    results = {
        'perms': [],
        'items': action_list,
        'prev': cq.prev_cursor,
        'cursor': cursor,
        'next': cq.next_cursor,
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 5
0
def get_action_id_data_for_step(request, act_id, step_idx):
    action = get_object_or_404(Action, pk=int(act_id))
    step_index = int_arg(step_idx)

    action_data = get_object_or_404(ActionData, action=action, step_index=step_idx)

    results = {
        'action': action.id,
        'step': step_index,
        'data': action_data.data,
        'type': action_data.data_type
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 6
0
def get_descriptor_list(request):
    results_per_page = int_arg(request.GET.get('more', 30))
    cursor = json.loads(request.GET.get('cursor', 'null'))
    limit = results_per_page
    sort_by = json.loads(request.GET.get('sort_by', '[]'))

    if not len(sort_by) or sort_by[-1] not in ('id', '+id', '-id'):
        order_by = sort_by + ['id']
    else:
        order_by = sort_by

    cq = CursorQuery(Descriptor)

    if request.GET.get('filters'):
        cq.filter(json.loads(request.GET['filters']))

    if request.GET.get('search'):
        cq.filter(json.loads(request.GET['search']))

    cq.cursor(cursor, order_by)
    cq.order_by(order_by).limit(limit)

    items = []

    for descriptor in cq:
        d = {
            'id': descriptor.id,
            'name': descriptor.name,
            'code': descriptor.code,
            'label': descriptor.get_label(),
            'group_name': descriptor.group_name,
            'description': descriptor.description,
            'can_delete': descriptor.can_delete,
            'can_modify': descriptor.can_modify,
            'format': descriptor.format
        }

        items.append(d)

    results = {
        'perms': [],
        'items': items,
        'prev': cq.prev_cursor,
        'cursor': cursor,
        'next': cq.next_cursor,
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 7
0
def get_index_list(request):
    results_per_page = int_arg(request.GET.get('more', 30))
    cursor = json.loads(request.GET.get('cursor', 'null'))
    limit = results_per_page
    sort_by = json.loads(request.GET.get('sort_by', '[]'))

    if not len(sort_by) or sort_by[-1] not in ('id', '+id', '-id'):
        order_by = sort_by + ['id']
    else:
        order_by = sort_by

    cq = CursorQuery(DescriptorIndex)

    if request.GET.get('filters'):
        cq.filter(json.loads(request.GET['filters']))

    if request.GET.get('search'):
        cq.filter(json.loads(request.GET['search']))

    cq.cursor(cursor, order_by)
    cq.order_by(order_by).limit(limit)

    items = []

    for index in cq:
        d = {
            'id': index.id,
            'descriptor': index.descriptor.name,
            'target': index.target.name.capitalize(),
            'type': JSONBFieldIndexType(index.type).name
        }

        items.append(d)

    results = {
        'perms': [],
        'items': items,
        'prev': cq.prev_cursor,
        'cursor': cursor,
        'next': cq.next_cursor,
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 8
0
def create_action(request):
    action_type_id = int_arg(request.data.get('action_type'))
    name = request.data.get('name')
    description = request.data.get('description', '')
    user = request.user

    action_type = get_object_or_404(ActionType, pk=action_type_id)

    action_controller = ActionController(action_type, user)
    action = action_controller.create(name, description)

    results = {
        'id': action.id,
        'name': action.name,
        'description': action.description,
        'completed': action.completed,
        'user': user.username,
        'action_type': action.action_type_id,
        'data': action.data,
        'created_date': action.created_date.strftime("%Y-%m-%d %H:%M:%S")
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 9
0
def search_descriptor(request):
    """
    Filters descriptors by name.
    @todo could needs pagination
    """
    filters = json.loads(request.GET['filters'])
    page = int_arg(request.GET.get('page', 1))

    descriptors = None

    if filters['method'] == 'ieq' and 'name' in filters['fields']:
        descriptors = Descriptor.objects.filter(name__iexact=filters['name'])
    elif filters['method'] == 'icontains' and 'name' in filters['fields']:
        descriptors = Descriptor.objects.filter(
            name__icontains=filters['name'])

    # descriptors = descriptors.annotate(Count('types_set'))

    descriptors_list = []

    if descriptors:
        for descriptor in descriptors:
            descriptors_list.append({
                'id': descriptor.id,
                'name': descriptor.name,
                'code': descriptor.code,
                'label': descriptor.get_label(),
                'group_name': descriptor.group_name,
                'description': descriptor.description,
                'can_delete': descriptor.can_delete,
                'can_modify': descriptor.can_modify,
                'format': descriptor.format
            })

    response = {'items': descriptors_list, 'page': page}

    return HttpResponseRest(request, response)
Ejemplo n.º 10
0
def search_display_value_for_descriptor(request, des_id):
    """
    Search and returns a list of value from the related descriptor and formatted as described.
    """
    results_per_page = int_arg(request.GET.get('more', 30))
    cursor = request.GET.get('cursor')
    limit = results_per_page

    descriptor = get_object_or_404(Descriptor, id=int(des_id))

    format_type = descriptor.format
    list_type = format_type.get('list_type', '')

    if not list_type:
        raise SuspiciousOperation(
            _("This descriptor does not contains a list"))

    search_field = format_type.get('search_field', 'value0')
    value = request.GET['value']

    values = []

    prev_cursor, next_cursor, values_list = descriptor.search_values(
        value, search_field, cursor, limit)

    if format_type['display_fields'] == 'value0':
        for value in values_list:
            values.append({
                'id': value['id'],
                'value': value['id'],
                'label': value['value0']
            })
    elif format_type['display_fields'] == 'value1':
        for value in values_list:
            values.append({
                'id': value['id'],
                'value': value['id'],
                'label': value['value1']
            })
    elif format_type['display_fields'] == 'value0-value1':
        for value in values_list:
            values.append({
                'id':
                value['id'],
                'value':
                value['id'],
                'label':
                "%s - %s" % (value['value0'], value['value1'])
            })
    elif format_type['display_fields'] == 'ordinal-value0':
        for value in values_list:
            values.append({
                'id':
                value['id'],
                'value':
                value['id'],
                'label':
                "%i - %s" % (value['ordinal'], value['value0'])
            })
    elif format_type['display_fields'] == 'hier0-value1':
        for value in values_list:
            shift_size = value['value0'].count('.')

            values.append({
                'id': value['id'],
                'value': value['id'],
                'label': value['value1'],
                'offset': shift_size
            })

    results = {
        'items': values,
        'prev': prev_cursor,
        'cursor': cursor,
        'next': next_cursor
    }

    return HttpResponseRest(request, results)
Ejemplo n.º 11
0
def search_audit_value_history_for_entity(request):
    """
    Search audit entries related to a specific entity according to its content type and unique id.
    And returns history for a specific value_name.
    @note Entity.natural_name() could in some cases make an extra query.
    """
    results_per_page = int_arg(request.GET.get('more', 30))

    app_label = request.GET['app_label']
    validictory.validate(app_label, Entity.NAME_VALIDATOR)

    model = request.GET['model']
    validictory.validate(model, Entity.NAME_VALIDATOR)

    object_id = int_arg(request.GET['object_id'])

    value_name = request.GET['value']

    if value_name.startswith('#'):
        value_name = value_name[1:]
        is_descriptor = True
    else:
        is_descriptor = False

    content_type = ContentType.objects.get_by_natural_key(app_label, model)
    entity = content_type.get_object_for_this_type(id=object_id)

    validictory.validate(value_name, entity.NAME_VALIDATOR)

    # @todo check permissions

    cursor = request.GET.get('cursor')
    limit = results_per_page

    if cursor:
        cursor = json.loads(cursor)
        cursor_time, cursor_id = cursor
        qs = Audit.objects.filter(
            Q(content_type=content_type), Q(object_id=object_id),
            Q(timestamp__lt=cursor_time) |
            (Q(timestamp=cursor_time) & Q(id__lt=cursor_id)))
    else:
        qs = Audit.objects.filter(content_type=content_type,
                                  object_id=object_id)

    # interested in change of value so update and create only
    qs = qs.filter(type__in=[AuditType.UPDATE, AuditType.CREATE])

    audits = qs.order_by('-timestamp').order_by('-id')[:limit]

    audit_list = []

    for audit in audits:
        if audit.type == AuditType.CREATE.value:
            if is_descriptor:
                descriptors = audit.fields.get("descriptors")
                if descriptors is None:
                    continue

                if value_name not in descriptors:
                    continue

                value = descriptors.get(value_name)
            else:
                if value_name not in audit.fields:
                    continue

                value = audit.fields.get(value_name)

        elif "descriptors" in audit.fields.get("updated_fields", []):
            if is_descriptor:
                descriptors = audit.fields.get("descriptors")
                if descriptors is None:
                    continue

                if value_name not in descriptors:
                    continue

                value = descriptors.get(value_name)
            else:
                if value_name not in audit.fields:
                    continue

                value = audit.fields.get(value_name)
        else:
            continue

        audit_list.append({
            'id': audit.id,
            'user_id': audit.user.id,
            'username': audit.user.username,
            'timestamp': audit.timestamp,
            'type': audit.type,
            'value': value
        })

    # prev cursor (desc order)
    if len(audit_list) > 0:
        audit = audit_list[0]
        prev_cursor = (audit['timestamp'].isoformat(), audit['id'])
    else:
        prev_cursor = None

    # next cursor (desc order)
    if len(audit_list) > 0:
        audit = audit_list[-1]
        next_cursor = (audit['timestamp'].isoformat(), audit['id'])
    else:
        next_cursor = None

    results = {
        'perms': [],
        'items': audit_list,
        'prev': prev_cursor,
        'cursor': cursor,
        'next': next_cursor
    }

    return HttpResponseRest(request, results)