def post(self, request: Request, name=None):
        check_captcha = grecaptcha_verify(request)

        if not check_captcha["status"]:
            return HttpResponseForbidden(content_type="text/plain",
                                         content=check_captcha["message"])

        data = request.data.get("value")

        x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
        if x_forwarded_for:
            ip_addr = x_forwarded_for.split(",")[0]
        else:
            ip_addr = request.META.get("REMOTE_ADDR")
        app_url = request.build_absolute_uri().split("/api", 1)[0]
        from_name = data.get("name")
        from_email = data.get("email")
        reason = data.get("reason")
        comments = data.get("comments")

        if not reason or not from_email:
            LOGGER.info("Skipped blank feedback")
            return

        reason_map = {
            "problem": "Report a problem with this service",
            "positive": "Positive feedback for this service",
        }
        reason_text = reason_map.get(reason) or ""
        subject = "Represent Someone Who Died Feedback: {}".format(reason_text)

        LOGGER.info("Received feedback from %s <%s>", from_name, from_email)
        LOGGER.info("Site: %s", app_url)
        LOGGER.info("Feedback content: %s\n%s", subject, comments)

        # Create email body
        body = ""
        if app_url:
            body = "{}Application URL: {}\n".format(body, app_url)
        if ip_addr:
            body = "{}IP address: {}\n".format(body, ip_addr)
        if from_name:
            body = "{}Name: {}\n".format(body, from_name)
        if from_email:
            body = "{}Email: {}\n".format(body, from_email)
        if reason_text:
            body = "{}Contact reason: {}\n".format(body, reason_text)
        if comments:
            body = "{}Feedback: {}\n".format(body, comments)
        recip_email = settings.FEEDBACK_TARGET_EMAIL
        bodyType = "text"
        attachment = ""
        feedback_sent = send_email(body, bodyType, subject, recip_email,
                                   attachment)
        if feedback_sent:
            msg_id = feedback_sent["messages"][0]["msgId"]
            LOGGER.debug("Feedback Sent, Message Id is %s", msg_id)
            return Response({"status": "sent"})
        return Response({"status": "failed"})
 def prepared_email(self, email, pdf_content, filename):
     encoded_string = base64.b64encode(pdf_content).decode('ascii')
     body = """\
             <html>
             <body>
             <p>Hi,<br></p>
             <b>Thank-you for choosing how you wish to attend your traffic hearing.<b>
             <p>A copy of your completed form is attached for your records.</p>
             <p>Your preference will be reviewed, and a Notice of Hearing will be sent in the mail telling you of the date and time of your hearing. The notice will also tell you whether you will be attending your hearing in-person, by telephone or by video and will provide you with important information about attending your hearing.</p>
             <p>If you want to learn more about the hearing process, please visit the Provincial Court of British Columbia's website and read their <a href ="https://www.provincialcourt.bc.ca/downloads/Traffic/Traffic Court Guide.pdf">Guide to Disputing a Ticket</a>.
             If you have any questions, please contact the Violation Ticket Centre at: 1-877-661-8026</p>
             </body>
             </html>
             """
     attachment = {
         "content": encoded_string,
         "contentType": "application/pdf",
         "encoding": "base64",
         "filename": filename
     }
     subject = "Traffic Hearing Choice"
     bodyType = "html"
     email_res = send_email(body, bodyType, subject, email, attachment)
     return email_res
