Esempio n. 1
0
def action_index(
    request: HttpRequest,
    wid: Optional[int] = None,
    workflow: Optional[Workflow] = None,
) -> HttpResponse:
    """Show all the actions attached to the workflow.

    :param request: HTTP Request

    :param pk: Primary key of the workflow object to use

    :return: HTTP response
    """
    # Reset object to carry action info throughout dialogs
    set_action_payload(request.session)
    request.session.save()

    return render(
        request,
        'action/index.html',
        {
            'workflow': workflow,
            'table': ActionTable(workflow.actions.all(), orderable=False),
        },
    )
Esempio n. 2
0
def edit(
    request: HttpRequest,
    pk: int,
    workflow: Optional[Workflow] = None,
) -> HttpResponse:
    """Edit an existing scheduled email action.

    :param request: HTTP request

    :param pk: primary key of the action

    :return: HTTP response
    """
    # Distinguish between creating a new element or editing an existing one
    new_item = request.path.endswith(
        reverse('scheduler:create', kwargs={'pk': pk}))

    if new_item:
        action = workflow.actions.filter(pk=pk, ).filter(
            Q(workflow__user=request.user)
            | Q(workflow__shared=request.user), ).first()
        if not action:
            return redirect('home')
        s_item = None
    else:
        # Get the scheduled action from the parameter in the URL
        s_item = ScheduledAction.objects.filter(pk=pk).first()
        if not s_item:
            return redirect('home')
        action = s_item.action

    # Get the payload from the session, and if not, use the given one
    op_payload = request.session.get(action_session_dictionary)
    if not op_payload:
        op_payload = {
            'action_id': action.id,
            'prev_url': reverse('scheduler:create', kwargs={'pk': action.id}),
            'post_url': reverse('scheduler:finish_scheduling'),
        }
        set_action_payload(request.session, op_payload)
        request.session.save()

    # Verify that celery is running!
    if not celery_is_up():
        messages.error(
            request,
            _('Unable to schedule actions due to a misconfiguration. ' +
              'Ask your system administrator to enable queueing.'))
        return redirect(reverse('action:index'))

    if action.action_type == Action.personalized_text:
        return save_email_schedule(request, action, s_item, op_payload)
    elif action.action_type == Action.personalized_canvas_email:
        return save_canvas_email_schedule(request, action, s_item, op_payload)
    elif action.action_type == Action.personalized_json:
        return save_json_schedule(request, action, s_item, op_payload)

    # Action type not found, so return to the main table view
    messages.error(request, _('This action does not support scheduling'))
    return redirect('scheduler:index')
Esempio n. 3
0
def run_email_done(
    request: HttpRequest,
    action_info: Optional[EmailPayload] = None,
    workflow: Optional[Workflow] = None,
) -> HttpResponse:
    """Create the log object, queue the operation request and render done.

    :param request: HTTP request (GET)
    :param action_info: Dictionary containing all the required parameters. If
    empty, the dictionary is taken from the session.
    :return: HTTP response
    """
    # Get the payload from the session if not given
    action_info = get_or_set_action_info(request.session,
                                         EmailPayload,
                                         action_info=action_info)
    if action_info is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(request, _('Incorrect email action invocation.'))
        return redirect('action:index')

    # Get the information from the payload
    action = workflow.actions.filter(pk=action_info['action_id']).first()
    if not action:
        return redirect('home')

    # Log the event
    log_item = Log.objects.register(
        request.user, Log.SCHEDULE_EMAIL_EXECUTE, action.workflow, {
            'action': action.name,
            'action_id': action.id,
            'from_email': request.user.email,
            'subject': action_info['subject'],
            'cc_email': action_info['cc_email'],
            'bcc_email': action_info['bcc_email'],
            'send_confirmation': action_info['send_confirmation'],
            'track_read': action_info['track_read'],
            'exported_workflow': action_info['export_wf'],
            'exclude_values': action_info['exclude_values'],
            'email_column': action_info['item_column'],
            'status': 'Preparing to execute',
        })

    # Update the last_execution_log
    action.last_executed_log = log_item
    action.save()

    # Send the emails!
    send_email_messages.delay(request.user.id, log_item.id,
                              action_info.get_store())

    # Reset object to carry action info throughout dialogs
    set_action_payload(request.session)
    request.session.save()

    # Successful processing.
    return render(request, 'action/action_done.html', {
        'log_id': log_item.id,
        'download': action_info['export_wf']
    })
