Example #1
0
def change_flag_and_add_comment(request, report_id):
    if request.fmsuser.is_pro():
        report = get_object_or_404(Report, id=report_id)
        comment_form = ReportCommentForm(request.POST)
        hidden = None
        event_type = None
        #if you add a new flag using divAddComment in _actions.html, don't forget to retrieve the correct name
        # of the hidden field here.
        if request.POST.get("hiddenThirdPartyResponsibility"):
            hidden = request.POST.get("hiddenThirdPartyResponsibility")
            if hidden == 'true':
                #source of incident is due to a third party
                report.third_party_responsibility = True
            else:
                #source of incident is not a third party
                report.third_party_responsibility = False
            report.save()
            event_type = ReportEventLog.THIRD_PARTY_RESPONSIBILITY

        elif request.POST.get("hiddenPrivateProperty"):
            hidden = request.POST.get("hiddenPrivateProperty")
            if hidden == 'true':
                #the source of the incident is not on a private property
                report.private_property = True
            else:
                #the source of the incident is on a private property
                report.private_property = False
            report.save()
            event_type = ReportEventLog.PRIVATE_PROPERTY

        if event_type is not None:
            event = ReportEventLog(
                report=report,
                event_type=event_type,
                user=get_current_user(),
                text=
                hidden,  #saving the new value of the flag in case we ever need it.
            )
            event.save()

        # TOFIX: Validate form
        if comment_form.is_valid() and request.POST.get(
                'text') and hidden is not None:
            comment = comment_form.save(commit=False)
            comment.report = report
            comment.save()
        return HttpResponseRedirect(report.get_absolute_url_pro())
    raise PermissionDenied()
Example #2
0
def change_flag_and_add_comment(request, report_id):
    if request.fmsuser.is_pro():
        report = get_object_or_404(Report, id=report_id)
        comment_form = ReportCommentForm(request.POST)
        hidden = None
        event_type = None
        #if you add a new flag using divAddComment in _actions.html, don't forget to retrieve the correct name
        # of the hidden field here.
        if request.POST.get("hiddenThirdPartyResponsibility"):
            hidden = request.POST.get("hiddenThirdPartyResponsibility")
            if hidden == 'true':
                #source of incident is due to a third party
                report.third_party_responsibility = True
            else:
                #source of incident is not a third party
                report.third_party_responsibility = False
            report.save()
            event_type = ReportEventLog.THIRD_PARTY_RESPONSIBILITY

        elif request.POST.get("hiddenPrivateProperty"):
            hidden = request.POST.get("hiddenPrivateProperty")
            if hidden == 'true':
                #the source of the incident is not on a private property
                report.private_property = True
            else:
                #the source of the incident is on a private property
                report.private_property = False
            report.save()
            event_type = ReportEventLog.PRIVATE_PROPERTY

        if event_type is not None:
            event = ReportEventLog(
                        report=report,
                        event_type=event_type,
                        user=get_current_user(),
                        text=hidden, #saving the new value of the flag in case we ever need it.
                    )
            event.save()

        # TOFIX: Validate form
        if comment_form.is_valid() and request.POST.get('text') and hidden is not None:
            comment = comment_form.save(commit=False)
            comment.report = report
            comment.save()
        return HttpResponseRedirect(report.get_absolute_url_pro())
    raise PermissionDenied()
Example #3
0
def deleteAttachment(request, report_id):
    """delete a attachment (pro only)"""
    report = get_object_or_404(Report, id=report_id)
    attachmentId = request.REQUEST.get('attachmentId')
    a = ReportAttachment.objects.get(pk=attachmentId)
    a.logical_deleted = True
    a.save()
    user = get_current_user()
    event_type = ReportEventLog.REPORT_COMMENT_DELETED
    if hasattr(a, "reportfile"):
        event_type = ReportEventLog.REPORT_FILE_DELETED

    event = ReportEventLog(
                report=report,
                event_type=event_type,
                user=user,
                text=attachmentId,
            )
    event.save()

    return HttpResponseRedirect(report.get_absolute_url_pro())
