fix flake8

This commit is contained in:
Kenneth Kehl
2024-07-25 12:38:33 -07:00
13 changed files with 67 additions and 56 deletions
+6 -1
View File
@@ -50,6 +50,7 @@ from app.main.validators import (
CommonlyUsedPassword, CommonlyUsedPassword,
CsvFileValidator, CsvFileValidator,
DoesNotStartWithDoubleZero, DoesNotStartWithDoubleZero,
FieldCannotContainComma,
LettersNumbersSingleQuotesFullStopsAndUnderscoresOnly, LettersNumbersSingleQuotesFullStopsAndUnderscoresOnly,
MustContainAlphanumericCharacters, MustContainAlphanumericCharacters,
NoCommasInPlaceHolders, NoCommasInPlaceHolders,
@@ -1650,7 +1651,11 @@ def get_placeholder_form_instance(
) # TODO: replace with us_mobile_number ) # TODO: replace with us_mobile_number
else: else:
field = GovukTextInputField( field = GovukTextInputField(
placeholder_name, validators=[DataRequired(message="Cannot be empty")] placeholder_name,
validators=[
DataRequired(message="Cannot be empty"),
FieldCannotContainComma(),
],
) )
PlaceholderForm.placeholder_value = field PlaceholderForm.placeholder_value = field
+9
View File
@@ -161,6 +161,15 @@ class DoesNotStartWithDoubleZero:
raise ValidationError(self.message) raise ValidationError(self.message)
class FieldCannotContainComma:
def __init__(self, message="Cannot contain a comma"):
self.message = message
def __call__(self, form, field):
if field.data and "," in field.data:
raise ValidationError(self.message)
class MustContainAlphanumericCharacters: class MustContainAlphanumericCharacters:
regex = re.compile(r".*[a-zA-Z0-9].*[a-zA-Z0-9].*") regex = re.compile(r".*[a-zA-Z0-9].*[a-zA-Z0-9].*")
+6 -17
View File
@@ -1,5 +1,4 @@
import calendar import calendar
from collections import defaultdict
from datetime import datetime from datetime import datetime
from functools import partial from functools import partial
from itertools import groupby from itertools import groupby
@@ -13,7 +12,6 @@ from app import (
billing_api_client, billing_api_client,
current_service, current_service,
job_api_client, job_api_client,
notification_api_client,
service_api_client, service_api_client,
socketio, socketio,
template_statistics_client, template_statistics_client,
@@ -83,18 +81,9 @@ def service_dashboard(service_id):
return redirect(url_for("main.choose_template", service_id=service_id)) return redirect(url_for("main.choose_template", service_id=service_id))
job_response = job_api_client.get_jobs(service_id)["data"] job_response = job_api_client.get_jobs(service_id)["data"]
notifications_response = notification_api_client.get_notifications_for_service(
service_id
)["notifications"]
service_data_retention_days = 7 service_data_retention_days = 7
aggregate_notifications_by_job = defaultdict(list) jobs = [
for notification in notifications_response:
job_id = notification.get("job", {}).get("id", None)
if job_id:
aggregate_notifications_by_job[job_id].append(notification)
job_and_notifications = [
{ {
"job_id": job["id"], "job_id": job["id"],
"time_left": get_time_left(job["created_at"]), "time_left": get_time_left(job["created_at"]),
@@ -105,20 +94,20 @@ def service_dashboard(service_id):
".view_job", service_id=current_service.id, job_id=job["id"] ".view_job", service_id=current_service.id, job_id=job["id"]
), ),
"created_at": job["created_at"], "created_at": job["created_at"],
"processing_finished": job["processing_finished"], "processing_finished": job.get("processing_finished"),
"processing_started": job["processing_started"], "processing_started": job.get("processing_started"),
"notification_count": job["notification_count"], "notification_count": job["notification_count"],
"created_by": job["created_by"], "created_by": job["created_by"],
"notifications": aggregate_notifications_by_job.get(job["id"], []), "template_name": job["template_name"],
"original_file_name": job["original_file_name"],
} }
for job in job_response for job in job_response
if aggregate_notifications_by_job.get(job["id"], [])
] ]
return render_template( return render_template(
"views/dashboard/dashboard.html", "views/dashboard/dashboard.html",
updates_url=url_for(".service_dashboard_updates", service_id=service_id), updates_url=url_for(".service_dashboard_updates", service_id=service_id),
partials=get_dashboard_partials(service_id), partials=get_dashboard_partials(service_id),
job_and_notifications=job_and_notifications, jobs=jobs,
service_data_retention_days=service_data_retention_days, service_data_retention_days=service_data_retention_days,
) )
+14 -4
View File
@@ -36,7 +36,11 @@ def _reformat_keystring(orig):
new_keystring = new_keystring.strip() new_keystring = new_keystring.strip()
new_keystring = new_keystring.replace(" ", "\n") new_keystring = new_keystring.replace(" ", "\n")
new_keystring = "\n".join( new_keystring = "\n".join(
[f"-----BEGIN {private_key}-----", new_keystring, f"-----END {private_key}-----"] [
f"-----BEGIN {private_key}-----",
new_keystring,
f"-----END {private_key}-----",
]
) )
new_keystring = f"{new_keystring}\n" new_keystring = f"{new_keystring}\n"
return new_keystring return new_keystring
@@ -67,7 +71,9 @@ def _get_access_token(code, state):
response = requests.post(url, headers=headers) response = requests.post(url, headers=headers)
if response.json().get("access_token") is None: if response.json().get("access_token") is None:
# Capture the response json here so it hopefully shows up in error reports # Capture the response json here so it hopefully shows up in error reports
current_app.logger.error(f"Error when getting access token {response.json()} #notify-admin-1505") current_app.logger.error(
f"Error when getting access token {response.json()} #notify-admin-1505"
)
raise KeyError(f"'access_token' {response.json()}") raise KeyError(f"'access_token' {response.json()}")
access_token = response.json()["access_token"] access_token = response.json()["access_token"]
return access_token return access_token
@@ -92,7 +98,9 @@ def _do_login_dot_gov():
login_gov_error = request.args.get("error") login_gov_error = request.args.get("error")
if login_gov_error: if login_gov_error:
current_app.logger.error(f"login.gov error: {login_gov_error} #notify-admin-1505") current_app.logger.error(
f"login.gov error: {login_gov_error} #notify-admin-1505"
)
raise Exception(f"Could not login with login.gov {login_gov_error}") raise Exception(f"Could not login with login.gov {login_gov_error}")
elif code and state: elif code and state:
@@ -108,7 +116,9 @@ def _do_login_dot_gov():
abort(403) abort(403)
redirect_url = request.args.get("next") redirect_url = request.args.get("next")
user = user_api_client.get_user_by_uuid_or_email(user_uuid, user_email) user = user_api_client.get_user_by_uuid_or_email(user_uuid, user_email)
current_app.logger.info(f"Retrieved user {user['id']} from db #notify-admin-1505") current_app.logger.info(
f"Retrieved user {user['id']} from db #notify-admin-1505"
)
# Check if the email needs to be revalidated # Check if the email needs to be revalidated
is_fresh_email = is_less_than_days_ago( is_fresh_email = is_less_than_days_ago(
+3 -2
View File
@@ -38,7 +38,7 @@ def verify_email(token):
current_app.config["EMAIL_EXPIRY_SECONDS"], current_app.config["EMAIL_EXPIRY_SECONDS"],
) )
except SignatureExpired: except SignatureExpired:
current_app.logger.error(f"Email link expired #notify-admin-1505") current_app.logger.error("Email link expired #notify-admin-1505")
flash( flash(
"The link in the email we sent you has expired. We've sent you a new one." "The link in the email we sent you has expired. We've sent you a new one."
) )
@@ -52,7 +52,8 @@ def verify_email(token):
if user.is_active: if user.is_active:
current_app.logger.error( current_app.logger.error(
f"User is using an invite link but is already logged in {user.id} #notify-admin-1505") f"User is using an invite link but is already logged in {user.id} #notify-admin-1505"
)
flash("That verification link has expired.") flash("That verification link has expired.")
return redirect(url_for("main.sign_in")) return redirect(url_for("main.sign_in"))
+5
View File
@@ -58,6 +58,10 @@ class NotifyAdminAPIClient(BaseAPIClient):
def check_inactive_user(self, *args): def check_inactive_user(self, *args):
still_signing_in = False still_signing_in = False
# TODO clean up and add testing etc.
# We really should be checking for exact matches
# and we only want to check the first arg
for arg in args: for arg in args:
arg = str(arg) arg = str(arg)
if ( if (
@@ -66,6 +70,7 @@ class NotifyAdminAPIClient(BaseAPIClient):
or "/activate" in arg or "/activate" in arg
or "/email-code" in arg or "/email-code" in arg
or "/verify/code" in arg or "/verify/code" in arg
or "/user" in arg
): ):
still_signing_in = True still_signing_in = True
+14
View File
@@ -58,6 +58,20 @@
</ul> </ul>
</div> </div>
</nav> </nav>
<section class="usa-identifier__section usa-identifier__section--usagov"
aria-label="Github Repos">
<div class="usa-identifier__container">
<div class="usa-identifier__required-links-item">
Find us on Github:
</div>
<ul>
<li><a href="https://github.com/gsa/notifications-admin" class="usa-identifier__required-link">Notify.gov Admin repo</a></li>
<li><a href="https://github.com/gsa/notifications-api" class="usa-identifier__required-link">Notify.gov API repo</a></li>
</ul>
</div>
</section>
<section class="usa-identifier__section usa-identifier__section--usagov" <section class="usa-identifier__section usa-identifier__section--usagov"
aria-label="Government information and services"> aria-label="Government information and services">
<div class="usa-identifier__container"> <div class="usa-identifier__container">
+6 -8
View File
@@ -55,31 +55,30 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{% if job_and_notifications %} {% if jobs %}
{% for job in job_and_notifications[:5] %} {% for job in jobs[:5] %}
{% if job.job_id and job.notifications %}
{% set notification = job.notifications[0] %} {% set notification = job.notifications[0] %}
<tr class="table-row" id="{{ job.job_id }}"> <tr class="table-row" id="{{ job.job_id }}">
<td class="table-field file-name"> <td class="table-field file-name">
{{ notification.job.original_file_name[:12] if notification.job.original_file_name else 'Manually entered number'}} {{ job.original_file_name[:12] if job.original_file_name else 'Manually entered number'}}
<br> <br>
<a class="usa-link file-list-filename" href="{{ job.view_job_link }}">View Batch</a> <a class="usa-link file-list-filename" href="{{ job.view_job_link }}">View Batch</a>
</td> </td>
<td class="table-field template"> <td class="table-field template">
{{ notification.template.name }} {{ job.template_name }}
</td> </td>
<td class="table-field time-sent"> <td class="table-field time-sent">
{{ (job.processing_finished if job.processing_finished else job.processing_started {{ (job.processing_finished if job.processing_finished else job.processing_started
if job.processing_started else job.created_at)|format_datetime_table }} if job.processing_started else job.created_at)|format_datetime_table }}
</td> </td>
<td class="table-field sender"> <td class="table-field sender">
{{ notification.created_by.name }} {{ job.created_by.name }}
</td> </td>
<td class="table-field count-of-recipients"> <td class="table-field count-of-recipients">
{{ job.notification_count}} {{ job.notification_count}}
</td> </td>
<td class="table-field report"> <td class="table-field report">
{% if notification and job.time_left != "Data no longer available" %} {% if job.time_left != "Data no longer available" %}
<a class="usa-link file-list-filename" href="{{ job.download_link }}">Download</a> <a class="usa-link file-list-filename" href="{{ job.download_link }}">Download</a>
<span class="usa-hint">{{ job.time_left }}</span> <span class="usa-hint">{{ job.time_left }}</span>
{% elif job %} {% elif job %}
@@ -87,7 +86,6 @@
{% endif %} {% endif %}
</td> </td>
</tr> </tr>
{% endif %}
{% endfor %} {% endfor %}
{% else %} {% else %}
<tr class="table-row"> <tr class="table-row">
+1 -1
View File
@@ -1,6 +1,6 @@
env: production env: production
instances: 2 instances: 2
memory: 2G memory: 1.5G
public_admin_route: beta.notify.gov public_admin_route: beta.notify.gov
cloud_dot_gov_route: notify.app.cloud.gov cloud_dot_gov_route: notify.app.cloud.gov
redis_enabled: 1 redis_enabled: 1
+1 -1
View File
@@ -149,7 +149,7 @@ const images = () => {
paths.govuk_frontend + 'assets/images/**/*', paths.govuk_frontend + 'assets/images/**/*',
paths.src + 'images/**/*', paths.src + 'images/**/*',
paths.src + 'img/**/*', paths.src + 'img/**/*',
]) ], {encoding: false})
.pipe(dest(paths.dist + 'images/')) .pipe(dest(paths.dist + 'images/'))
}; };
+1 -1
View File
@@ -1 +1 @@
python-3.12.3 python-3.12.x
+1 -1
View File
@@ -65,7 +65,7 @@ module "domain" {
cf_space_name = local.cf_space_name cf_space_name = local.cf_space_name
app_name_or_id = "${local.app_name}-${local.env}" app_name_or_id = "${local.app_name}-${local.env}"
name = "${local.app_name}-domain-${local.env}" name = "${local.app_name}-domain-${local.env}"
recursive_delete = local.recursive_delete recursive_delete = false
cdn_plan_name = "domain" cdn_plan_name = "domain"
domain_name = "beta.notify.gov" domain_name = "beta.notify.gov"
} }
-20
View File
@@ -305,10 +305,6 @@ def test_inbound_messages_shows_count_of_messages_when_there_are_messages(
mock_get_inbound_sms_summary, mock_get_inbound_sms_summary,
): ):
service_one["permissions"] = ["inbound_sms"] service_one["permissions"] = ["inbound_sms"]
mocker.patch(
"app.notification_api_client.get_notifications_for_service",
return_value=FAKE_ONE_OFF_NOTIFICATION,
)
page = client_request.get( page = client_request.get(
"main.service_dashboard", "main.service_dashboard",
service_id=SERVICE_ONE_ID, service_id=SERVICE_ONE_ID,
@@ -337,10 +333,6 @@ def test_inbound_messages_shows_count_of_messages_when_there_are_no_messages(
mock_get_inbound_sms_summary_with_no_messages, mock_get_inbound_sms_summary_with_no_messages,
): ):
service_one["permissions"] = ["inbound_sms"] service_one["permissions"] = ["inbound_sms"]
mocker.patch(
"app.notification_api_client.get_notifications_for_service",
return_value=FAKE_ONE_OFF_NOTIFICATION,
)
page = client_request.get( page = client_request.get(
"main.service_dashboard", "main.service_dashboard",
service_id=SERVICE_ONE_ID, service_id=SERVICE_ONE_ID,
@@ -839,10 +831,6 @@ def test_should_not_show_upcoming_jobs_on_dashboard_if_count_is_0(
}, },
) )
mocker.patch("app.job_api_client.get_jobs", return_value=MOCK_JOBS) mocker.patch("app.job_api_client.get_jobs", return_value=MOCK_JOBS)
mocker.patch(
"app.notification_api_client.get_notifications_for_service",
return_value=FAKE_ONE_OFF_NOTIFICATION,
)
page = client_request.get( page = client_request.get(
"main.service_dashboard", "main.service_dashboard",
service_id=SERVICE_ONE_ID, service_id=SERVICE_ONE_ID,
@@ -919,10 +907,6 @@ def test_correct_font_size_for_big_numbers(
mocker.patch("app.main.views.dashboard.get_dashboard_totals", return_value=totals) mocker.patch("app.main.views.dashboard.get_dashboard_totals", return_value=totals)
mocker.patch("app.job_api_client.get_jobs", return_value=MOCK_JOBS) mocker.patch("app.job_api_client.get_jobs", return_value=MOCK_JOBS)
mocker.patch(
"app.notification_api_client.get_notifications_for_service",
return_value=FAKE_ONE_OFF_NOTIFICATION,
)
page = client_request.get( page = client_request.get(
"main.service_dashboard", "main.service_dashboard",
service_id=service_one["id"], service_id=service_one["id"],
@@ -952,10 +936,6 @@ def test_should_not_show_jobs_on_dashboard_for_users_with_uploads_page(
mock_get_free_sms_fragment_limit, mock_get_free_sms_fragment_limit,
mock_get_inbound_sms_summary, mock_get_inbound_sms_summary,
): ):
mocker.patch(
"app.notification_api_client.get_notifications_for_service",
return_value=FAKE_ONE_OFF_NOTIFICATION,
)
page = client_request.get( page = client_request.get(
"main.service_dashboard", "main.service_dashboard",
service_id=SERVICE_ONE_ID, service_id=SERVICE_ONE_ID,