Esempio n. 4
0
def zip_action(
    req: HttpRequest,
    pk: int,
    workflow: Optional[Workflow] = None,
    action: Optional[Action] = None,
) -> HttpResponse:
    """Request data to create a zip file.

    Form asking for participant column, user file name column, file suffix,
    if it is a ZIP for Moodle and confirm users step.

    :param req: HTTP request (GET)
    :param pk: Action key
    :return: HTTP response
    """
    # Get the payload from the session, and if not, use the given one
    action_info = get_or_set_action_info(
        req.session,
        ZipPayload,
        initial_values={
            'action_id': action.id,
            'prev_url': reverse('action:run', kwargs={'pk': action.id}),
            'post_url': reverse('action:zip_done'),
        }
    )

    # Create the form to ask for the email subject and other information
    form = ZipActionForm(
        req.POST or None,
        column_names=[col.name for col in workflow.columns.all()],
        action=action,
        action_info=action_info,
    )

    if req.method == 'POST' and form.is_valid():
        if action_info['confirm_items']:
            # Add information to the session object to execute the next pages
            action_info['button_label'] = ugettext('Create ZIP')
            action_info['valuerange'] = 2
            action_info['step'] = 2
            set_action_payload(req.session, action_info.get_store())

            return redirect('action:item_filter')

        # Go straight to the final step.
        return run_zip_done(
            req,
            action_info=action_info,
            workflow=workflow)

    # Render the form
    return render(
        req,
        'action/action_zip_step1.html',
        {'action': action,
         'num_msgs': action.get_rows_selected(),
         'form': form,
         'valuerange': range(2)})
Esempio n. 5
0
def run_email_action(
    req: HttpRequest,
    workflow: Workflow,
    action: Action,
) -> HttpResponse:
    """Request data to send emails.

    Form asking for subject line, email column, etc.
    :param req: HTTP request (GET)
    :param workflow: workflow being processed
    :param action: Action being run
    :return: HTTP response
    """
    # Get the payload from the session, and if not, use the given one
    action_info = get_or_set_action_info(req.session,
                                         EmailPayload,
                                         initial_values={
                                             'action_id':
                                             action.id,
                                             'prev_url':
                                             reverse('action:run',
                                                     kwargs={'pk': action.id}),
                                             'post_url':
                                             reverse('action:email_done')
                                         })

    # Create the form to ask for the email subject and other information
    form = EmailActionForm(req.POST or None,
                           column_names=[
                               col.name
                               for col in workflow.columns.filter(is_key=True)
                           ],
                           action=action,
                           action_info=action_info)

    # Request is a POST and is valid
    if req.method == 'POST' and form.is_valid():
        if action_info['confirm_items']:
            # Add information to the session object to execute the next pages
            action_info['button_label'] = ugettext('Send')
            action_info['valuerange'] = 2
            action_info['step'] = 2
            set_action_payload(req.session, action_info.get_store())

            return redirect('action:item_filter')

        # Go straight to the final step.
        return run_email_done(req, action_info=action_info, workflow=workflow)

    # Render the form
    return render(
        req, 'action/request_email_data.html', {
            'action': action,
            'num_msgs': action.get_rows_selected(),
            'form': form,
            'valuerange': range(2)
        })