Example #4
0
def deleteAttachment(request, report_id):
    """delete a attachment (pro only)"""
    report = get_object_or_404(Report, id=report_id)
    attachmentId = request.REQUEST.get('attachmentId')
    a = ReportAttachment.objects.get(pk=attachmentId)
    a.logical_deleted = True
    a.save()
    user = get_current_user()
    event_type = ReportEventLog.REPORT_COMMENT_DELETED
    if hasattr(a, "reportfile"):
        event_type = ReportEventLog.REPORT_FILE_DELETED

    event = ReportEventLog(
        report=report,
        event_type=event_type,
        user=user,
        text=attachmentId,
    )
    event.save()

    return HttpResponseRedirect(report.get_absolute_url_pro())
Example #5
0
    def run(self):
        super(ReportTransferRejectInWebhook, self).run()

        # Transfer to the previous group of managers if exist
        try:
            responsible_department = ReportEventLog.objects.filter(
                report=self._report,
                organisation=self._report.responsible_entity,
                event_type=ReportEventLog.MANAGER_ASSIGNED).latest(
                    "event_at").related_old

            if responsible_department:
                self._report.responsible_department = responsible_department
                self._report.responsible_entity = self._report.responsible_department.dependency
                self._report.status = Report.MANAGER_ASSIGNED
                self._report.save()
            else:
                raise ReportEventLog.DoesNotExist()
        except ReportEventLog.DoesNotExist:
            # If no previous group of manager, dispatch it.
            self._report.dispatch()
Example #6
0
 def set_history(self, report, row):
     ReportEventLog(report=report,
                    event_type=ReportEventLog.CREATED,
                    user=self._get_pave_user(),
                    related_new=report.responsible_department).save()
Example #7
0
def send_pdf(request, report_id):
    to_return = {
        "status": "success",
        "message": "",
        "logMessages": [],
        "validRecipients": []
    }

    user = get_current_user()
    recipients = request.POST.get('to')
    comments = request.POST.get('comments', '')

    # recipient can't be empty
    if recipients.strip() == '':
        to_return["status"] = "error"
        to_return["message"] = _("Add a valid email address.")
        return JsonHttpResponse(to_return)

    recipients = re.compile("[\\s,;]+").split(recipients)

    valid_recipients = []
    for recipient in recipients:
        recipient = recipient.strip()
        if not recipient:
            continue
        try:
            validate_email(recipient)
            valid_recipients.append(recipient)
        except ValidationError:
            to_return["status"] = "error"
            to_return["message"] = _("There were errors.")
            to_return["logMessages"].append(_("'{email}' is not a valid email address.").format(email=recipient))
            continue
    #if no valid emails, no need to proceed
    if len(valid_recipients) == 0:
        return JsonHttpResponse(to_return)

    # Only set visibility as private if user is auth and visibility POST param is private
    if request.fmsuser.is_pro() and "private" == request.POST.get('visibility'):
        pro_version = True
    else:
        pro_version = False

    report = get_object_or_404(Report, id=report_id)
    #generate the pdf
    pdffile = generate_pdf("reports/pdf.html", {
        'report': report,
        'files': report.files() if pro_version else report.active_files(),
        'comments': report.comments() if pro_version else report.active_comments(),
        'activity_list': report.activities.all(),
        'visibility': 'private' if pro_version else 'public',
        'BACKOFFICE': pro_version,
        'base_url': getattr(settings, 'RENDER_PDF_BASE_URL', None),
    }, context_instance=RequestContext(request))

    subject, html, text = transform_notification_template("mail-pdf", report, user, comment=comments)

    for recipient in valid_recipients:
        msg = EmailMultiAlternatives(subject, text, settings.DEFAULT_FROM_EMAIL, (recipient,))

        if html:
            msg.attach_alternative(html, "text/html")

        #reset the seek to 0 to be able to read multiple times the same file
        pdffile.seek(0)
        name = "export-incident-%s-date-%s.pdf" % (report.id, datetime.date.today().isoformat())
        msg.attach(name, pdffile.read(), 'application/pdf')

        msg.send()
        to_return["logMessages"].append(_("Successfully sent to '{email}'.").format(email=recipient))
        to_return["validRecipients"].append(recipient)

    if to_return["status"] == "success":
        to_return["message"] = _("PDF sent by email.")
    else:
        to_return["message"] = _("There were errors.")

    event = ReportEventLog(
                report=report,
                event_type=ReportEventLog.PDF_HISTORY,
                user=user,
                text=", ".join(valid_recipients),
            )
    event.save()

    return JsonHttpResponse(to_return)
