def view_template(service_id, template_id): template = current_service.get_template(template_id) template_folder = current_service.get_template_folder(template['folder']) user_has_template_permission = current_user.has_template_folder_permission( template_folder) if should_skip_template_page(template['template_type']): return redirect( url_for('.send_one_off', service_id=service_id, template_id=template_id)) page_count = get_page_count_for_letter(template) return render_template( 'views/templates/template.html', template=get_template( template, current_service, letter_preview_url=url_for( 'no_cookie.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', ), show_recipient=True, page_count=get_page_count_for_letter(template), ), template_postage=template["postage"], user_has_template_permission=user_has_template_permission, letter_too_long=is_letter_too_long(page_count), letter_max_pages=LETTER_MAX_PAGE_COUNT, page_count=page_count)
def view_template(service_id, template_id): if not current_user.has_permissions('view_activity'): return redirect( url_for('.send_one_off', service_id=service_id, template_id=template_id)) template = service_api_client.get_service_template( service_id, str(template_id))['data'] if template["template_type"] == "letter": letter_contact_details = service_api_client.get_letter_contacts( service_id) default_letter_contact_block_id = next( (x['id'] for x in letter_contact_details if x['is_default']), None) else: default_letter_contact_block_id = None return render_template( 'views/templates/template.html', template=get_template( template, current_service, expand_emails=True, letter_preview_url=url_for( '.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', ), show_recipient=True, page_count=get_page_count_for_letter(template), ), default_letter_contact_block_id=default_letter_contact_block_id, )
def get_email_preview_template(template, template_id, service_id): email_preview_template = get_template( template, current_service, letter_preview_url=url_for( '.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', ), show_recipient=True, page_count=get_page_count_for_letter(template), ) template_str = str(email_preview_template) translate = {"From": _("From"), "To": _("To"), "Subject": _("Subject")} def translate_brackets(x): g = x.group(0) english = g[1:-1] # drop brackets if english not in translate: return english return translate[english] # this regex finds test inside [] template_str = re.sub(r"\[[^]]*\]", translate_brackets, template_str) email_preview_template.html = template_str return email_preview_template
def _check_notification(service_id, template_id, exception=None): db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() template = get_template( db_template, current_service, show_recipient=True, email_reply_to=email_reply_to, sms_sender=sms_sender, letter_preview_url=url_for( 'no_cookie.check_notification_preview', service_id=service_id, template_id=template_id, filetype='png', ), page_count=get_page_count_for_letter(db_template), ) placeholders = fields_to_fill_in(template) back_link = get_back_link(service_id, template, len(placeholders), placeholders) if ((not session.get('recipient') and db_template['template_type'] != 'letter') or not all_placeholders_in_session(template.placeholders)): raise PermanentRedirect(back_link) template.values = get_recipient_and_placeholders_from_session( template.template_type) page_count = get_page_count_for_letter(db_template, template.values) template.page_count = page_count return dict( template=template, back_link=back_link, help=get_help_argument(), letter_too_long=is_letter_too_long(page_count), letter_max_pages=LETTER_MAX_PAGE_COUNT, page_count=page_count, **(get_template_error_dict(exception) if exception else {}), )
def send_one_off_letter_address(service_id, template_id): if {'recipient', 'placeholders'} - set(session.keys()): # if someone has come here via a bookmark or back button they might have some stuff still in their session return redirect(url_for('.send_one_off', service_id=service_id, template_id=template_id)) db_template = current_service.get_template_with_user_permission_or_403(template_id, current_user) template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( 'no_cookie.send_test_preview', service_id=service_id, template_id=template_id, filetype='png', ), page_count=get_page_count_for_letter(db_template), email_reply_to=None, sms_sender=None ) current_session_address = PostalAddress.from_personalisation( get_normalised_placeholders_from_session() ) form = LetterAddressForm( address=current_session_address.normalised, allow_international_letters=current_service.has_permission('international_letters'), ) if form.validate_on_submit(): session['placeholders'].update(PostalAddress(form.address.data).as_personalisation) placeholders = fields_to_fill_in(template) if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) first_non_address_placeholder_index = len(address_lines_1_to_7_keys) return redirect(url_for( 'main.send_one_off_step', service_id=service_id, template_id=template_id, step_index=first_non_address_placeholder_index, )) return render_template( 'views/send-one-off-letter-address.html', page_title=get_send_test_page_title( template_type='letter', entering_recipient=True, name=template.name, ), template=template, form=form, back_link=get_back_link(service_id, template, 0), link_to_upload=True, )
def send_messages(service_id, template_id): session['sender_id'] = None db_template = service_api_client.get_service_template(service_id, template_id)['data'] if email_or_sms_not_enabled(db_template['template_type'], current_service['permissions']): return redirect(url_for( '.action_blocked', service_id=service_id, notification_type=db_template['template_type'], return_to='view_template', template_id=template_id )) template = get_template( db_template, current_service, show_recipient=True, expand_emails=True, letter_preview_url=url_for( '.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', page_count=get_page_count_for_letter(db_template), ), ) form = CsvUploadForm() if form.validate_on_submit(): try: upload_id = s3upload( service_id, Spreadsheet.from_file(form.file.data, filename=form.file.data.filename).as_dict, current_app.config['AWS_REGION'] ) session['upload_data'] = { "template_id": template_id, "original_file_name": form.file.data.filename } return redirect(url_for('.check_messages', service_id=service_id, upload_id=upload_id, template_type=template.template_type)) except (UnicodeDecodeError, BadZipFile, XLRDError): flash('Couldn’t read {}. Try using a different file format.'.format( form.file.data.filename )) column_headings = first_column_headings[template.template_type] + list(template.placeholders) return render_template( 'views/send.html', template=template, column_headings=list(ascii_uppercase[:len(column_headings)]), example=[column_headings, get_example_csv_rows(template)], form=form )
def view_notification(service_id, notification_id): notification = notification_api_client.get_notification( service_id, str(notification_id)) notification['template'].update( {'reply_to_text': notification['reply_to_text']}) if notification['template']['is_precompiled_letter']: file_contents = view_letter_notification_as_preview( service_id, notification_id, "pdf") page_count = pdf_page_count(io.BytesIO(file_contents)) else: page_count = get_page_count_for_letter(notification['template']) template = get_template( notification['template'], current_service, letter_preview_url=url_for( '.view_letter_notification_as_preview', service_id=service_id, notification_id=notification_id, filetype='png', ), page_count=page_count, show_recipient=True, redact_missing_personalisation=True, ) template.values = get_all_personalisation_from_notification(notification) if notification['job']: job = job_api_client.get_job(service_id, notification['job']['id'])['data'] else: job = None return render_template( 'views/notifications/notification.html', finished=(notification['status'] in (DELIVERED_STATUSES + FAILURE_STATUSES)), uploaded_file_name='Report', template=template, job=job, updates_url=url_for(".view_notification_updates", service_id=service_id, notification_id=notification['id'], status=request.args.get('status'), help=get_help_argument()), partials=get_single_notification_partials(notification), created_by=notification.get('created_by'), created_at=notification['created_at'], help=get_help_argument(), estimated_letter_delivery_date=get_letter_timings( notification['created_at']).earliest_delivery, notification_id=notification['id'], can_receive_inbound=(current_service.has_permission('inbound_sms')), is_precompiled_letter=notification['template'] ['is_precompiled_letter'])
def get_email_preview_template(template, template_id, service_id): email_preview_template = get_template( template, current_service, letter_preview_url=url_for( '.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', ), show_recipient=True, page_count=get_page_count_for_letter(template), ) return email_preview_template
def _check_notification(service_id, template_id, exception=None): db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template["template_type"] == "email": email_reply_to = get_email_reply_to_address_from_session() elif db_template["template_type"] == "sms": sms_sender = get_sms_sender_from_session() template = get_template( db_template, current_service, show_recipient=True, email_reply_to=email_reply_to, sms_sender=sms_sender, letter_preview_url=url_for( ".check_notification_preview", service_id=service_id, template_id=template_id, filetype="png", ), page_count=get_page_count_for_letter(db_template), ) step_index = len( fields_to_fill_in( template, prefill_current_user=( session.get("send_step") == "main.send_test_step"), )) back_link = get_back_link(service_id, template, step_index) if (not session.get("recipient") and db_template["template_type"] != "letter" ) or not all_placeholders_in_session(template.placeholders): raise PermanentRedirect(back_link) template.values = get_recipient_and_placeholders_from_session( template.template_type) return dict( template=template, back_link=back_link, help=get_help_argument(), **(get_template_error_dict(exception) if exception else {}), )
def view_template(service_id, template_id): template = current_service.get_template(template_id) template_folder = current_service.get_template_folder(template['folder']) user_has_template_permission = current_user.has_template_folder_permission( template_folder) if should_skip_template_page(template['template_type']): return redirect( url_for('.send_one_off', service_id=service_id, template_id=template_id)) if template["template_type"] == "letter": letter_contact_details = service_api_client.get_letter_contacts( service_id) default_letter_contact_block_id = next( (x['id'] for x in letter_contact_details if x['is_default']), None) else: default_letter_contact_block_id = None return render_template( 'views/templates/template.html', template=get_template( template, current_service, expand_emails=True, letter_preview_url=url_for( '.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', ), show_recipient=True, page_count=get_page_count_for_letter(template), ), template_postage=template["postage"], user_has_template_permission=user_has_template_permission, default_letter_contact_block_id=default_letter_contact_block_id, )
def test_page_count_returns_none_for_non_letter_templates(template_type): assert get_page_count_for_letter({'template_type': template_type}) is None
def send_test_step(service_id, template_id, step_index): if {"recipient", "placeholders"} - set(session.keys()): return redirect( url_for( { "main.send_test_step": ".send_test", "main.send_one_off_step": ".send_one_off", }[request.endpoint], service_id=service_id, template_id=template_id, )) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) if not session.get("send_test_letter_page_count"): session["send_test_letter_page_count"] = get_page_count_for_letter( db_template) email_reply_to = None sms_sender = None if db_template["template_type"] == "email": email_reply_to = get_email_reply_to_address_from_session() elif db_template["template_type"] == "sms": sms_sender = get_sms_sender_from_session() template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( ".send_test_preview", service_id=service_id, template_id=template_id, filetype="png", ), page_count=session["send_test_letter_page_count"], email_reply_to=email_reply_to, sms_sender=sms_sender, ) placeholders = fields_to_fill_in( template, prefill_current_user=(request.endpoint == "main.send_test_step"), ) # used to set the back link in the check_notification screen session["send_step"] = request.endpoint try: current_placeholder = placeholders[step_index] except IndexError: if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) return redirect( url_for( { "main.send_test_step": ".send_test", "main.send_one_off_step": ".send_one_off", }[request.endpoint], service_id=service_id, template_id=template_id, )) optional_placeholder = current_placeholder in optional_address_columns form = get_placeholder_form_instance( current_placeholder, dict_to_populate_from=get_normalised_placeholders_from_session(), template_type=template.template_type, optional_placeholder=optional_placeholder, allow_international_phone_numbers=current_service.has_permission( "international_sms"), ) if form.validate_on_submit(): # if it's the first input (phone/email), we store against `recipient` as well, for easier extraction. # Only if it's not a letter. # And only if we're not on the test route, since that will already have the user's own number set if step_index == 0 and template.template_type != "letter" and request.endpoint != "main.send_test_step": session["recipient"] = form.placeholder_value.data session["placeholders"][ current_placeholder] = form.placeholder_value.data if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) return redirect( url_for( request.endpoint, service_id=service_id, template_id=template_id, step_index=step_index + 1, help=get_help_argument(), )) back_link = get_back_link(service_id, template, step_index) template.values = get_recipient_and_placeholders_from_session( template.template_type) template.values[current_placeholder] = None return render_template( "views/send-test.html", page_title=get_send_test_page_title( template.template_type, get_help_argument(), entering_recipient=not session["recipient"], ), template=template, form=form, optional_placeholder=optional_placeholder, back_link=back_link, help=get_help_argument(), link_to_upload=(request.endpoint == "main.send_one_off_step" and step_index == 0), bulk_send_allowed=service_can_bulk_send(service_id), )
def _check_messages(service_id, template_id, upload_id, preview_row, letters_as_pdf=False): try: # The happy path is that the job doesn’t already exist, so the # API will return a 404 and the client will raise HTTPError. job_api_client.get_job(service_id, upload_id) # the job exists already - so go back to the templates page # If we just return a `redirect` (302) object here, we'll get # errors when we try and unpack in the check_messages route. # Rasing a werkzeug.routing redirect means that doesn't happen. raise PermanentRedirect( url_for('.send_messages', service_id=service_id, template_id=template_id)) except HTTPError as e: if e.status_code != 404: raise statistics = service_api_client.get_service_statistics(service_id, today_only=True) remaining_messages = (current_service.message_limit - sum(stat['requested'] for stat in statistics.values())) contents = s3download(service_id, upload_id) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( '.check_messages_preview', service_id=service_id, template_id=template_id, upload_id=upload_id, filetype='png', row_index=preview_row, ) if not letters_as_pdf else None, email_reply_to=email_reply_to, sms_sender=sms_sender, page_count=get_page_count_for_letter(db_template), ) recipients = RecipientCSV( contents, template_type=template.template_type, placeholders=template.placeholders, max_initial_rows_shown=50, max_errors_shown=50, whitelist=itertools.chain.from_iterable( [user.name, user.mobile_number, user.email_address] for user in Users(service_id)) if current_service.trial_mode else None, remaining_messages=remaining_messages, international_sms=current_service.has_permission('international_sms'), ) if request.args.get('from_test'): # only happens if generating a letter preview test back_link = url_for('.send_test', service_id=service_id, template_id=template.id) choose_time_form = None else: back_link = url_for('.send_messages', service_id=service_id, template_id=template.id) choose_time_form = ChooseTimeForm() if preview_row < 2: abort(404) if preview_row < len(recipients) + 2: template.values = recipients[preview_row - 2].recipient_and_personalisation elif preview_row > 2: abort(404) return dict( recipients=recipients, template=template, errors=recipients.has_errors, row_errors=get_errors_for_csv(recipients, template.template_type), count_of_recipients=len(recipients), count_of_displayed_recipients=len(list(recipients.displayed_rows)), original_file_name=request.args.get('original_file_name', ''), upload_id=upload_id, form=CsvUploadForm(), remaining_messages=remaining_messages, choose_time_form=choose_time_form, back_link=back_link, help=get_help_argument(), trying_to_send_letters_in_trial_mode=all(( current_service.trial_mode, template.template_type == 'letter', )), required_recipient_columns=OrderedSet( recipients.recipient_column_headers) - optional_address_columns, preview_row=preview_row, sent_previously=job_api_client.has_sent_previously( service_id, template.id, db_template['version'], request.args.get('original_file_name', '')))
def send_test_step(service_id, template_id, step_index): if {'recipient', 'placeholders'} - set(session.keys()): return redirect( url_for( { 'main.send_test_step': '.send_test', 'main.send_one_off_step': '.send_one_off', }[request.endpoint], service_id=service_id, template_id=template_id, )) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) if not session.get('send_test_letter_page_count'): session['send_test_letter_page_count'] = get_page_count_for_letter( db_template) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() template = get_template(db_template, current_service, show_recipient=True, letter_preview_url=url_for( '.send_test_preview', service_id=service_id, template_id=template_id, filetype='png', ), page_count=session['send_test_letter_page_count'], email_reply_to=email_reply_to, sms_sender=sms_sender) placeholders = fields_to_fill_in( template, prefill_current_user=(request.endpoint == 'main.send_test_step'), ) # used to set the back link in the check_notification screen session['send_step'] = request.endpoint try: current_placeholder = placeholders[step_index] except IndexError: if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) return redirect( url_for( { 'main.send_test_step': '.send_test', 'main.send_one_off_step': '.send_one_off', }[request.endpoint], service_id=service_id, template_id=template_id, )) optional_placeholder = (current_placeholder in optional_address_columns) form = get_placeholder_form_instance( current_placeholder, dict_to_populate_from=get_normalised_placeholders_from_session(), template_type=template.template_type, optional_placeholder=optional_placeholder, allow_international_phone_numbers=current_service.has_permission( 'international_sms'), ) if form.validate_on_submit(): # if it's the first input (phone/email), we store against `recipient` as well, for easier extraction. # Only if it's not a letter. # And only if we're not on the test route, since that will already have the user's own number set if (step_index == 0 and template.template_type != 'letter' and request.endpoint != 'main.send_test_step'): session['recipient'] = form.placeholder_value.data session['placeholders'][ current_placeholder] = form.placeholder_value.data if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) return redirect( url_for( request.endpoint, service_id=service_id, template_id=template_id, step_index=step_index + 1, help=get_help_argument(), )) back_link = get_back_link(service_id, template, step_index) template.values = get_recipient_and_placeholders_from_session( template.template_type) template.values[current_placeholder] = None if (request.endpoint == 'main.send_one_off_step' and step_index == 0 and template.template_type != 'letter' and not (template.template_type == 'sms' and current_user.mobile_number is None) and current_user.has_permissions('manage_templates', 'manage_service')): type = first_column_headings[template.template_type][0] if (type == "email address"): type = _l("email address") elif (type == "phone number"): type = _l("phone number") skip_link = ( '{} {}'.format(_l("Use my"), type), url_for('.send_test', service_id=service_id, template_id=template.id), ) else: skip_link = None return render_template( 'views/send-test.html', page_title=get_send_test_page_title( template.template_type, get_help_argument(), entering_recipient=not session['recipient'], name=template.name, ), template=template, form=form, skip_link=skip_link, optional_placeholder=optional_placeholder, back_link=back_link, help=get_help_argument(), link_to_upload=(request.endpoint == 'main.send_one_off_step' and step_index == 0), )
def send_messages(service_id, template_id): # if there's lots of data in the session, lets log it for debugging purposes # TODO: Remove this once we're confident we have session size under control if len(session.get('file_uploads', {}).keys()) > 2: current_app.logger.info( 'session contains large file_uploads - json_len {}, keys: {}'. format(len(json.dumps(session['file_uploads'])), session['file_uploads'].keys())) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() if email_or_sms_not_enabled(db_template['template_type'], current_service.permissions): return redirect( url_for('.action_blocked', service_id=service_id, notification_type=db_template['template_type'], return_to='view_template', template_id=template_id)) template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( '.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', page_count=get_page_count_for_letter(db_template), ), email_reply_to=email_reply_to, sms_sender=sms_sender, ) form = CsvUploadForm() if form.validate_on_submit(): try: upload_id = s3upload( service_id, Spreadsheet.from_file( form.file.data, filename=form.file.data.filename).as_dict, current_app.config['AWS_REGION']) return redirect( url_for( '.check_messages', service_id=service_id, upload_id=upload_id, template_id=template.id, original_file_name=form.file.data.filename, )) except (UnicodeDecodeError, BadZipFile, XLRDError): flash( 'Couldn’t read {}. Try using a different file format.'.format( form.file.data.filename)) except (XLDateError): flash(( '{} contains numbers or dates that Notification can’t understand. ' 'Try formatting all columns as ‘text’ or export your file as CSV.' ).format(form.file.data.filename)) column_headings = get_spreadsheet_column_headings_from_template(template) return render_template( 'views/send.html', template=template, column_headings=list(ascii_uppercase[:len(column_headings)]), example=[column_headings, get_example_csv_rows(template)], form=form)
def view_notification(service_id, notification_id): notification = notification_api_client.get_notification( service_id, str(notification_id)) notification['template'].update( {'reply_to_text': notification['reply_to_text']}) personalisation = get_all_personalisation_from_notification(notification) if notification['template']['is_precompiled_letter']: try: file_contents = view_letter_notification_as_preview( service_id, notification_id, "pdf") page_count = pdf_page_count(io.BytesIO(file_contents)) except PdfReadError: return render_template( 'views/notifications/invalid_precompiled_letter.html', created_at=notification['created_at']) else: page_count = get_page_count_for_letter(notification['template'], values=personalisation) if notification.get('postage'): notification['template']['postage'] = notification['postage'] template = get_template( notification['template'], current_service, letter_preview_url=url_for( '.view_letter_notification_as_preview', service_id=service_id, notification_id=notification_id, filetype='png', ), page_count=page_count, show_recipient=True, redact_missing_personalisation=True, ) template.values = personalisation if notification['job']: job = job_api_client.get_job(service_id, notification['job']['id'])['data'] else: job = None letter_print_day = get_letter_printing_statement( notification['status'], notification['created_at']) notification_created = parser.parse( notification['created_at']).replace(tzinfo=None) show_cancel_button = notification['notification_type'] == 'letter' and \ letter_can_be_cancelled(notification['status'], notification_created) if get_help_argument() or request.args.get('help') == '0': # help=0 is set when you’ve just sent a notification. We # only want to show the back link when you’ve navigated to a # notification, not when you’ve just sent it. back_link = None elif request.args.get('from_job'): back_link = url_for( 'main.view_job', service_id=current_service.id, job_id=request.args.get('from_job'), ) else: back_link = url_for( 'main.view_notifications', service_id=current_service.id, message_type=template.template_type, status='sending,delivered,failed', ) return render_template( 'views/notifications/notification.html', finished=(notification['status'] in (DELIVERED_STATUSES + FAILURE_STATUSES)), notification_status=notification['status'], uploaded_file_name='Report', template=template, job=job, updates_url=url_for(".view_notification_updates", service_id=service_id, notification_id=notification['id'], status=request.args.get('status'), help=get_help_argument()), partials=get_single_notification_partials(notification), created_by=notification.get('created_by'), created_at=notification['created_at'], updated_at=notification['updated_at'], help=get_help_argument(), estimated_letter_delivery_date=get_letter_timings( notification['created_at'], postage=notification['postage']).earliest_delivery, notification_id=notification['id'], postage=notification['postage'], can_receive_inbound=(current_service.has_permission('inbound_sms')), is_precompiled_letter=notification['template'] ['is_precompiled_letter'], letter_print_day=letter_print_day, show_cancel_button=show_cancel_button, sent_with_test_key=(notification.get('key_type') == KEY_TYPE_TEST), back_link=back_link, )
def send_one_off_step(service_id, template_id, step_index): if {'recipient', 'placeholders'} - set(session.keys()): return redirect( url_for( ".send_one_off", service_id=service_id, template_id=template_id, )) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() template_values = get_recipient_and_placeholders_from_session( db_template['template_type']) template = get_template(db_template, current_service, show_recipient=True, letter_preview_url=url_for( 'no_cookie.send_test_preview', service_id=service_id, template_id=template_id, filetype='png', ), page_count=get_page_count_for_letter( db_template, values=template_values), email_reply_to=email_reply_to, sms_sender=sms_sender) placeholders = fields_to_fill_in(template) try: current_placeholder = placeholders[step_index] except IndexError: if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) return redirect( url_for( '.send_one_off', service_id=service_id, template_id=template_id, )) # if we're in a letter, we should show address block rather than "address line #" or "postcode" if template.template_type == 'letter': if step_index < len(address_lines_1_to_7_keys): return redirect( url_for( '.send_one_off_letter_address', service_id=service_id, template_id=template_id, )) if current_placeholder in Columns( PostalAddress('').as_personalisation): return redirect( url_for( request.endpoint, service_id=service_id, template_id=template_id, step_index=step_index + 1, )) form = get_placeholder_form_instance( current_placeholder, dict_to_populate_from=get_normalised_placeholders_from_session(), template_type=template.template_type, allow_international_phone_numbers=current_service.has_permission( 'international_sms'), ) if form.validate_on_submit(): # if it's the first input (phone/email), we store against `recipient` as well, for easier extraction. # Only if it's not a letter. # And only if we're not on the test route, since that will already have the user's own number set if (step_index == 0 and template.template_type != 'letter'): session['recipient'] = form.placeholder_value.data session['placeholders'][ current_placeholder] = form.placeholder_value.data if all_placeholders_in_session(placeholders): return get_notification_check_endpoint(service_id, template) return redirect( url_for( request.endpoint, service_id=service_id, template_id=template_id, step_index=step_index + 1, )) back_link = get_back_link(service_id, template, step_index, placeholders) template.values = template_values template.values[current_placeholder] = None return render_template( 'views/send-test.html', page_title=get_send_test_page_title( template.template_type, entering_recipient=not session['recipient'], name=template.name, ), template=template, form=form, skip_link=get_skip_link(step_index, template), back_link=back_link, link_to_upload=(request.endpoint == 'main.send_one_off_step' and step_index == 0), )
def send_messages(service_id, template_id): db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template['template_type'] == 'email': email_reply_to = get_email_reply_to_address_from_session() elif db_template['template_type'] == 'sms': sms_sender = get_sms_sender_from_session() if db_template[ 'template_type'] not in current_service.available_template_types: return redirect( url_for('.action_blocked', service_id=service_id, notification_type=db_template['template_type'], return_to='view_template', template_id=template_id)) template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( 'no_cookie.view_letter_template_preview', service_id=service_id, template_id=template_id, filetype='png', page_count=get_page_count_for_letter(db_template), ), email_reply_to=email_reply_to, sms_sender=sms_sender, ) form = CsvUploadForm() if form.validate_on_submit(): try: upload_id = s3upload(service_id, Spreadsheet.from_file_form(form).as_dict, current_app.config['AWS_REGION']) file_name_metadata = unicode_truncate( SanitiseASCII.encode(form.file.data.filename), 1600) set_metadata_on_csv_upload(service_id, upload_id, original_file_name=file_name_metadata) return redirect( url_for( '.check_messages', service_id=service_id, upload_id=upload_id, template_id=template.id, )) except (UnicodeDecodeError, BadZipFile, XLRDError): flash( 'Could not read {}. Try using a different file format.'.format( form.file.data.filename)) except (XLDateError): flash(( '{} contains numbers or dates that Notify cannot understand. ' 'Try formatting all columns as ‘text’ or export your file as CSV.' ).format(form.file.data.filename)) column_headings = get_spreadsheet_column_headings_from_template(template) return render_template( 'views/send.html', template=template, column_headings=list(ascii_uppercase[:len(column_headings)]), example=[column_headings, get_example_csv_rows(template)], form=form, allowed_file_extensions=Spreadsheet.ALLOWED_FILE_EXTENSIONS)
def view_notification(service_id, notification_id): notification = notification_api_client.get_notification(service_id, str(notification_id)) notification["template"].update({"reply_to_text": notification["reply_to_text"]}) personalisation = get_all_personalisation_from_notification(notification) if notification["template"]["is_precompiled_letter"]: try: file_contents = view_letter_notification_as_preview(service_id, notification_id, "pdf") page_count = pdf_page_count(io.BytesIO(file_contents)) except PdfReadError: return render_template( "views/notifications/invalid_precompiled_letter.html", created_at=notification["created_at"], ) else: page_count = get_page_count_for_letter(notification["template"], values=personalisation) if notification.get("postage"): notification["template"]["postage"] = notification["postage"] template = get_template( notification["template"], current_service, letter_preview_url=url_for( ".view_letter_notification_as_preview", service_id=service_id, notification_id=notification_id, filetype="png", ), page_count=page_count, show_recipient=True, redact_missing_personalisation=True, ) template.values = personalisation if notification["job"]: job = job_api_client.get_job(service_id, notification["job"]["id"])["data"] else: job = None letter_print_day = get_letter_printing_statement(notification["status"], notification["created_at"]) notification_created = parser.parse(notification["created_at"]).replace(tzinfo=None) show_cancel_button = notification["notification_type"] == "letter" and letter_can_be_cancelled( notification["status"], notification_created ) if get_help_argument() or request.args.get("help") == "0": # help=0 is set when you’ve just sent a notification. We # only want to show the back link when you’ve navigated to a # notification, not when you’ve just sent it. back_link = None elif request.args.get("from_job"): back_link = url_for( "main.view_job", service_id=current_service.id, job_id=request.args.get("from_job"), ) else: back_link = url_for( "main.view_notifications", service_id=current_service.id, message_type=template.template_type, status="sending,delivered,failed", ) return render_template( "views/notifications/notification.html", finished=(notification["status"] in (DELIVERED_STATUSES + FAILURE_STATUSES)), notification_status=notification["status"], uploaded_file_name="Report", template=template, job=job, updates_url=url_for( ".view_notification_updates", service_id=service_id, notification_id=notification["id"], status=request.args.get("status"), help=get_help_argument(), ), partials=get_single_notification_partials(notification), created_by=notification.get("created_by"), created_at=notification["created_at"], updated_at=notification["updated_at"], help=get_help_argument(), estimated_letter_delivery_date=get_letter_timings( notification["created_at"], postage=notification["postage"] ).earliest_delivery, notification_id=notification["id"], postage=notification["postage"], can_receive_inbound=(current_service.has_permission("inbound_sms")), is_precompiled_letter=notification["template"]["is_precompiled_letter"], letter_print_day=letter_print_day, show_cancel_button=show_cancel_button, sent_with_test_key=(notification.get("key_type") == KEY_TYPE_TEST), back_link=back_link, just_sent=request.args.get("just_sent"), attachments=get_attachments(notification, "attach").values(), )
def s3_send(service_id, template_id): # if there's lots of data in the session, lets log it for debugging purposes # TODO: Remove this once we're confident we have session size under control if len(session.get("file_uploads", {}).keys()) > 2: current_app.logger.info( "session contains large file_uploads - json_len {}, keys: {}". format(len(json.dumps(session["file_uploads"])), session["file_uploads"].keys())) db_template = current_service.get_template_with_user_permission_or_403( template_id, current_user) email_reply_to = None sms_sender = None if db_template["template_type"] == "email": email_reply_to = get_email_reply_to_address_from_session() elif db_template["template_type"] == "sms": sms_sender = get_sms_sender_from_session() is_email_or_sms_not_enabled = email_or_sms_not_enabled( db_template["template_type"], current_service.permissions) if is_email_or_sms_not_enabled or not service_can_bulk_send(service_id): return redirect( url_for( ".action_blocked", service_id=service_id, notification_type=db_template["template_type"], return_to="view_template", template_id=template_id, )) template = get_template( db_template, current_service, show_recipient=True, letter_preview_url=url_for( ".view_letter_template_preview", service_id=service_id, template_id=template_id, filetype="png", page_count=get_page_count_for_letter(db_template), ), email_reply_to=email_reply_to, sms_sender=sms_sender, ) s3_objects = list_bulk_send_uploads() form = SelectCsvFromS3Form( choices=[(x.key, x.key) for x in s3_objects], # (value, label) label="Select a file from Amazon S3", ) if form.validate_on_submit(): try: upload_id = copy_bulk_send_file_to_uploads( service_id, form.s3_files.data, ) return redirect( url_for( ".check_messages", service_id=service_id, upload_id=upload_id, template_id=template.id, original_file_name=form.s3_files.data, )) except (UnicodeDecodeError, BadZipFile, XLRDError): flash( _("Could not read {}. Try using a different file format."). format(form.s3_files.data)) except (XLDateError): flash( _("{} contains numbers or dates that GC Notify can’t understand. " "Try formatting all columns as ‘text’ or export your file as CSV." ).format(form.s3_files.data)) column_headings = get_spreadsheet_column_headings_from_template(template) return render_template( "views/s3-send.html", template=template, column_headings=list(ascii_uppercase[:len(column_headings)]), example=[column_headings, get_example_csv_rows(template)], form=form, )