Esempio n. 6
0
def action_zip_export(
    request: HttpRequest,
    workflow: Optional[Workflow] = None,
) -> HttpResponse:
    """Create a zip with the personalised text and return it as response.

    :param request: Request object with a Dictionary with all the required
    information
    :return: Response (download)
    """
    # Get the payload from the session if not given
    action_info = get_or_set_action_info(request.session, ZipPayload)
    if not action_info:
        # Something is wrong with this execution. Return to action table.
        messages.error(request, _('Incorrect ZIP action invocation.'))
        return redirect('action:index')

    # Get the information from the payload
    action = workflow.actions.filter(pk=action_info['action_id']).first()
    if not action:
        return redirect('home')

    # Create the file name template
    if action_info['zip_for_moodle']:
        file_name_template = (
            '{user_fname}_{part_id}_assignsubmission_file_'
        )
    else:
        if action_info['user_fname_column']:
            file_name_template = '{part_id}_{user_fname}_'
        else:
            file_name_template = '{part_id}'
    if action_info['file_suffix']:
        file_name_template += action_info['file_suffix']
    else:
        file_name_template += 'feedback.html'

    # Create the ZIP with the eval data tuples and return it for download
    sbuf = create_zip(
        create_eval_data_tuple(
            action,
            action_info['item_column'],
            action_info['exclude_values'],
            action_info['user_fname_column'],
        ),
        action_info['zip_for_moodle'],
        file_name_template)

    # Reset object to carry action info throughout dialogs
    set_action_payload(request.session)
    request.session.save()

    return create_response(sbuf)
Esempio n. 7
0
def run_zip_done(
    request: HttpRequest,
    action_info: Optional[ZipPayload] = None,
    workflow: Optional[Workflow] = None,
) -> HttpResponse:
    """Create the zip object, send it for download and render the DONE page.

    :param request: HTTP request (GET)
    :param action_info: Dictionary containing all the required parameters. If
    empty, the dictionary is taken from the session.
    :return: HTTP response
    """
    # Get the payload from the session if not given
    action_info = get_or_set_action_info(
        request.session,
        ZipPayload,
        action_info=action_info)
    if action_info is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(request, _('Incorrect ZIP action invocation.'))
        return redirect('action:index')

    # Get the information from the payload
    action = workflow.actions.filter(pk=action_info['action_id']).first()
    if not action:
        return redirect('home')

    # Log the event
    log_item = Log.objects.register(
        request.user,
        Log.DOWNLOAD_ZIP_ACTION,
        action.workflow,
        {
            'action': action.name,
            'action_id': action.id,
            'user_fname_column': action_info['user_fname_column'],
            'participant_column': action_info['item_column'],
            'file_suffix': action_info['file_suffix'],
            'zip_for_moodle': action_info['zip_for_moodle'],
            'exclude_values': action_info['exclude_values'],
        })

    # Store the payload in the session for the download part
    set_action_payload(request.session, action_info.get_store())

    # Successful processing.
    return render(request, 'action/action_zip_done.html', {})
Esempio n. 8
0
def run_canvas_email_action(
    req: HttpRequest,
    workflow: Workflow,
    action: Action,
) -> HttpResponse:
    """Request data to send JSON objects.

    Form asking for subject, item column (contains ids to select unique users),
    confirm items (add extra step to drop items), export workflow and
    target_rul (if needed).

    :param req: HTTP request (GET)
    :param workflow: workflow being processed
    :param action: Action begin run
    :return: HTTP response
    """
    # Get the payload from the session, and if not, use the given one
    action_info = get_or_set_action_info(req.session,
                                         CanvasEmailPayload,
                                         initial_values={
                                             'action_id':
                                             action.id,
                                             'prev_url':
                                             reverse('action:run',
                                                     kwargs={'pk': action.id}),
                                             'post_url':
                                             reverse('action:email_done')
                                         })

    # Create the form to ask for the email subject and other information
    form = CanvasEmailActionForm(
        req.POST or None,
        column_names=[
            col.name for col in workflow.columns.filter(is_key=True)
        ],
        action=action,
        action_info=action_info)

    if req.method == 'POST' and form.is_valid():
        # Request is a POST and is valid

        if action_info['confirm_items']:
            # Create a dictionary in the session to carry over all the
            # information to execute the next pages
            action_info['button_label'] = ugettext('Send')
            action_info['valuerange'] = 2
            action_info['step'] = 2
            set_action_payload(req.session, action_info.get_store())

            return redirect('action:item_filter')

        # Go straight to the token request step
        return canvas_get_or_set_oauth_token(req, action_info['target_url'])

    # Render the form
    return render(
        req, 'action/request_canvas_email_data.html', {
            'action': action,
            'num_msgs': action.get_rows_selected(),
            'form': form,
            'valuerange': range(2),
            'rows_all_false': action.get_row_all_false_count()
        })