Example #8
0
def send_pdf(request, report_id):
    to_return = {
        "status": "success",
        "message": "",
        "logMessages": [],
        "validRecipients": []
    }

    user = get_current_user()
    recipients = request.POST.get('to')
    comments = request.POST.get('comments', '')

    # recipient can't be empty
    if recipients.strip() == '':
        to_return["status"] = "error"
        to_return["message"] = _("Add a valid email address.")
        return JsonHttpResponse(to_return)

    recipients = re.compile("[\\s,;]+").split(recipients)

    valid_recipients = []
    for recipient in recipients:
        recipient = recipient.strip()
        if not recipient:
            continue
        try:
            validate_email(recipient)
            valid_recipients.append(recipient)
        except ValidationError:
            to_return["status"] = "error"
            to_return["message"] = _("There were errors.")
            to_return["logMessages"].append(
                _("'{email}' is not a valid email address.").format(
                    email=recipient))
            continue
    #if no valid emails, no need to proceed
    if len(valid_recipients) == 0:
        return JsonHttpResponse(to_return)

    # Only set visibility as private if user is auth and visibility POST param is private
    if request.fmsuser.is_pro() and "private" == request.POST.get(
            'visibility'):
        pro_version = True
    else:
        pro_version = False

    report = get_object_or_404(Report, id=report_id)
    #generate the pdf
    pdffile = generate_pdf("reports/pdf.html", {
        'report':
        report,
        'files':
        report.files() if pro_version else report.active_files(),
        'comments':
        report.comments() if pro_version else report.active_comments(),
        'activity_list':
        report.activities.all(),
        'visibility':
        'private' if pro_version else 'public',
        'BACKOFFICE':
        pro_version,
        'base_url':
        getattr(settings, 'RENDER_PDF_BASE_URL', None),
    },
                           context_instance=RequestContext(request))

    subject, html, text = transform_notification_template("mail-pdf",
                                                          report,
                                                          user,
                                                          comment=comments)

    for recipient in valid_recipients:
        msg = EmailMultiAlternatives(subject, text,
                                     settings.DEFAULT_FROM_EMAIL,
                                     (recipient, ))

        if html:
            msg.attach_alternative(html, "text/html")

        #reset the seek to 0 to be able to read multiple times the same file
        pdffile.seek(0)
        name = "export-incident-%s-date-%s.pdf" % (
            report.id, datetime.date.today().isoformat())
        msg.attach(name, pdffile.read(), 'application/pdf')

        msg.send()
        to_return["logMessages"].append(
            _("Successfully sent to '{email}'.").format(email=recipient))
        to_return["validRecipients"].append(recipient)

    if to_return["status"] == "success":
        to_return["message"] = _("PDF sent by email.")
    else:
        to_return["message"] = _("There were errors.")

    event = ReportEventLog(
        report=report,
        event_type=ReportEventLog.PDF_HISTORY,
        user=user,
        text=", ".join(valid_recipients),
    )
    event.save()

    return JsonHttpResponse(to_return)