示例#3
0
    def post(self, request: Request, name=None):
        check_captcha = grecaptcha_verify(request)
        if not check_captcha["status"]:
            return HttpResponseForbidden(text=check_captcha["message"])

        request.session["file_guid"] = None
        #############################################################
        #  Adding different pdf form logic: Jul 3, 2020
        data = request.data
        name = request.query_params.get("name")

        template = "{}.html".format(name)

        # These are the current allowed forms (whitelist)
        possibleTemplates = [
            "notice-to-disputant-response",
            "violation-ticket-statement-and-written-reasons",
        ]

        # If not one of our two forms... reject.
        if name not in possibleTemplates:
            return HttpResponseBadRequest("No valid form specified")

        transformed_data = transform(data)

        template = get_template(template)
        html_content = template.render(transformed_data)
        #############################################################

        disputant = data.get("disputantName", {})
        email = data.get("disputantEmail")

        result_bin = json.dumps(data).encode("ascii")
        (key_id, result_enc) = settings.ENCRYPTOR.encrypt(result_bin)

        response = TicketResponse(
            first_name=disputant.get("first"),
            middle_name=disputant.get("middle"),
            last_name=disputant.get("last"),
            result=result_enc,
            key_id=key_id,
            ticket_number=data.get("ticketNumber"),
            ticket_date=data.get("ticketDate"),
            hearing_location_id=data.get("hearingLocation"),
            hearing_attendance=data.get("hearingAttendance"),
            dispute_type=data.get("disputeType"),
        )

        check_required = [
            "first_name",
            "last_name",
            "ticket_number",
            "ticket_date",
            "hearing_location_id",
        ]

        for fname in check_required:
            if not getattr(response, fname):
                return HttpResponseBadRequest("Missing: " + fname)

        # Generate/Save the pdf to DB and generate email with pdf attached
        email_sent = False
        pdf_response = None

        try:
            pdf_content = render_pdf(html_content)

            pdf_response = PreparedPdf(data=pdf_content)
            pdf_response.save()
            response.prepared_pdf_id = pdf_response.pk
            response.printed_date = timezone.now()

            if pdf_content:
                (pdf_key_id,
                 pdf_content_enc) = settings.ENCRYPTOR.encrypt(pdf_content)
                pdf_response = PreparedPdf(data=pdf_content_enc,
                                           key_id=pdf_key_id)
                pdf_response.save()
                response.prepared_pdf_id = pdf_response.pk
                response.save()
                request.session["file_guid"] = str(response.file_guid)

            if email and pdf_content:
                send_email(email, pdf_content, name)
                response.emailed_date = timezone.now()
                email_sent = True
                response.save()

        except Exception as exception:
            LOGGER.exception("Pdf / Email generation error", exception)

        return Response({"id": response.pk, "email-sent": email_sent})
    def post(self, request: Request, name=None):
        check_captcha = grecaptcha_verify(request)
        if not check_captcha["status"]:
            return HttpResponseForbidden(text=check_captcha["message"])

        #############################################################
        #  Adding different pdf form logic: Jul 3, 2020
        data = copy.deepcopy(request.data)
        name = request.GET['name']
        template = '{}.html'.format(name)

        # Add date to the payload
        today = date.today().strftime('%d-%b-%Y')
        data['date'] = today

        #######################
        # Notice To Disputant - Response
        #
        # Make the Violation Ticket Number all upper case
        try:
            x = data['ticketNumber']['prefix']
            data['ticketNumber']['prefix'] = x.upper()
        except KeyError:
            pass

        # Format the date to be more user friendly
        try:
            x = datetime.strptime(data['ticketDate'], '%Y-%m-%d')
            data['ticketDate'] = x.strftime('%d-%b-%Y')
        except KeyError:
            pass

        # Format the date of birth to be more user friendly
        try:
            x2 = datetime.strptime(data['disputantDOB'], '%Y-%m-%d')
            data['disputantDOB'] = x2.strftime('%d-%b-%Y')
        except KeyError:
            pass
        #######################

        template = get_template(template)
        html_content = template.render(data)

        pdf_content2 = render_pdf(html_content)

        # XXX: Just for testing
        # response = HttpResponse(content_type='application/pdf')
        # response['Content-Disposition'] = 'attachment; filename="report.pdf"'

        # response.write(pdf_content)

        # return response

        #############################################################

        result = request.data
        disputant = result.get("disputantName", {})
        # address = result.get("disputantAddress", {})
        ticketNumber = result.get("ticketNumber", {})
        ticketNumber = str(ticketNumber.get("prefix")) + str(ticketNumber.get("suffix"))

        result_bin = json.dumps(result).encode("ascii")
        (key_id, result_enc) = settings.ENCRYPTOR.encrypt(result_bin)

        response = TicketResponse(
            first_name=disputant.get("first"),
            middle_name=disputant.get("middle"),
            last_name=disputant.get("last"),
            result=result_enc,
            key_id=key_id,
            ticket_number=ticketNumber.upper(),
            ticket_date=result.get("ticketDate"),
            hearing_location_id=result.get("hearingLocation"),
            hearing_attendance=result.get("hearingAttendance"),
            dispute_type=result.get("disputeType"),
        )

        check_required = [
            "first_name",
            "last_name",
            "ticket_number",
            "ticket_date",
            "hearing_location_id"
            ]

        for fname in check_required:
            if not getattr(response, fname):
                return HttpResponseBadRequest("Missing: " + fname)

        # check terms acceptance?
        # if not result.get("disputantAcknowledgement"):
        #     return HttpResponseBadRequest()

        # Generate/Save the pdf to DB and generate email with pdf attached
        email_sent = False
        pdf_response = None

        try:
            if result:
                pdf_content = generate_pdf(result)
                if pdf_content:
                    (pdf_key_id, pdf_content_enc) = settings.ENCRYPTOR.encrypt(
                        pdf_content
                    )
                    pdf_response = PreparedPdf(data=pdf_content_enc, key_id=pdf_key_id)
                    pdf_response.save()
                    response.prepared_pdf_id = pdf_response.pk
                    response.save()
                    request.session['file_guid'] = str(response.file_guid)

                email = result.get("disputantEmail")
                if email and pdf_content:
                    send_email(email, pdf_content)
                    response.emailed_date = timezone.now()
                    email_sent = True
                    response.save()

        except Exception as exception:
            LOGGER.exception("Pdf / Email generation error", exception)

        return Response(
            {
                "id": response.pk,
                "email-sent": email_sent,
            }
        )