Esempio n. 9
0
def save_email_schedule(request, action, schedule_item, op_payload):
    """Handle the creation and edition of email items.

    :param request: Http request being processed

    :param action: Action item related to the schedule

    :param schedule_item: Schedule item or None if it is new

    :param op_payload: dictionary to carry over the request to the next step

    :return:
    """
    # Create the form to ask for the email subject and other information
    form = EmailScheduleForm(
        form_data=request.POST or None,
        action=action,
        instance=schedule_item,
        columns=action.workflow.columns.filter(is_key=True),
        confirm_items=op_payload.get('confirm_items', False))

    # Processing a valid POST request
    if request.method == 'POST' and form.is_valid():

        # Save the schedule item object
        s_item = form.save(commit=False)

        # Assign additional fields and save
        s_item.user = request.user
        s_item.action = action
        s_item.status = ScheduledAction.STATUS_CREATING
        s_item.payload = {
            'subject':
            form.cleaned_data['subject'],
            'cc_email': [
                email for email in form.cleaned_data['cc_email'].split(',')
                if email
            ],
            'bcc_email': [
                email for email in form.cleaned_data['bcc_email'].split(',')
                if email
            ],
            'send_confirmation':
            form.cleaned_data['send_confirmation'],
            'track_read':
            form.cleaned_data['track_read'],
        }
        # Verify that that action does comply with the name uniqueness
        # property (only with respec to other actions)
        try:
            s_item.save()
        except IntegrityError:
            # There is an action with this name already
            form.add_error(
                'name',
                _('A scheduled execution of this action with this name ' +
                  'already exists'))
            return render(
                request,
                'scheduler/edit.html',
                {
                    'action':
                    action,
                    'form':
                    form,
                    'now':
                    datetime.datetime.now(pytz.timezone(settings.TIME_ZONE)),
                },
            )

        # Upload information to the op_payload
        op_payload['schedule_id'] = s_item.id
        op_payload['confirm_items'] = form.cleaned_data['confirm_items']

        if op_payload['confirm_items']:
            # Update information to carry to the filtering stage
            op_payload['exclude_values'] = s_item.exclude_values
            op_payload['item_column'] = s_item.item_column.name
            op_payload['button_label'] = ugettext('Schedule')
            op_payload['valuerange'] = 2
            op_payload['step'] = 2
            set_action_payload(request.session, op_payload)

            return redirect('action:item_filter')

        # If there is not item_column, the exclude values should be empty.
        s_item.exclude_values = []
        s_item.save()

        # Go straight to the final step
        return finish_scheduling(request, s_item, op_payload)

    # Render the form
    return render(
        request,
        'scheduler/edit.html',
        {
            'action': action,
            'form': form,
            'now': datetime.datetime.now(pytz.timezone(settings.TIME_ZONE)),
            'valuerange': range(2),
        },
    )
