Esempio n. 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()
Esempio n. 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()
Esempio n. 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())
Esempio n. 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())
Esempio n. 5
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)
Esempio n. 6
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)