Esempio n. 10
0
def finish_scheduling(request, schedule_item=None, payload=None):
    """Finalize the creation of a scheduled action.

    All required data is passed through the payload.

    :param request: Request object received

    :param schedule_item: ScheduledAction item being processed. If None,
    it has to be extracted from the information in the payload.

    :param payload: Dictionary with all the required data coming from
    previous requests.

    :return:
    """
    # Get the payload from the session if not given
    if payload is None:
        payload = request.session.get(action_session_dictionary)

        # If there is no payload, something went wrong.
        if payload is None:
            # Something is wrong with this execution. Return to action table.
            messages.error(request,
                           _('Incorrect action scheduling invocation.'))
            return redirect('action:index')

    # Get the scheduled item if needed
    if not schedule_item:
        s_item_id = payload.get('schedule_id')
        if not s_item_id:
            messages.error(request,
                           _('Incorrect parameters in action scheduling'))
            return redirect('action:index')

        # Get the item being processed
        schedule_item = ScheduledAction.objects.get(id=s_item_id)

    # Check for exclude values and store them if needed
    schedule_item.exclude_values = payload.get('exclude_values', [])

    schedule_item.status = ScheduledAction.STATUS_PENDING
    schedule_item.save()

    # Create the payload to record the event in the log
    log_payload = {
        'action': schedule_item.action.name,
        'action_id': schedule_item.action.id,
        'execute': schedule_item.execute.isoformat(),
    }
    if schedule_item.action.action_type == Action.personalized_text:
        log_payload.update({
            'email_column':
            schedule_item.item_column.name,
            'subject':
            schedule_item.payload.get('subject'),
            'cc_email':
            schedule_item.payload.get('cc_email', []),
            'bcc_email':
            schedule_item.payload.get('bcc_email', []),
            'send_confirmation':
            schedule_item.payload.get('send_confirmation', False),
            'track_read':
            schedule_item.payload.get('track_read', False),
        })
        log_type = Log.SCHEDULE_EMAIL_EDIT
    elif schedule_item.action.action_type == Action.personalized_json:
        ivalue = None
        if schedule_item.item_column:
            ivalue = schedule_item.item_column.name
        log_payload.update({
            'item_column': ivalue,
            'token': schedule_item.payload.get('subject'),
        })
        log_type = Log.SCHEDULE_JSON_EDIT
    elif schedule_item.action.action_type == Action.personalized_canvas_email:
        ivalue = None
        if schedule_item.item_column:
            ivalue = schedule_item.item_column.name
        log_payload.update({
            'item_column': ivalue,
            'token': schedule_item.payload.get('subject'),
            'subject': schedule_item.payload.get('subject'),
        })
        log_type = Log.SCHEDULE_CANVAS_EMAIL_EXECUTE
    else:
        messages.error(request, _('This type of actions cannot be scheduled'))
        return redirect('action:index')

    # Create the log
    Log.objects.register(request.user, log_type, schedule_item.action.workflow,
                         log_payload)

    # Reset object to carry action info throughout dialogs
    set_action_payload(request.session)
    request.session.save()

    # Successful processing.
    return render(
        request, 'scheduler/schedule_done.html', {
            'tdelta': create_timedelta_string(schedule_item.execute),
            's_item': schedule_item
        })
Esempio n. 11
0
def save_json_schedule(request, action, schedule_item, op_payload):
    """Create and edit scheduled json actions.

    :param request: Http request being processed

    :param action: Action item related to the schedule

    :param schedule_item: Schedule item or None if it is new

    :param op_payload: dictionary to carry over the request to the next step

    :return:
    """
    # Create the form to ask for the email subject and other information
    form = JSONScheduleForm(
        form_data=request.POST or None,
        action=action,
        instance=schedule_item,
        columns=action.workflow.columns.filter(is_key=True),
        confirm_items=op_payload.get('confirm_items', False))

    # Processing a valid POST request
    if request.method == 'POST' and form.is_valid():

        # Save the schedule item object
        s_item = form.save(commit=False)

        # Assign additional fields and save
        s_item.user = request.user
        s_item.action = action
        s_item.status = ScheduledAction.STATUS_CREATING
        s_item.payload = {'token': form.cleaned_data['token']}
        s_item.save()

        # Upload information to the op_payload
        op_payload['schedule_id'] = s_item.id

        if s_item.item_column:
            # Create a dictionary in the session to carry over all the
            # information to execute the next steps
            op_payload['item_column'] = s_item.item_column.name
            op_payload['exclude_values'] = s_item.exclude_values
            op_payload['button_label'] = ugettext('Schedule')
            op_payload['valuerange'] = 2
            op_payload['step'] = 2
            set_action_payload(request.session, op_payload)

            return redirect('action:item_filter')

        # If there is not item_column, the exclude values should be empty.
        s_item.exclude_values = []
        s_item.save()

        # Go straight to the final step
        return finish_scheduling(request, s_item, op_payload)

    # Render the form
    return render(
        request,
        'scheduler/edit.html',
        {
            'action': action,
            'form': form,
            'now': datetime.datetime.now(pytz.timezone(settings.TIME_ZONE)),
            'valuerange': range(2),
        },
    )