Compare commits

..

1 Commits

Author SHA1 Message Date
Sheev Davé
42ff7aa623 Update issue_template.yml
Added a11y checks and language in the acceptance criteria, tasks, and dependencies sections
2025-01-22 12:14:31 -08:00
268 changed files with 7868 additions and 13191 deletions

View File

@@ -161,7 +161,7 @@
"filename": "app/config.py",
"hashed_secret": "577a4c667e4af8682ca431857214b3a920883efc",
"is_verified": false,
"line_number": 123,
"line_number": 120,
"is_secret": false
}
],
@@ -399,6 +399,26 @@
"is_secret": false
}
],
"app/templates/new/components/head.html": [
{
"type": "Base64 High Entropy String",
"filename": "app/templates/new/components/head.html",
"hashed_secret": "ee5048791fc7ff45a1545e24f85bec3317371327",
"is_verified": false,
"line_number": 33,
"is_secret": false
}
],
"app/templates/old/admin_template.html": [
{
"type": "Base64 High Entropy String",
"filename": "app/templates/old/admin_template.html",
"hashed_secret": "ee5048791fc7ff45a1545e24f85bec3317371327",
"is_verified": false,
"line_number": 18,
"is_secret": false
}
],
"deploy-config/sandbox.yml": [
{
"type": "Secret Keyword",
@@ -507,7 +527,7 @@
"filename": "tests/app/main/views/test_accept_invite.py",
"hashed_secret": "07f0a6c13923fc3b5f0c57ffa2d29b715eb80d71",
"is_verified": false,
"line_number": 631,
"line_number": 643,
"is_secret": false
}
],
@@ -553,7 +573,7 @@
"filename": "tests/app/main/views/test_sign_in.py",
"hashed_secret": "8b8b69116ee882b5e987e330f55db81aba0636f9",
"is_verified": false,
"line_number": 95,
"line_number": 97,
"is_secret": false
}
],
@@ -632,7 +652,37 @@
"line_number": 3266,
"is_secret": false
}
],
"tests/notifications_utils/clients/antivirus/test_antivirus_client.py": [
{
"type": "Secret Keyword",
"filename": "tests/notifications_utils/clients/antivirus/test_antivirus_client.py",
"hashed_secret": "932b25270abe1301c22c709a19082dff07d469ff",
"is_verified": false,
"line_number": 16,
"is_secret": false
}
],
"tests/notifications_utils/clients/encryption/test_encryption_client.py": [
{
"type": "Secret Keyword",
"filename": "tests/notifications_utils/clients/encryption/test_encryption_client.py",
"hashed_secret": "f1e923a9667de11be6a210849a8651c1bfd81605",
"is_verified": false,
"line_number": 13,
"is_secret": false
}
],
"tests/notifications_utils/clients/zendesk/test_zendesk_client.py": [
{
"type": "Secret Keyword",
"filename": "tests/notifications_utils/clients/zendesk/test_zendesk_client.py",
"hashed_secret": "913a73b565c8e2c8ed94497580f619397709b8b6",
"is_verified": false,
"line_number": 16,
"is_secret": false
}
]
},
"generated_at": "2025-06-04T16:12:20Z"
"generated_at": "2025-01-16T16:38:48Z"
}

View File

@@ -37,7 +37,7 @@ body:
- type: textarea
id: acceptanceCriteria
attributes:
label: "Detailed condition or criteria that must be met for the user story to be considered complete."
label: "Detailed condition or criteria that must be met for the user story to be considered complete. This includes basic a11y checks around screen readers and keyboard testing."
description: "List the acceptance criteria for the user story."
validations:
required: true
@@ -48,7 +48,7 @@ body:
- type: textarea
id: tasks
attributes:
label: "List of specific tasks or sub-tasks that need to be done to implement the user story."
label: "List of specific tasks or sub-tasks that need to be done to implement the user story. This includes a11y standards."
description: "Outline the tasks necessary to implement the user story."
validations:
required: true
@@ -59,22 +59,11 @@ body:
- type: textarea
id: dependencies
attributes:
label: "List any dependencies that need to be resolved before starting or completing this user story."
label: "List any dependencies that need to be resolved before starting or completing this user story. This includes screenreaders and keyboard testing passing."
description: "Specify any dependencies related to the user story."
validations:
required: false
- type: markdown
attributes:
value: '**Accessibility:**'
- type: textarea
id: accessibility
attributes:
label: "List any specific accessibility guidance or tests that need to be considered for this user story."
description: "List what type of accessibility tests need to pass."
validations:
required: false
- type: markdown
attributes:
value: '**Notes:**'

View File

@@ -9,9 +9,10 @@ body:
label: Log In
options:
- label: notify-staging.app.cloud.gov resolves
- label: Clicking sign in takes you to Login.gov
- label: Can sign in via Login.gov
- label: After successful login, you are brought to the “choose service” screen
- label: Clicking sign in takes you to login page
- label: 2FA code is sent promptly
- label: 2FA code input screen appears as expected
- label: After code is entered, you are brought to the “choose service” screen
- label: Choosing a service brings you to the dashboard for that service
- type: checkboxes
@@ -71,10 +72,11 @@ body:
- label: From team member screen, clicking “Change Details” on a specific profile brings you to that persons profile
- label: Clicking on “Remove this team member” prompts a confirmation
- label: Clicking the confirmation removes the team member
- type: checkboxes
id: sign_out
attributes:
label: Sign Out
options:
- label: Clicking “Sign Out” takes you back to the homepage and logs you out
- label: Hitting “Sign Out” takes you back to the homepage and logs you out

View File

@@ -9,19 +9,13 @@ runs:
sudo apt-get update \
&& sudo apt-get install -y --no-install-recommends \
libcurl4-openssl-dev
- name: Set up Python 3.12.2
- name: Set up Python 3.12.3
uses: actions/setup-python@v4
with:
python-version: "3.12.2"
python-version: "3.12.3"
- name: Install poetry
shell: bash
run: pip install poetry==2.1.3
- name: Install poetry export plugin
shell: bash
run: poetry self add poetry-plugin-export
- name: Downgrade virtualenv to compatible version
shell: bash
run: pip install "virtualenv<20.30"
run: pip install poetry==1.8.5
- name: Install application dependencies
shell: bash
run: make bootstrap

View File

@@ -10,9 +10,9 @@ updates:
schedule:
interval: "daily"
assignees:
- "alexjanousekGSA"
- "A-Shumway42"
reviewers:
- "alexjanousekGSA"
- "A-Shumway42"
- package-ecosystem: "npm"
directory: "/"
schedule:

View File

@@ -23,7 +23,5 @@ Please enter a detailed description here.
## A11y Checks (if applicable)
* Double check work is getting picked up by the automated E2E tests
* Conduct browser-based tests through [AxeDevTools](https://www.deque.com/axe/devtools/) and [WAVE](https://wave.webaim.org/)
* Conduct automated tests through [AxeDevTools](https://www.deque.com/axe/devtools/) and [WAVE](https://wave.webaim.org/)
* Review the [Manual Checklist](https://docs.google.com/document/d/192bBXStebdXWtYhZQ73qaWMJhGcuSB1W6c9YBXhWZvc/edit?usp=sharing)
* Make sure there are no linting errors in VSCode or other IDE of choice

View File

@@ -10,7 +10,7 @@ env:
FLASK_APP: application.py
WERKZEUG_DEBUG_PIN: off
REDIS_ENABLED: 0
NODE_VERSION: 22.3.0
NODE_VERSION: 16.15.1
AWS_US_TOLL_FREE_NUMBER: "+18556438890"
ADMIN_BASE_URL: http://localhost:6012
@@ -38,10 +38,10 @@ jobs:
output: report-markdown
annotations: failed-tests
prnumber: ${{ steps.findPr.outputs.number }}
- name: Check imports alphabetized
run: poetry run isort --check-only ./app ./tests
- name: Run style checks
run: poetry run flake8 .
- name: Check imports alphabetized
run: poetry run isort --check-only ./app ./tests
- name: Check dead code
run: make dead-code
- name: Run js tests
@@ -118,7 +118,6 @@ jobs:
NOTIFY_E2E_TEST_PASSWORD: ${{ secrets.NOTIFY_E2E_TEST_PASSWORD }}
NOTIFY_E2E_TEST_URI: http://localhost:6012/
VCAP_SERVICES: ${{ secrets.VCAP_SERVICES }}
validate-new-relic-config:
runs-on: ubuntu-latest
environment: staging
@@ -139,12 +138,13 @@ jobs:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup-project
- name: Create requirements.txt
run: poetry export --output requirements.txt
- uses: pypa/gh-action-pip-audit@v1.1.0
run: poetry export --without-hashes --format=requirements.txt > requirements.txt
- uses: pypa/gh-action-pip-audit@v1.0.8
with:
inputs: requirements.txt
ignore-vulns: |
PYSEC-2023-312
PYSEC-2024-60
PYSEC-2022-43162
- name: Run npm audit
run: make npm-audit
@@ -165,9 +165,8 @@ jobs:
run: make run-flask &
env:
NOTIFY_ENVIRONMENT: scanning
FEATURE_SOCKET_ENABLED: true
- name: Run OWASP Baseline Scan
uses: zaproxy/action-baseline@v0.14.0
uses: zaproxy/action-baseline@v0.9.0
with:
docker_name: "ghcr.io/zaproxy/zaproxy:weekly"
target: "http://localhost:6012"
@@ -177,7 +176,7 @@ jobs:
cmd_options: "-I"
a11y-scan:
runs-on: ubuntu-latest
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup-project

View File

@@ -16,7 +16,7 @@ env:
FLASK_APP: application.py
WERKZEUG_DEBUG_PIN: off
REDIS_ENABLED: 0
NODE_VERSION: 22.3.0
NODE_VERSION: 16.15.1
jobs:
dependency-audits:
@@ -25,12 +25,10 @@ jobs:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup-project
- name: Create requirements.txt
run: poetry export --output requirements.txt
- uses: pypa/gh-action-pip-audit@v1.1.0
run: poetry export --without-hashes --format=requirements.txt > requirements.txt
- uses: pypa/gh-action-pip-audit@v1.0.6
with:
inputs: requirements.txt
ignore-vulns: |
PYSEC-2023-312
- name: Run npm audit
run: make npm-audit
@@ -52,7 +50,7 @@ jobs:
env:
NOTIFY_ENVIRONMENT: scanning
- name: Run OWASP Full Scan
uses: zaproxy/action-full-scan@v0.12.0
uses: zaproxy/action-full-scan@v0.7.0
with:
docker_name: 'ghcr.io/zaproxy/zaproxy:weekly'
target: 'http://localhost:6012'

View File

@@ -16,21 +16,23 @@ jobs:
with:
fetch-depth: 2
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
- name: Check for changes to Terraform
id: changed-terraform-files
uses: tj-actions/changed-files@v44
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
files: |
terraform/demo/**
terraform/shared/**
.github/workflows/deploy-demo.yml
- name: Terraform init
if: steps.changed-terraform-files.outputs.any_changed == 'true'
working-directory: terraform/demo
env:
AWS_ACCESS_KEY_ID: ${{ secrets.TERRAFORM_STATE_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.TERRAFORM_STATE_SECRET_ACCESS_KEY }}
run: terraform init
- name: Terraform apply
if: steps.changed-terraform-files.outputs.any_changed == 'true'
working-directory: terraform/demo
env:
AWS_ACCESS_KEY_ID: ${{ secrets.TERRAFORM_STATE_ACCESS_KEY }}
@@ -42,7 +44,7 @@ jobs:
- uses: ./.github/actions/setup-project
- name: Create requirements.txt
run: poetry export --output requirements.txt
run: poetry export --without-hashes --format=requirements.txt > requirements.txt
- name: Deploy to cloud.gov
uses: cloud-gov/cg-cli-tools@main
@@ -63,8 +65,6 @@ jobs:
LOGIN_DOT_GOV_SIGNOUT_REDIRECT: "https://notify-demo.app.cloud.gov/sign-out"
LOGIN_DOT_GOV_INITIAL_SIGNIN_URL: "https://secure.login.gov/openid_connect/authorize?acr_values=http%3A%2F%2Fidmanagement.gov%2Fns%2Fassurance%2Fial%2F1&client_id=urn:gov:gsa:openidconnect.profiles:sp:sso:gsa:notify-gov&nonce=NONCE&prompt=select_account&redirect_uri=https://notify-demo.app.cloud.gov/sign-in&response_type=code&scope=openid+email&state=STATE"
LOGIN_DOT_GOV_CERTS_URL: "https://secure.login.gov/api/openid_connect/certs"
API_PUBLIC_URL: ${{ secrets.API_PUBLIC_URL }}
API_PUBLIC_WS_URL: ${{ secrets.API_PUBLIC_WS_URL }}
with:
cf_username: ${{ secrets.CLOUDGOV_USERNAME }}
cf_password: ${{ secrets.CLOUDGOV_PASSWORD }}
@@ -89,11 +89,18 @@ jobs:
--var LOGIN_DOT_GOV_INITIAL_SIGNIN_URL="$LOGIN_DOT_GOV_INITIAL_SIGNIN_URL"
--var LOGIN_DOT_GOV_CERTS_URL="$LOGIN_DOT_GOV_CERTS_URL"
--var LOGIN_PEM="$LOGIN_PEM"
--var API_PUBLIC_URL="$API_PUBLIC_URL"
--var API_PUBLIC_WS_URL="$API_PUBLIC_WS_URL"
--strategy rolling
- name: Check for changes to egress config
id: changed-egress-config
uses: tj-actions/changed-files@v44
with:
files: |
deploy-config/egress_proxy/notify-admin-demo.*.acl
.github/actions/deploy-proxy/action.yml
.github/workflows/deploy-demo.yml
- name: Deploy egress proxy
if: steps.changed-egress-config.outputs.any_changed == 'true'
uses: ./.github/actions/deploy-proxy
env:
CF_USERNAME: ${{ secrets.CLOUDGOV_USERNAME }}

View File

@@ -16,21 +16,23 @@ jobs:
with:
fetch-depth: 2
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
- name: Check for changes to Terraform
id: changed-terraform-files
uses: tj-actions/changed-files@v44
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
files: |
terraform/production/**
terraform/shared/**
.github/workflows/deploy-prod.yml
- name: Terraform init
if: steps.changed-terraform-files.outputs.any_changed == 'true'
working-directory: terraform/production
env:
AWS_ACCESS_KEY_ID: ${{ secrets.TERRAFORM_STATE_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.TERRAFORM_STATE_SECRET_ACCESS_KEY }}
run: terraform init
- name: Terraform apply
if: steps.changed-terraform-files.outputs.any_changed == 'true'
working-directory: terraform/production
env:
AWS_ACCESS_KEY_ID: ${{ secrets.TERRAFORM_STATE_ACCESS_KEY }}
@@ -42,7 +44,7 @@ jobs:
- uses: ./.github/actions/setup-project
- name: Create requirements.txt
run: poetry export --output requirements.txt
run: poetry export --without-hashes --format=requirements.txt > requirements.txt
- name: Deploy to cloud.gov
uses: cloud-gov/cg-cli-tools@main
@@ -63,8 +65,6 @@ jobs:
LOGIN_DOT_GOV_SIGNOUT_REDIRECT: "https://beta.notify.gov/sign-out"
LOGIN_DOT_GOV_INITIAL_SIGNIN_URL: "https://secure.login.gov/openid_connect/authorize?acr_values=http%3A%2F%2Fidmanagement.gov%2Fns%2Fassurance%2Fial%2F1&client_id=urn:gov:gsa:openidconnect.profiles:sp:sso:gsa:notify-gov&nonce=NONCE&prompt=select_account&redirect_uri=https://beta.notify.gov/sign-in&response_type=code&scope=openid+email&state=STATE"
LOGIN_DOT_GOV_CERTS_URL: "https://secure.login.gov/api/openid_connect/certs"
API_PUBLIC_URL: ${{ secrets.API_PUBLIC_URL }}
API_PUBLIC_WS_URL: ${{ secrets.API_PUBLIC_WS_URL }}
with:
cf_username: ${{ secrets.CLOUDGOV_USERNAME }}
cf_password: ${{ secrets.CLOUDGOV_PASSWORD }}
@@ -89,11 +89,18 @@ jobs:
--var LOGIN_DOT_GOV_INITIAL_SIGNIN_URL="$LOGIN_DOT_GOV_INITIAL_SIGNIN_URL"
--var LOGIN_DOT_GOV_CERTS_URL="$LOGIN_DOT_GOV_CERTS_URL"
--var LOGIN_PEM="$LOGIN_PEM"
--var API_PUBLIC_URL="$API_PUBLIC_URL"
--var API_PUBLIC_WS_URL="$API_PUBLIC_WS_URL"
--strategy rolling
- name: Check for changes to egress config
id: changed-egress-config
uses: tj-actions/changed-files@v44
with:
files: |
deploy-config/egress_proxy/notify-admin-production.*.acl
.github/actions/deploy-proxy/action.yml
.github/workflows/deploy-prod.yml
- name: Deploy egress proxy
if: steps.changed-egress-config.outputs.any_changed == 'true'
uses: ./.github/actions/deploy-proxy
env:
CF_USERNAME: ${{ secrets.CLOUDGOV_USERNAME }}

View File

@@ -21,21 +21,23 @@ jobs:
with:
fetch-depth: 2
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
- name: Check for changes to Terraform
id: changed-terraform-files
uses: tj-actions/changed-files@v44
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
files: |
terraform/staging/**
terraform/shared/**
.github/workflows/deploy.yml
- name: Terraform init
if: steps.changed-terraform-files.outputs.any_changed == 'true'
working-directory: terraform/staging
env:
AWS_ACCESS_KEY_ID: ${{ secrets.TERRAFORM_STATE_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.TERRAFORM_STATE_SECRET_ACCESS_KEY }}
run: terraform init
- name: Terraform apply
if: steps.changed-terraform-files.outputs.any_changed == 'true'
working-directory: terraform/staging
env:
AWS_ACCESS_KEY_ID: ${{ secrets.TERRAFORM_STATE_ACCESS_KEY }}
@@ -47,7 +49,7 @@ jobs:
- uses: ./.github/actions/setup-project
- name: Create requirements.txt
run: poetry export --output requirements.txt
run: poetry export --without-hashes --format=requirements.txt > requirements.txt
- name: Deploy to cloud.gov
@@ -69,8 +71,6 @@ jobs:
LOGIN_DOT_GOV_SIGNOUT_REDIRECT: "https://notify-staging.app.cloud.gov/sign-out"
LOGIN_DOT_GOV_INITIAL_SIGNIN_URL: "https://secure.login.gov/openid_connect/authorize?acr_values=http%3A%2F%2Fidmanagement.gov%2Fns%2Fassurance%2Fial%2F1&client_id=urn:gov:gsa:openidconnect.profiles:sp:sso:gsa:notify-gov&nonce=NONCE&prompt=select_account&redirect_uri=https://notify-staging.app.cloud.gov/sign-in&response_type=code&scope=openid+email&state=STATE"
LOGIN_DOT_GOV_CERTS_URL: "https://secure.login.gov/api/openid_connect/certs"
API_PUBLIC_URL: ${{ secrets.API_PUBLIC_URL }}
API_PUBLIC_WS_URL: ${{ secrets.API_PUBLIC_WS_URL }}
with:
cf_username: ${{ secrets.CLOUDGOV_USERNAME }}
cf_password: ${{ secrets.CLOUDGOV_PASSWORD }}
@@ -95,12 +95,19 @@ jobs:
--var LOGIN_DOT_GOV_INITIAL_SIGNIN_URL="$LOGIN_DOT_GOV_INITIAL_SIGNIN_URL"
--var LOGIN_DOT_GOV_CERTS_URL="$LOGIN_DOT_GOV_CERTS_URL"
--var LOGIN_PEM="$LOGIN_PEM"
--var API_PUBLIC_URL="$API_PUBLIC_URL"
--var API_PUBLIC_WS_URL="$API_PUBLIC_WS_URL"
--strategy rolling
- name: Check for changes to egress config
id: changed-egress-config
uses: tj-actions/changed-files@v44
with:
files: |
deploy-config/egress_proxy/notify-admin-staging.*.acl
.github/actions/deploy-proxy/action.yml
.github/workflows/deploy.yml
- name: Deploy egress proxy
if: steps.changed-egress-config.outputs.any_changed == 'true'
uses: ./.github/actions/deploy-proxy
env:
CF_USERNAME: ${{ secrets.CLOUDGOV_USERNAME }}

View File

@@ -15,14 +15,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
- name: Check for drift
uses: dflook/terraform-check@v1
env:
@@ -43,14 +35,6 @@ jobs:
with:
ref: 'production'
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
- name: Check for drift
uses: dflook/terraform-check@v1
env:
@@ -71,14 +55,6 @@ jobs:
with:
ref: 'production'
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
- name: Check for drift
uses: dflook/terraform-check@v1
env:

View File

@@ -18,14 +18,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
- name: Terraform format
id: format
run: terraform fmt -check
@@ -59,7 +51,7 @@ jobs:
# inspiration: https://learn.hashicorp.com/tutorials/terraform/github-actions#review-actions-workflow
- name: Update PR
uses: actions/github-script@v7
uses: actions/github-script@v6
# we would like to update the PR even when a prior step failed
if: ${{ always() }}
with:

View File

@@ -18,14 +18,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
- name: Terraform format
id: format
run: terraform fmt -check
@@ -59,7 +51,7 @@ jobs:
# inspiration: https://learn.hashicorp.com/tutorials/terraform/github-actions#review-actions-workflow
- name: Update PR
uses: actions/github-script@v7
uses: actions/github-script@v6
# we would like to update the PR even when a prior step failed
if: ${{ always() }}
with:

View File

@@ -18,14 +18,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
# Looks like we need to install Terraform ourselves now!
# https://github.com/actions/runner-images/issues/10796#issuecomment-2417064348
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "^1.7.5"
terraform_wrapper: false
- name: Terraform format
id: format
run: terraform fmt -check
@@ -59,7 +51,7 @@ jobs:
# inspiration: https://learn.hashicorp.com/tutorials/terraform/github-actions#review-actions-workflow
- name: Update PR
uses: actions/github-script@v7
uses: actions/github-script@v6
# we would like to update the PR even when a prior step failed
if: ${{ always() }}
with:

9
.gitignore vendored
View File

@@ -14,16 +14,7 @@
*.XLSX
## Non user files allowed to be commited
!app/assets/pdf/wa_case_study.pdf
!app/assets/pdf/best-practices-for-texting-the-public.pdf
!app/assets/pdf/investing-in-notifications-tts-public-benefits-studio-decision-memo.pdf
!app/assets/pdf/best-practices-section-outline.pdf
!app/assets/pdf/standing-up-your-own-notify.pdf
!app/assets/pdf/tcpa_overview.pdf
!app/assets/pdf/investing-notifications-tts-public-benefits-memo.pdf
!app/assets/pdf/out-of-pilot-announcement.pdf
!app/assets/pdf/studio-research-snapshot-2022-07-external.pdf
!app/assets/pdf/TCPA-Overview.pdf
!tests/test_pdf_files/no_eof_marker.pdf
!tests/test_pdf_files/multi_page_pdf.pdf
!tests/test_pdf_files/big.pdf

View File

@@ -1,10 +1,7 @@
{
"defaults": {
"standard": "WCAG2AA",
"runners": ["htmlcs"],
"chromeLaunchConfig": {
"executablePath": "/usr/bin/google-chrome"
},
"runners": ["htmlcs"],
"concurrency": 1,
"hideElements": [
"nav > ol a",

View File

@@ -8,7 +8,6 @@ repos:
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
exclude: ^app/assets/pdf/.*\.pdf$
- id: debug-statements
- id: check-merge-conflict
- id: check-toml

View File

@@ -6,4 +6,4 @@
export NEW_RELIC_PROXY_HOST=$egress_proxy
export http_proxy=$egress_proxy
export https_proxy=$egress_proxy
export no_proxy="apps.internal,s3-fips.us-gov-west-1.amazonaws.com"
export no_proxy="apps.internal"

View File

@@ -6,7 +6,6 @@ APP_VERSION_FILE = app/version.py
GIT_BRANCH ?= $(shell git symbolic-ref --short HEAD 2> /dev/null || echo "detached")
GIT_COMMIT ?= $(shell git rev-parse HEAD 2> /dev/null || echo "")
GIT_HOOKS_PATH ?= $(shell git config --global core.hooksPath || echo "")
VIRTUALENV_ROOT := $(shell [ -z $$VIRTUAL_ENV ] && echo $$(pwd)/venv || echo $$VIRTUAL_ENV)
@@ -15,27 +14,16 @@ NVMSH := $(shell [ -f "$(HOME)/.nvm/nvm.sh" ] && echo "$(HOME)/.nvm/nvm.sh" || e
## DEVELOPMENT
.PHONY: bootstrap
bootstrap: ## Set up everything to run the app
make generate-version-file
poetry sync --no-root
bootstrap: generate-version-file ## Set up everything to run the app
poetry self add poetry-dotenv-plugin
poetry lock --no-update
poetry install --sync --no-root
poetry run playwright install --with-deps
poetry run pre-commit install
source $(NVMSH) --no-use && nvm install && npm install
source $(NVMSH) && npm ci --no-audit
source $(NVMSH) && npm run build
.PHONY: bootstrap-with-git-hooks
bootstrap-with-git-hooks: ## Sets everything up and accounts for pre-existing git hooks
make generate-version-file
poetry sync --no-root
poetry run playwright install --with-deps
git config --global --unset-all core.hooksPath
poetry run pre-commit install
git config --global core.hookspath "${GIT_HOOKS_PATH}"
source $(NVMSH) --no-use && nvm install && npm install
source $(NVMSH) && npm ci --no-audit
source $(NVMSH) && npm run build
.PHONY: watch-frontend
watch-frontend: ## Build frontend and watch for changes
source $(NVMSH) && npm run watch
@@ -65,7 +53,7 @@ generate-version-file: ## Generates the app version file
@echo -e "__git_commit__ = \"${GIT_COMMIT}\"\n__time__ = \"${DATE}\"" > ${APP_VERSION_FILE}
.PHONY: test
test: py-lint py-test js-test ## Run tests
test: py-lint py-test js-lint js-test ## Run tests
.PHONY: py-lint
py-lint: ## Run python linting scanners and black
@@ -74,13 +62,6 @@ py-lint: ## Run python linting scanners and black
poetry run flake8 .
poetry run isort --check-only ./app ./tests
.PHONY: tada
tada: ## Run python linting scanners and black
poetry run isort ./app ./tests
poetry run black .
poetry run flake8 .
.PHONY: avg-complexity
avg-complexity:
echo "*** Shows average complexity in radon of all code ***"
@@ -95,18 +76,18 @@ too-complex:
py-test: export NEW_RELIC_ENVIRONMENT=test
py-test: ## Run python unit tests
poetry run coverage run -m pytest --maxfail=10 --ignore=tests/end_to_end tests/
poetry run coverage report --fail-under=93
poetry run coverage report --fail-under=96
poetry run coverage html -d .coverage_cache
.PHONY: dead-code
dead-code: ## 60% is our aspirational goal, but currently breaks the build
poetry run vulture ./app ./notifications_utils --min-confidence=100
.PHONY: e2e-test
e2e-test: export NEW_RELIC_ENVIRONMENT=test
e2e-test: ## Run end-to-end integration tests; note that --browser webkit isn't currently working
@echo "Running E2E tests in path: $${TESTPATH:-tests/end_to_end}"
@bash -c 'DEBUG=pw:api,pw:browser poetry run pytest -vv --browser chromium --browser firefox "$${TESTPATH:-tests/end_to_end}"'
DEBUG=pw:api,pw:browser poetry run pytest -vv --browser chromium --browser firefox tests/end_to_end
.PHONY: js-lint
js-lint: ## Run javascript linting scanners
@@ -127,7 +108,7 @@ py-lock: ## Syncs dependencies and updates lock file without performing recursiv
.PHONY: freeze-requirements
freeze-requirements: ## create static requirements.txt
poetry export --output requirements.txt
poetry export --without-hashes --format=requirements.txt > requirements.txt
.PHONY: pip-audit
pip-audit:
@@ -174,8 +155,3 @@ upload-static:
# @cf map-route notify-admin ${DNS_NAME} --hostname www
# @cf unmap-route notify-admin-failwhale ${DNS_NAME} --hostname www
# @echo "Failwhale is disabled"
.PHONY: test-single
test-single: export NEW_RELIC_ENVIRONMENT=test
test-single: ## Run a single test file
poetry run pytest $(TEST_FILE)

View File

@@ -31,7 +31,7 @@ You will need the following items:
[setting up an account](https://cloud.gov/sign-up/) (requires a `.mil`,
`.gov`, or `.fed.us` email address) and getting access to the
`notify-local-dev` and `notify-staging` spaces.
- Admin privileges and SSH access on your machine; you may need to work with
- Admin priviliges and SSH access on your machine; you may need to work with
your organization's IT support staff if you're not sure or don't currently
have this access.
@@ -308,22 +308,6 @@ you'll be set with an upgraded version of Python.
_If you're not sure about the details of your current virtual environment, you can run `poetry env info` to get more information. If you've been using `pyenv` for everything, you can also see all available virtual environments with `pyenv virtualenvs`._
#### Poetry upgrades ####
If you are doing a new project setup, then after you install poetry you need to install the export plugin
```sh
poetry self add poetry-plugin-export
```
If you are upgrading from poetry 1.8.5, you need to do this:
```sh
curl -sSL https://install.python-poetry.org | python3 - --version 2.1.3
poetry self add poetry-export-plugin
```
#### Updating the .env file for Login.gov
To configure the application for Login.gov, you will need to update the following environment variables in the .env file:

View File

@@ -1,6 +1,5 @@
import os
import pathlib
import re
import secrets
from functools import partial
from time import monotonic
@@ -109,7 +108,6 @@ from app.notify_client.template_statistics_api_client import template_statistics
from app.notify_client.upload_api_client import upload_api_client
from app.notify_client.user_api_client import user_api_client
from app.url_converters import SimpleDateTypeConverter, TemplateTypeConverter
from app.utils.api_health import is_api_down
from app.utils.govuk_frontend_jinja.flask_ext import init_govuk_frontend
from notifications_utils import logging, request_helper
from notifications_utils.formatters import (
@@ -141,15 +139,11 @@ navigation = {
def _csp(config):
asset_domain = config["ASSET_DOMAIN"]
logo_domain = config["LOGO_CDN_DOMAIN"]
api_public_url = config["API_PUBLIC_URL"]
api_public_ws_url = config["API_PUBLIC_WS_URL"]
return {
"default-src": ["'self'", asset_domain],
"frame-src": [
"https://www.youtube.com",
"https://www.youtube-nocookie.com",
"https://www.googletagmanager.com",
],
"frame-ancestors": "'none'",
"form-action": "'self'",
@@ -162,14 +156,11 @@ def _csp(config):
"https://www.googletagmanager.com",
"https://www.google-analytics.com",
"https://dap.digitalgov.gov",
"https://cdn.socket.io",
],
"connect-src": [
"'self'",
"https://gov-bam.nr-data.net",
"https://www.google-analytics.com",
f"{api_public_url}",
f"{api_public_ws_url}",
],
"style-src": ["'self'", asset_domain],
"img-src": ["'self'", asset_domain, logo_domain],
@@ -177,25 +168,14 @@ def _csp(config):
def create_app(application):
@application.after_request
def add_csp_header(response):
existing_csp = response.headers.get("Content-Security-Policy", "")
response.headers["Content-Security-Policy"] = (
existing_csp + "; form-action 'self';"
)
return response
@application.context_processor
def inject_feature_flags():
# this is where feature flags can be easily added as a dictionary within context
feature_socket_enabled = application.config.get("FEATURE_SOCKET_ENABLED", False)
return dict(
FEATURE_SOCKET_ENABLED=feature_socket_enabled,
feature_about_page_enabled = application.config.get(
"FEATURE_ABOUT_PAGE_ENABLED", False
)
return dict(
FEATURE_ABOUT_PAGE_ENABLED=feature_about_page_enabled,
)
@application.context_processor
def inject_is_api_down():
return {"is_api_down": is_api_down()}
@application.context_processor
def inject_initial_signin_url():
@@ -636,8 +616,6 @@ def setup_event_handlers():
def add_template_filters(application):
application.add_template_filter(slugify)
for fn in [
format_auth_type,
format_billions,
@@ -695,10 +673,3 @@ def init_jinja(application):
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
application.jinja_loader = jinja_loader
def slugify(text):
"""
Converts text to lowercase, replaces spaces with hyphens, and removes invalid characters.
"""
return re.sub(r"[^a-z0-9-]", "", re.sub(r"\s+", "-", text.lower()))

View File

@@ -1 +0,0 @@
<svg id="Capa_1" enable-background="new 0 0 512 512" height="512" viewBox="0 0 512 512" width="512" xmlns="http://www.w3.org/2000/svg"><g><g><path d="m468.547 144.82h-63.047v-121.32c0-12.958-10.542-23.5-23.5-23.5h-324c-12.958 0-23.5 10.542-23.5 23.5v84.833c.344 9.931 14.659 9.923 15 0v-33.333h341v69.82h-121.998c-14.312 0-25.954 11.574-25.954 25.8v83.174l-28.866 19.221c-5.511 3.444-5.51 12.168.001 15.611l28.865 19.22v83.174c0 14.226 11.643 25.799 25.954 25.799h121.998v71.68c0 4.687-3.813 8.5-8.5 8.5h-324c-4.687 0-8.5-3.813-8.5-8.5v-20h131.5c7.444 0 13.5-6.056 13.5-13.5v-127.999c0-7.444-6.056-13.5-13.5-13.5h-131.5v-168.021c-.344-9.931-14.659-9.923-15 0v168.021h-3.5c-7.444 0-13.5 6.056-13.5 13.5v128c0 7.444 6.056 13.5 13.5 13.5h3.5v20c0 12.958 10.542 23.5 23.5 23.5h324c12.958 0 23.5-10.542 23.5-23.5v-71.68h11.5c9.931-.344 9.923-14.659 0-15h-148.498c-6.04 0-10.954-4.845-10.954-10.799v-85.173c0-3.779-1.882-7.288-5.031-9.384l-23.492-15.643 23.492-15.644c3.15-2.098 5.031-5.606 5.031-9.384v-85.173c0-5.955 4.914-10.8 10.954-10.8h200.045c6.04 0 10.953 4.845 10.953 10.8v220.401c0 5.955-4.913 10.799-10.953 10.799h-16.436c-9.931.344-9.923 14.659 0 15h16.436c14.311 0 25.953-11.574 25.953-25.799v-220.401c0-14.226-11.643-25.8-25.953-25.8zm-256.047-129.82v9.5c-.353 9.929-14.65 9.922-15 0v-9.5zm-55.333 0v9.5c-.353 9.929-14.65 9.922-15 0v-9.5zm-55.334 0v9.5c-.353 9.929-14.65 9.922-15 0v-9.5zm-52.333 45v-36.5c0-4.687 3.813-8.5 8.5-8.5h13.833v9.5c1.135 29.816 43.876 29.793 45 0v-9.5h10.334v9.5c1.135 29.816 43.876 29.793 45 0v-9.5h10.333v9.5c1.135 29.816 43.876 29.793 45 0v-9.5h154.5c4.687 0 8.5 3.813 8.5 8.5v36.5zm-17 268.5h147v125h-147z"/><path d="m451.356 344.514c2.439-4.507 2.214-9.973-.589-14.264l-69.093-105.771c-5.242-8.361-18.107-8.359-23.35 0l-69.092 105.771c-2.803 4.291-3.028 9.756-.589 14.263s7.139 7.307 12.264 7.307h138.186c5.125 0 9.824-2.799 12.263-7.306zm-148.499-7.694 67.143-102.786 67.143 102.786z"/><path d="m362.5 266.32v31.445c.344 9.931 14.659 9.923 15 0v-31.445c-.344-9.931-14.659-9.923-15 0z"/><path d="m370 310.82c-4.143 0-7.5 3.358-7.5 7.5v2.5c.344 9.931 14.659 9.923 15 0v-2.5c0-4.142-3.357-7.5-7.5-7.5z"/><path d="m91.375 123.094h36.375c9.931-.344 9.923-14.659 0-15h-36.375c-9.931.344-9.923 14.66 0 15z"/><path d="m91.375 149.316h90c9.931-.344 9.923-14.659 0-15h-90c-9.931.344-9.923 14.66 0 15z"/><path d="m91.375 175.539h77.625c9.931-.344 9.923-14.659 0-15h-77.625c-9.931.344-9.923 14.659 0 15z"/><path d="m91.375 225.76h36.375c9.931-.344 9.923-14.659 0-15h-36.375c-9.931.344-9.923 14.66 0 15z"/><path d="m91.375 251.982h90c9.931-.344 9.923-14.659 0-15h-90c-9.931.344-9.923 14.66 0 15z"/><path d="m91.375 278.205h77.625c9.931-.344 9.923-14.659 0-15h-77.625c-9.931.344-9.923 14.659 0 15z"/><path d="m139.354 356.038c-2.93-2.929-7.678-2.929-10.607 0l-22.747 22.747-22.747-22.747c-2.93-2.929-7.678-2.929-10.607 0s-2.929 7.678 0 10.606l22.748 22.748-22.748 22.748c-2.929 2.929-2.929 7.678 0 10.606 2.93 2.929 7.677 2.929 10.607 0l22.747-22.747 22.747 22.747c2.93 2.929 7.677 2.929 10.607 0 2.929-2.929 2.929-7.678 0-10.606l-22.748-22.748 22.748-22.748c2.929-2.928 2.929-7.677 0-10.606z"/></g></g></svg>

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@@ -1,17 +0,0 @@
<svg width="305" height="304" viewBox="0 0 381 380" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M163.41 47.1289H32.7852C14.983 47.1289 0.5 61.6119 0.5 79.414V293.793C0.755313 301.164 11.3797 301.158 11.6328 293.793V79.414C11.6328 67.7506 21.1217 58.2617 32.7852 58.2617H163.41C175.074 58.2617 184.562 67.7506 184.562 79.414V335.84H11.6328V319.851C11.3775 312.481 0.753086 312.487 0.5 319.851V346.601C0.5 364.403 14.983 378.887 32.7852 378.887H163.41C181.212 378.887 195.695 364.403 195.695 346.601V79.414C195.695 61.6119 181.212 47.1289 163.41 47.1289ZM163.41 367.754H32.7852C21.2464 367.754 11.8414 358.464 11.6425 346.972H184.554C184.354 358.464 174.949 367.754 163.41 367.754Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M72.8629 102.793H123.332C145.461 101.951 145.444 70.2287 123.332 69.3945H72.8629C50.7338 70.2362 50.7509 101.959 72.8629 102.793ZM72.8629 80.5273H123.332C130.701 80.7893 130.696 91.4004 123.332 91.6601H72.8629C65.4937 91.3981 65.4989 80.7871 72.8629 80.5273Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M41.6899 265.26V303.853C41.6899 308.56 45.5189 312.389 50.2251 312.389H145.225C149.931 312.389 153.76 308.56 153.76 303.853V265.26C153.76 260.554 149.931 256.725 145.225 256.725H50.2251C45.5181 256.725 41.6899 260.554 41.6899 265.26ZM52.8228 267.857H142.627V301.256H52.8228V267.857Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M374.934 50.0976C378.008 50.0976 380.5 47.6054 380.5 44.5312V21.4203C380.5 9.60909 370.835 0 358.955 0H258.626C246.746 0 237.081 9.60909 237.081 21.4203V99.174L211.672 116.104C207.446 118.746 207.447 125.434 211.673 128.076L237.081 145.005V195.298C237.081 207.109 246.746 216.718 258.626 216.718H358.955C370.835 216.719 380.5 207.109 380.5 195.298V71.9098C380.245 64.5391 369.62 64.545 369.367 71.9098V195.298C369.367 200.971 364.697 205.586 358.955 205.586H258.626C252.885 205.586 248.214 200.971 248.214 195.298V143.773C248.214 140.812 246.74 138.063 244.272 136.418L222.766 122.09L244.272 107.761C246.741 106.116 248.214 103.367 248.214 100.407V21.4203C248.214 15.7477 252.885 11.1328 258.626 11.1328H358.955C364.697 11.1328 369.367 15.7477 369.367 21.4203V44.5312C369.367 47.6054 371.86 50.0976 374.934 50.0976Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M279.025 44.4072H313.172C320.542 44.1519 320.537 33.5275 313.172 33.2744H279.025C271.655 33.5305 271.66 44.1549 279.025 44.4072Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M279.025 116.647H313.172C320.542 116.392 320.537 105.768 313.172 105.515H279.025C271.655 105.77 271.66 116.394 279.025 116.647Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M279.025 62.4678H336.689C344.059 62.2125 344.054 51.588 336.689 51.335H279.025C271.655 51.5903 271.66 62.2147 279.025 62.4678Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M279.025 80.5273H336.689C344.059 80.272 344.054 69.6476 336.689 69.3945H279.025C271.655 69.6498 271.66 80.2743 279.025 80.5273Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M98.0967 205.319C108.123 205.319 116.28 197.161 116.28 187.135C115.366 163.045 80.8237 163.052 79.9131 187.135C79.9131 197.161 88.0705 205.319 98.0967 205.319ZM98.0967 180.084C101.984 180.084 105.147 183.248 105.147 187.135C104.793 196.476 91.3992 196.473 91.0459 187.135C91.0459 183.247 94.2091 180.084 98.0967 180.084Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M49.0186 181.389C49.7927 183.69 51.1932 185.667 53.0569 187.135C51.1932 188.603 49.7935 190.58 49.0186 192.88C47.9662 196.005 48.1948 199.354 49.6621 202.308L56.7158 216.509C59.7425 222.603 67.1644 225.101 73.2592 222.078L77.814 219.82V224.885C77.814 231.693 83.3529 237.233 90.1618 237.233H106.039C112.844 237.233 118.38 231.697 118.38 224.891V219.82L122.935 222.078C129.032 225.101 136.452 222.603 139.479 216.509L146.533 202.305C148 199.352 148.229 196.004 147.177 192.879C146.403 190.578 145.001 188.601 143.138 187.134C147.636 183.694 149.157 177.013 146.532 171.96L139.48 157.763C136.453 151.668 129.029 149.168 122.932 152.192L118.38 154.449V149.378C118.38 142.573 112.844 137.036 106.039 137.036H90.1618C83.3537 137.036 77.814 142.575 77.814 149.384V154.449L73.2622 152.192C67.1651 149.168 59.7417 151.667 56.7144 157.762L49.6621 171.96C48.1948 174.916 47.9662 178.264 49.0186 181.389ZM59.6319 176.914L66.6842 162.717C66.9825 162.115 67.7151 161.867 68.3162 162.167L78.764 167.347C80.9646 168.437 83.5259 168.316 85.6129 167.021C87.7007 165.726 88.9468 163.486 88.9468 161.03V149.385C88.9468 148.715 89.4916 148.17 90.1618 148.17H106.039C106.705 148.17 107.247 148.712 107.247 149.379V161.03C107.247 163.486 108.493 165.726 110.581 167.021C112.668 168.316 115.228 168.439 117.43 167.346L127.878 162.166C128.48 161.868 129.211 162.115 129.51 162.716L136.563 176.913C136.747 177.284 136.698 177.62 136.626 177.836C136.553 178.053 136.388 178.349 136.016 178.533L131.411 180.817C126.23 183.267 126.231 191.002 131.411 193.451L136.019 195.736C136.39 195.92 136.554 196.215 136.626 196.431C136.699 196.647 136.747 196.982 136.563 197.351L129.509 211.555C129.211 212.154 128.48 212.401 127.881 212.103L117.43 206.921C115.229 205.83 112.668 205.952 110.582 207.247C108.494 208.542 107.248 210.782 107.248 213.239V224.89C107.248 225.556 106.706 226.099 106.039 226.099H90.1625C89.4931 226.099 88.9476 225.554 88.9476 224.884V213.239C88.9476 210.782 87.7014 208.542 85.6137 207.247C83.5229 205.95 80.9601 205.832 78.764 206.922L68.3133 212.104C67.7121 212.401 66.9833 212.155 66.6864 211.556L59.6326 197.356C59.4486 196.985 59.4968 196.649 59.5696 196.432C59.6423 196.215 59.807 195.919 60.1781 195.735L64.7842 193.451C69.9654 191.001 69.9639 183.266 64.7842 180.818L60.1789 178.534C59.8078 178.35 59.643 178.053 59.5703 177.837C59.4968 177.62 59.4486 177.285 59.6319 176.914Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M363.426 257.783H235.796C226.382 257.783 218.723 265.442 218.723 274.856V362.927C218.723 372.341 226.383 380 235.796 380H363.426C372.841 380 380.499 372.341 380.499 362.927V274.856C380.499 265.442 372.841 257.783 363.426 257.783ZM369.366 362.927C369.366 366.203 366.702 368.867 363.426 368.867H235.796C232.52 368.867 229.856 366.203 229.856 362.927V274.856C229.856 271.58 232.521 268.916 235.796 268.916H363.426C366.702 268.916 369.366 271.58 369.366 274.856V362.927Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M268.272 141.779V181.381C268.272 185.809 271.875 189.412 276.304 189.412H340.926C345.354 189.412 348.956 185.809 348.956 181.381V141.779C348.956 137.351 345.354 133.749 340.926 133.749H276.304C271.875 133.748 268.272 137.35 268.272 141.779ZM279.405 144.881H337.824V178.279H279.405V144.881Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M273.174 297.591C271.206 295.229 267.695 294.909 265.334 296.878L241.975 316.344C239.33 318.441 239.331 322.8 241.975 324.897L265.334 344.364C266.375 345.23 267.638 345.654 268.895 345.653C270.489 345.653 272.073 344.971 273.174 343.65C275.142 341.289 274.823 337.779 272.462 335.811L254.233 320.62L272.462 305.431C274.823 303.462 275.142 299.953 273.174 297.591Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M357.249 316.344L333.889 296.878C331.527 294.91 328.018 295.229 326.049 297.59C324.081 299.952 324.4 303.462 326.762 305.43L344.99 320.62L326.762 335.81C324.4 337.778 324.081 341.288 326.049 343.65C328.026 346.021 331.541 346.322 333.889 344.362L357.249 324.895C359.893 322.799 359.892 318.441 357.249 316.344Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
<path d="M314.73 284.336C311.892 283.154 308.634 284.495 307.451 287.333L281.496 349.626C280.314 352.464 281.656 355.723 284.493 356.905C287.26 358.079 290.59 356.775 291.772 353.908L317.727 291.616C318.91 288.778 317.569 285.519 314.73 284.336Z" fill="#005EA2" stroke="#DFE1E2" stroke-width="2"/>
</svg>

Before

Width:  |  Height:  |  Size: 7.7 KiB

View File

@@ -1,14 +1,10 @@
(function (window) {
if (document.getElementById('activityChartContainer')) {
let currentType = 'service';
const tableContainer = document.getElementById('activityContainer');
const currentUserName = tableContainer.getAttribute('data-currentUserName');
const currentServiceId = tableContainer.getAttribute('data-currentServiceId');
const COLORS = {
delivered: '#0076d6',
failed: '#fa9441',
pending: '#C7CACE',
text: '#666'
};
@@ -16,7 +12,7 @@
const FONT_WEIGHT = 'bold';
const MAX_Y = 120;
const createChart = function(containerId, labels, deliveredData, failedData, pendingData) {
const createChart = function(containerId, labels, deliveredData, failedData) {
const container = d3.select(containerId);
container.selectAll('*').remove(); // Clear any existing content
@@ -39,7 +35,7 @@
}
// Calculate total messages
const totalMessages = d3.sum(deliveredData) + d3.sum(failedData) + d3.sum(pendingData);
const totalMessages = d3.sum(deliveredData) + d3.sum(failedData);
// Create legend only if there are messages
const legendContainer = d3.select('.chart-legend');
@@ -49,8 +45,7 @@
// Show legend if there are messages
const legendData = [
{ label: 'Delivered', color: COLORS.delivered },
{ label: 'Failed', color: COLORS.failed },
{ label: 'Pending', color: COLORS.pending }
{ label: 'Failed', color: COLORS.failed }
];
const legendItem = legendContainer.selectAll('.legend-item')
@@ -81,9 +76,8 @@
.range([0, width])
.padding(0.1);
// Adjust the y-axis domain to add some space above the tallest bar
const maxY = d3.max(deliveredData.map((d, i) => d + (failedData[i] || 0) + (pendingData[i] || 0)));
const y = d3.scaleSymlog()
const maxY = d3.max(deliveredData.map((d, i) => d + (failedData[i] || 0)));
const y = d3.scaleSqrt()
.domain([0, maxY + 2]) // Add 2 units of space at the top
.nice()
.range([height, 0]);
@@ -95,7 +89,7 @@
// Generate the y-axis with whole numbers
const yAxis = d3.axisLeft(y)
.ticks(Math.min(maxY + 2, 3))
.ticks(Math.min(maxY + 2, 10)) // Generate up to 10 ticks based on the data
.tickFormat(d3.format('d')); // Ensure whole numbers on the y-axis
svg.append('g')
@@ -106,13 +100,12 @@
const stackData = labels.map((label, i) => ({
label: label,
delivered: deliveredData[i],
failed: failedData[i] || 0,
pending: pendingData[i] || 0
failed: failedData[i] || 0 // Ensure there's a value for failed, even if it's 0
}));
// Stack the data
const stack = d3.stack()
.keys(['delivered', 'failed', 'pending'])
.keys(['delivered', 'failed'])
.order(d3.stackOrderNone)
.offset(d3.stackOffsetNone);
@@ -120,8 +113,8 @@
// Color scale
const color = d3.scaleOrdinal()
.domain(['delivered', 'failed', 'pending'])
.range([COLORS.delivered, COLORS.failed, COLORS.pending]);
.domain(['delivered', 'failed'])
.range([COLORS.delivered, COLORS.failed]);
// Create bars with animation
const barGroups = svg.selectAll('.bar-group')
@@ -130,12 +123,11 @@
.append('g')
.attr('class', 'bar-group')
.attr('fill', d => color(d.key));
const minBarHeight = 5;
barGroups.selectAll('rect')
.data(d => d)
.enter()
.append('rect')
.filter(d => d[1] - d[0] > 0)
.attr('x', d => x(d.data.label))
.attr('y', height)
.attr('height', 0)
@@ -156,13 +148,11 @@
.transition()
.duration(1000)
.attr('y', d => y(d[1]))
.attr('height', d => {
const calculatedHeight = y(d[0]) - y(d[1]);
return calculatedHeight < minBarHeight ? minBarHeight : calculatedHeight;
}); };
.attr('height', d => y(d[0]) - y(d[1]));
};
// Function to create an accessible table
const createTable = function(tableId, chartType, labels, deliveredData, failedData, pendingData) {
const createTable = function(tableId, chartType, labels, deliveredData, failedData) {
const table = document.getElementById(tableId);
table.innerHTML = ""; // Clear previous data
@@ -174,7 +164,7 @@
// Create table header
const headerRow = document.createElement('tr');
const headers = ['Day', 'Delivered', 'Failed', 'Pending'];
const headers = ['Day', 'Delivered', 'Failed'];
headers.forEach(headerText => {
const th = document.createElement('th');
th.textContent = headerText;
@@ -197,10 +187,6 @@
cellFailed.textContent = failedData[index];
row.appendChild(cellFailed);
const cellPending = document.createElement('td');
cellPending.textContent = pendingData[index];
row.appendChild(cellPending);
tbody.appendChild(row);
});
@@ -210,19 +196,12 @@
};
const fetchData = function(type) {
var ctx = document.getElementById('weeklyChart');
if (!ctx) {
return;
}
var userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var url = type === 'service'
? `/services/${currentServiceId}/daily-stats.json?timezone=${encodeURIComponent(userTimezone)}`
: `/services/${currentServiceId}/daily-stats-by-user.json?timezone=${encodeURIComponent(userTimezone)}`;
var url = type === 'service' ? `/daily_stats.json` : `/daily_stats_by_user.json`;
return fetch(url)
.then(response => {
if (!response.ok) {
@@ -234,7 +213,7 @@
labels = [];
deliveredData = [];
failedData = [];
pendingData = [];
let totalMessages = 0;
for (var dateString in data) {
@@ -245,8 +224,9 @@
labels.push(formattedDate);
deliveredData.push(data[dateString].sms.delivered);
failedData.push(data[dateString].sms.failure);
pendingData.push(data[dateString].sms.pending || 0);
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure + data[dateString].sms.pending;
// Calculate the total number of messages
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure;
}
}
@@ -272,18 +252,17 @@
}
} else {
// If there are messages, create the chart and table
createChart('#weeklyChart', labels, deliveredData, failedData, pendingData);
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData, pendingData);
}
createChart('#weeklyChart', labels, deliveredData, failedData);
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData);
}
return data;
})
.catch(error => console.error('Error fetching daily stats:', error));
};
return data;
})
.catch(error => console.error('Error fetching daily stats:', error));
};
setInterval(() => fetchData(currentType), 25000);
const handleDropdownChange = function(event) {
const selectedValue = event.target.value;
currentType = selectedValue;
const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`);
const selectElement = document.getElementById('options');
const selectedText = selectElement.options[selectElement.selectedIndex].text;
@@ -291,67 +270,36 @@
subTitle.textContent = `${selectedText} - last 7 days`;
fetchData(selectedValue);
// Update ARIA live region
const liveRegion = document.getElementById('aria-live-account');
liveRegion.textContent = `Data updated for ${selectedText} - last 7 days`;
const tableHeading = document.querySelector('#tableActivity h2');
const senderColumns = document.querySelectorAll('.sender-column');
const allRows = document.querySelectorAll('#activity-table tbody tr');
const caption = document.querySelector('#activity-table caption');
if (selectedValue === 'individual') {
tableHeading.textContent = 'My activity';
caption.textContent = `Table showing the sent jobs for ${currentUserName}`;
senderColumns.forEach(col => {
col.style.display = 'none';
});
allRows.forEach(row => row.style.display = 'none');
const userRows = Array.from(allRows).filter(row => {
const senderCell = row.querySelector('.sender-column');
const rowSender = senderCell ? senderCell.textContent.trim() : '';
return rowSender === currentUserName;
});
userRows.slice(0, 5).forEach(row => {
row.style.display = '';
});
} else {
tableHeading.textContent = 'Service activity';
caption.textContent = `Table showing the sent jobs for service`;
senderColumns.forEach(col => {
col.style.display = '';
});
allRows.forEach((row, index) => {
row.style.display = (index < 5) ? '' : 'none';
});
}
// Switch tables based on dropdown selection
const selectedTable = selectedValue === "individual" ? "table1" : "table2";
const tables = document.querySelectorAll('.table-overflow-x-auto');
tables.forEach(function(table) {
table.classList.add('hidden'); // Hide all tables by adding the hidden class
table.classList.remove('visible'); // Ensure they are not visible
});
const tableToShow = document.getElementById(selectedTable);
tableToShow.classList.remove('hidden'); // Remove hidden class
tableToShow.classList.add('visible'); // Add visible class
};
document.addEventListener('DOMContentLoaded', function() {
// Initialize activityChart chart and table with service data by default
fetchData(currentType);
const allRows = Array.from(document.querySelectorAll('#activity-table tbody tr'));
allRows.forEach((row, index) => {
row.style.display = (index < 5) ? '' : 'none';
});
fetchData('service');
// Add event listener to the dropdown
const dropdown = document.getElementById('options');
dropdown.addEventListener('change', handleDropdownChange);
});
// Resize chart on window resize
window.addEventListener('resize', function() {
if (labels.length > 0 && deliveredData.length > 0 && failedData.length > 0 && pendingData.length > 0) {
createChart('#weeklyChart', labels, deliveredData, failedData, pendingData);
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData, pendingData);
if (labels.length > 0 && deliveredData.length > 0 && failedData.length > 0) {
createChart('#weeklyChart', labels, deliveredData, failedData);
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData);
}
});

View File

@@ -0,0 +1,27 @@
(function(Modules) {
"use strict";
Modules.Autofocus = function() {
this.start = function(component) {
var $component = $(component),
forceFocus = $component.data('forceFocus');
// if the page loads with a scroll position, we can't assume the item to focus onload
// is still where users intend to start
if (($(window).scrollTop() > 0) && !forceFocus) { return; }
// See if the component itself is something we want to send focus to
var target = $component.filter('input, textarea, select');
// Otherwise look inside the component to see if there are any elements
// we want to send focus to
if (target.length === 0) {
target = $('input, textarea, select', $component);
}
target.eq(0).trigger('focus');
};
};
})(window.GOVUK.Modules);

View File

@@ -0,0 +1,29 @@
(function(Modules) {
"use strict";
let isSixDigitHex = value => value.match(/^#[0-9A-F]{6}$/i);
let colourOrWhite = value => isSixDigitHex(value) ? value : '#FFFFFF';
Modules.ColourPreview = function() {
this.start = component => {
this.$input = $(component);
this.$input.closest('.usa-form-group').append(
this.$preview = $('<span class="textbox-colour-preview"></span>')
);
this.$input
.on('input', this.update)
.trigger('input');
};
this.update = () => this.$preview.css(
'background', colourOrWhite(this.$input.val())
);
};
})(window.GOVUK.Modules);

View File

@@ -1,69 +1,34 @@
function announceUploadStatusFromElement() {
const srRegion = document.getElementById('upload-status-live');
const success = document.getElementById('upload-success');
const error = document.getElementById('upload-error');
if (!srRegion) return;
const message = error?.textContent || success?.textContent;
if (message) {
srRegion.textContent = '';
setTimeout(() => {
srRegion.textContent = message + '\u00A0'; // add a non-breaking space
srRegion.focus(); // Optional
}, 300);
}
}
// Exported for use in tests
function initUploadStatusAnnouncer() {
document.addEventListener('DOMContentLoaded', () => {
announceUploadStatusFromElement();
});
}
(function(Modules) {
"use strict";
Modules.FileUpload = function() {
this.submit = () => this.$form.trigger('submit');
this.showCancelButton = () => {
$('.file-upload-button', this.$form).replaceWith(`
<button class='usa-button uploading-button' aria-disabled="true" tabindex="0">
Uploading<span class="dot-anim" aria-hidden="true"></span>
</button>
`);
};
this.showCancelButton = () => $('.file-upload-button', this.$form).replaceWith(`
<a href="" class='usa-button usa-button--secondary'>Cancel upload</a>
`);
this.start = function(component) {
this.$form = $(component);
this.$form.on('click', '[data-module="upload-trigger"]', function () {
const inputId = $(this).data('file-input-id');
const fileInput = document.getElementById(inputId);
if (fileInput) fileInput.click();
});
// The label gets styled like a button and is used to hide the native file upload control. This is so that
// users see a button that looks like the others on the site.
this.$form.find('label.file-upload-button').addClass('usa-button margin-bottom-1').attr( {role: 'button', tabindex: '0'} );
// Clear the form if the user navigates back to the page
$(window).on("pageshow", () => this.$form[0].reset());
this.$form.on('change', '.file-upload-field', () => {
this.submit();
this.showCancelButton();
});
// Need to put the event on the container, not the input for it to work properly
this.$form.on(
'change', '.file-upload-field',
() => this.submit() && this.showCancelButton()
);
};
};
})(window.GOVUK.Modules);
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
announceUploadStatusFromElement,
initUploadStatusAnnouncer
};
}
if (typeof window !== 'undefined') {
initUploadStatusAnnouncer();
}

View File

@@ -22,6 +22,7 @@
this.$scrollableTable
.on('scroll', this.toggleShadows)
.on('scroll', this.maintainHeight)
.on('focus blur', () => this.$component.toggleClass('js-focus-style'));
if (
window.GOVUK.stickAtBottomWhenScrolling &&
@@ -36,11 +37,11 @@
this.insertShims = () => {
const attributesForFocus = 'role aria-labelledby';
const attributesForFocus = 'role aria-labelledby tabindex';
let captionId = this.$table.find('caption').text().toLowerCase().replace(/[^A-Za-z]+/g, '');
this.$table.find('caption').attr('id', captionId);
this.$table.wrap(`<div class="fullscreen-scrollable-table" role="region" aria-labelledby="${captionId}"/>`);
this.$table.wrap(`<div class="fullscreen-scrollable-table" role="region" aria-labelledby="${captionId}" tabindex="0"/>`);
this.$component
.append(

View File

@@ -0,0 +1,24 @@
(function(window) {
"use strict";
window.GOVUK.Modules.Homepage = function() {
this.start = function(component) {
let $component = $(component);
let iterations = 0;
let timeout = null;
$component.on('click', () => {
if (++iterations == 5) {
$component.toggleClass('product-page-intro-wrapper--alternative');
}
clearTimeout(timeout);
timeout = setTimeout(() => iterations = 0, 1500);
});
};
};
})(window);

View File

@@ -15,11 +15,11 @@
let query = normalize($searchBox.val());
let results = 0;
let $noResultsMessage = $('.js-live-search-no-results');
$targets.each(function() {
let content = $('.live-search-relevant', this).text() || $(this).text();
let isMatch = normalize(content).indexOf(normalize(query)) > -1;
if ($(this).has(':checked').length) {
$(this).show();
@@ -28,27 +28,17 @@
}
if (query == '') {
$(this).removeClass('js-hidden');
$(this).css('display', '');
results++;
return;
}
let isMatch = normalize(content).includes(normalize(query));
$(this).toggle(isMatch);
if (isMatch) { results++; }
if (isMatch) {
$(this).removeClass('js-hidden');
results++;
} else {
$(this).addClass('js-hidden');
}
});
if (query !== '' && results === 0) {
$noResultsMessage.removeClass('js-hidden');
} else {
$noResultsMessage.addClass('js-hidden');
}
if (state === 'loaded') {
if (query !== '') {
$searchBox.attr('aria-label', $searchLabel.text().trim() + ', ' + resultsSummary(results));

View File

@@ -1,5 +1,7 @@
window.GOVUK.Frontend.initAll();
$(() => $("time.timeago").timeago());
var showHideContent = new GOVUK.ShowHideContent();
showHideContent.init();

View File

@@ -1,100 +0,0 @@
let activeModal = null;
let lastFocusedElement = null;
function openModal(modalId) {
const wrapper = document.getElementById(modalId);
if (!wrapper) return;
const modal = wrapper.querySelector('.usa-modal, dialog');
if (!modal) return;
lastFocusedElement = document.activeElement;
wrapper.classList.remove('is-hidden');
modal.removeAttribute('aria-hidden');
modal.removeAttribute('inert');
modal.removeAttribute('hidden');
document.body.classList.add('modal-open');
// Set focus to the first focusable element inside modal
const focusTarget = modal.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
if (focusTarget) focusTarget.focus();
modal.addEventListener('keydown', function(e) {
if (e.key !== 'Tab') return;
const focusableElements = modal.querySelectorAll(
'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"])'
);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
if (e.shiftKey && document.activeElement === firstElement) {
e.preventDefault();
lastElement.focus();
} else if (!e.shiftKey && document.activeElement === lastElement) {
e.preventDefault();
firstElement.focus();
}
});
activeModal = wrapper;
}
function closeModal() {
if (!activeModal) return;
const modal = activeModal.querySelector('.usa-modal, dialog');
if (modal) {
modal.setAttribute('aria-hidden', 'true');
modal.setAttribute('inert', '');
modal.setAttribute('hidden', '');
}
activeModal.classList.add('is-hidden');
document.body.classList.remove('modal-open');
if (lastFocusedElement) lastFocusedElement.focus();
activeModal = null;
}
function attachModalTriggers() {
document.querySelectorAll('[data-open-modal]').forEach(btn => {
btn.addEventListener('click', () => {
const modalId = btn.getAttribute('data-open-modal');
openModal(modalId);
});
});
document.querySelectorAll('[data-close-modal]').forEach(btn => {
btn.addEventListener('click', () => {
closeModal();
});
});
}
// Escape key closes modal
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && activeModal) {
closeModal();
}
});
// Optional: click outside modal closes it
document.addEventListener('click', (e) => {
if (activeModal && e.target.classList.contains('usa-modal-overlay')) {
closeModal();
}
});
document.addEventListener('DOMContentLoaded', () => {
attachModalTriggers();
});
// ✅ Check if we're in a Node.js environment (for Jest) before using `module.exports`
if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
module.exports = { closeModal, openModal, attachModalTriggers };
}

View File

@@ -1,45 +1,30 @@
(function () {
(function() {
"use strict";
const disableSubmitButtons = function (event) {
const $submitButton = $(this).find(':submit');
let disableSubmitButtons = function(event) {
var $submitButton = $(this).find(':submit');
if ($submitButton.data('clicked') == 'true') {
if ($submitButton.data('clicked') === 'true') {
event.preventDefault();
return;
}
$submitButton.data('clicked', 'true');
// Add dot animation for Send/Schedule/Cancel buttons
const buttonName = $submitButton.attr('name')?.toLowerCase();
if (["send", "schedule", "cancel"].includes(buttonName)) {
$submitButton.prop('disabled', true);
// Inject dot animation span if not already present
if ($submitButton.find('.dot-anim').length === 0) {
$submitButton.append('<span class="dot-anim" aria-hidden="true"></span>');
}
// Disable Cancel button too
const $cancelButton = $('button[name]').filter(function () {
return $(this).attr('name')?.toLowerCase() === 'cancel';
});
$cancelButton.prop('disabled', true);
setTimeout(() => {
renableSubmitButton($submitButton);
}, 10000); // fallback safety
} else {
$submitButton.data('clicked', 'true');
setTimeout(renableSubmitButton($submitButton), 1500);
}
};
const renableSubmitButton = ($submitButton) => () => {
let renableSubmitButton = $submitButton => () => {
$submitButton.data('clicked', '');
$submitButton.prop('disabled', false);
$submitButton.find('.dot-anim').remove(); // clean up if needed
};
$('form').on('submit', disableSubmitButtons);
})();

View File

@@ -38,7 +38,7 @@
<label class="usa-radio__label" for="{{id}}">{{label}}</label>
</div>
{{/choices}}
<input type='button' class='usa-button usa-button--outline radio-select__button--done margin-top-4' aria-expanded='true' value='Back to select a new time' />
<input type='button' class='usa-button usa-button--outline radio-select__button--done' aria-expanded='true' value='Done' />
</div>
`),
'chosen': Hogan.compile(`

View File

@@ -1,83 +0,0 @@
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
document.addEventListener('DOMContentLoaded', function () {
const isJobPage = window.location.pathname.includes('/jobs/');
if (!isJobPage) return;
const jobEl = document.querySelector('[data-job-id]');
const jobId = jobEl?.dataset?.jobId;
const featureEnabled = jobEl?.dataset?.feature === 'true';
const apiHost = jobEl?.dataset?.host;
if (!jobId) return;
if (featureEnabled) {
const socket = io(apiHost);
socket.on('connect_error', (err) => {
console.error('Socket connect_error:', err);
});
socket.on('error', (err) => {
console.error('Socket error:', err);
});
socket.on('connect', () => {
socket.emit('join', { room: `job-${jobId}` });
});
window.addEventListener('beforeunload', () => {
socket.emit('leave', { room: `job-${jobId}` });
});
const debouncedUpdate = debounce((data) => {
updateAllJobSections();
}, 1000);
socket.on('job_updated', (data) => {
if (data.job_id !== jobId) return;
debouncedUpdate(data);
});
}
function updateAllJobSections() {
const resourceEl = document.querySelector('[data-socket-update="status"]');
const url = resourceEl?.dataset?.resource;
if (!url) {
console.warn('No resource URL found for job updates');
return;
}
fetch(url)
.then((res) => res.json())
.then(({ status, counts, notifications }) => {
const sections = {
status: document.querySelector('[data-socket-update="status"]'),
counts: document.querySelector('[data-socket-update="counts"]'),
notifications: document.querySelector(
'[data-socket-update="notifications"]'
),
};
if (status && sections.status) {
sections.status.innerHTML = status;
}
if (counts && sections.counts) {
sections.counts.innerHTML = counts;
}
if (notifications && sections.notifications) {
sections.notifications.innerHTML = notifications;
}
})
.catch((err) => {
console.error('Error fetching job update partials:', err);
});
}
});

View File

@@ -197,11 +197,6 @@
if (event.currentTarget.value === 'add-new-template' && this.$singleNotificationChannel) {
window.location = "/services/" + this.$singleChannelService + "/templates/add-" + this.$singleNotificationChannel;
} else {
if (this.currentState === 'add-new-template') {
this.$form.find('input[type=checkbox]').prop('checked', false);
this.selectionStatus.update({ total: 0, templates: 0, folders: 0 });
}
if (this.stateChanged()) {
this.render();
}
@@ -291,29 +286,7 @@
mode = 'dialog';
}
if (this.currentState === 'add-new-template') {
this.$form.find('.template-list-item').addClass('js-hidden');
$('.live-search').addClass('js-hidden');
$('#breadcrumb-template-folders').addClass('js-hidden');
$('#template-list').addClass('js-hidden');
this.$form.find('input[type=checkbox]').prop('checked', false);
this.selectionStatus.update({ total: 0, templates: 0, folders: 0 });
$('#page-title').text('New Template');
$('#page-description').text('Every message starts with a template. Choose to start with a blank template or copy an existing template.');
document.title = 'New Templates';
} else {
this.$form.find('.template-list-item').removeClass('js-hidden');
$('.live-search').removeClass('js-hidden');
$('#breadcrumb-template-folders').removeClass('js-hidden');
$('#template-list').removeClass('js-hidden');
$('#page-title').text('Select or create a template');
$('#page-description').text('Every message starts with a template. To send, choose or create a template.');
document.title = 'Select or create a template';
}
if (currentStateObj && 'setFocus' in currentStateObj) {
if (currentStateObj && ('setFocus' in currentStateObj)) {
scrollTop = $(window).scrollTop();
currentStateObj.setFocus();
$(window).scrollTop(scrollTop);

View File

@@ -6,17 +6,17 @@
var chartTitle = document.getElementById('chartTitle').textContent;
// Access data attributes from the HTML
var messagesSent = parseInt(chartContainer.getAttribute('data-messages-sent'));
var messagesRemaining = parseInt(chartContainer.getAttribute('data-messages-remaining'));
var totalMessages = messagesSent + messagesRemaining;
var sms_sent = parseInt(chartContainer.getAttribute('data-sms-sent'));
var sms_remaining_messages = parseInt(chartContainer.getAttribute('data-sms-allowance-remaining'));
var totalMessages = sms_sent + sms_remaining_messages;
// Update the message below the chart
document.getElementById('message').innerText = `${messagesSent.toLocaleString()} sent / ${messagesRemaining.toLocaleString()} remaining`;
document.getElementById('message').innerText = `${sms_sent.toLocaleString()} sent / ${sms_remaining_messages.toLocaleString()} remaining`;
// Calculate minimum width for "Messages Sent" as 1% of the total chart width
var minSentPercentage = (messagesSent === 0) ? 0 : 0.02;
var minSentPercentage = (sms_sent === 0) ? 0 : 0.02;
var minSentValue = totalMessages * minSentPercentage;
var displaySent = Math.max(messagesSent, minSentValue);
var displaySent = Math.max(sms_sent, minSentValue);
var displayRemaining = totalMessages - displaySent;
var svg = d3.select("#totalMessageChart");
@@ -48,7 +48,7 @@
.attr("width", 0) // Start with width 0 for animation
.on('mouseover', function(event) {
tooltip.style('display', 'block')
.html(`Messages Sent: ${messagesSent.toLocaleString()}`);
.html(`Messages Sent: ${sms_sent.toLocaleString()}`);
})
.on('mousemove', function(event) {
tooltip.style('left', `${event.pageX + 10}px`)
@@ -66,7 +66,7 @@
.attr("width", 0) // Start with width 0 for animation
.on('mouseover', function(event) {
tooltip.style('display', 'block')
.html(`Remaining: ${messagesRemaining.toLocaleString()}`);
.html(`Remaining: ${sms_remaining_messages.toLocaleString()}`);
})
.on('mousemove', function(event) {
tooltip.style('left', `${event.pageX + 10}px`)
@@ -115,9 +115,9 @@
var tbodyRow = document.createElement('tr');
var tdMessagesSent = document.createElement('td');
tdMessagesSent.textContent = messagesSent.toLocaleString(); // Value for Messages Sent
tdMessagesSent.textContent = sms_sent.toLocaleString(); // Value for Messages Sent
var tdRemaining = document.createElement('td');
tdRemaining.textContent = messagesRemaining.toLocaleString(); // Value for Remaining
tdRemaining.textContent = sms_remaining_messages.toLocaleString(); // Value for Remaining
tbodyRow.appendChild(tdMessagesSent);
tbodyRow.appendChild(tdRemaining);

View File

@@ -1,117 +0,0 @@
function showError(input, errorElement, message) {
errorElement.textContent = ""; // Clear existing message
errorElement.style.display = "block";
// Small delay to ensure screen readers pick up the change
setTimeout(() => {
errorElement.textContent = message;
}, 10);
if (input.type !== "radio" && input.type !== "checkbox") {
input.classList.add("usa-input--error");
}
input.setAttribute("aria-describedby", errorElement.id);
}
function hideError(input, errorElement) {
errorElement.style.display = "none";
if (input.type !== "radio" && input.type !== "checkbox") {
input.classList.remove("usa-input--error");
}
input.removeAttribute("aria-describedby");
}
function getFieldLabel(input) {
const label = document.querySelector(`label[for="${input.id}"]`);
return label ? label.textContent.trim() : "This field";
}
// Attach validation logic to forms
function attachValidation() {
const forms = document.querySelectorAll('form[data-force-focus="True"]');
forms.forEach((form) => {
const inputs = form.querySelectorAll("input, textarea, select");
form.addEventListener("submit", function (event) {
let isValid = true;
let firstInvalidInput = null;
const validatedRadioNames = new Set();
inputs.forEach((input) => {
if (input.type === "hidden") return;
const errorId = input.type === "radio" ? `${input.name}-error` : `${input.id}-error`;
let errorElement = document.getElementById(errorId);
if (!errorElement) {
errorElement = document.createElement("span");
errorElement.id = errorId;
errorElement.classList.add("usa-error-message");
errorElement.setAttribute("aria-live", "polite");
errorElement.style.display = "none";
if (input.type === "radio") {
const group = form.querySelectorAll(`input[name="${input.name}"]`);
const lastRadio = group[group.length - 1];
lastRadio.parentElement.insertAdjacentElement("afterend", errorElement);
} else {
input.insertAdjacentElement("afterend", errorElement);
}
}
if (input.type === "radio") {
if (validatedRadioNames.has(input.name)) return;
validatedRadioNames.add(input.name);
const radioGroup = form.querySelectorAll(`input[name="${input.name}"]`);
const isChecked = Array.from(radioGroup).some(radio => radio.checked);
if (!isChecked) {
showError(input, errorElement, `Error: A selection must be made.`);
isValid = false;
if (!firstInvalidInput) {
firstInvalidInput = input;
}
}
} else if (input.value.trim() === "") {
showError(input, errorElement, `Error: ${getFieldLabel(input)} is required.`);
isValid = false;
if (!firstInvalidInput) {
firstInvalidInput = input;
}
}
});
if (!isValid) {
event.preventDefault();
if (firstInvalidInput) firstInvalidInput.focus();
}
});
inputs.forEach((input) => {
if (input.type === "hidden") return;
input.addEventListener("input", function () {
const errorId = input.type === "radio" ? `${input.name}-error` : `${input.id}-error`;
const errorElement = document.getElementById(errorId);
if (errorElement && input.value.trim() !== "") {
hideError(input, errorElement);
}
});
if (input.type === "radio") {
input.addEventListener("change", function () {
const errorElement = document.getElementById(`${input.name}-error`);
if (errorElement) {
hideError(input, errorElement);
}
});
}
});
});
}
// Automatically attach validation only in the browser
if (typeof window !== "undefined") {
document.addEventListener("DOMContentLoaded", attachValidation);
}
// ✅ Check if we're in a Node.js environment (for Jest) before using `module.exports`
if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
module.exports = { showError, hideError, getFieldLabel, attachValidation };
}

View File

@@ -1,8 +0,0 @@
document.addEventListener("DOMContentLoaded", function () {
if (window.uswds && typeof window.uswds.init === 'function') {
console.log("Calling USWDS init");
window.uswds.init();
} else {
console.error("USWDS not found or init is not a function");
}
});

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -60,6 +60,17 @@ $failed: color('gray-cool-20');
}
}
.usa-tooltip {
line-height: 1;
.usa-tooltip__body {
width: units(mobile);
font-size: size("body", 2);
height: auto;
white-space: wrap;
line-height: units(1);
}
}
.progress-bar {
width: 300px;
height: 20px;

View File

@@ -49,12 +49,12 @@
}
.sms-message-sender, .sms-message-file-name, .sms-message-scheduler, .sms-message-template, .sms-message-sender {
margin: units(0.5) 0 0;
margin:0.25rem 0 0;
}
.sms-message-recipient {
color: color('gray-cool-90');
margin: units(0.5) 0 units(2);
margin: units(1) 0 units(1);
}
.sms-message-status {
@@ -344,43 +344,3 @@ h2.recipient-list {
}
}
}
.usa-search__input, [type=search] {
border-right: 1px solid;
height: 40px;
margin-top: units(1);
}
.usa-search .search-form__button {
height: 40px;
}
// Button ellipses loading
.dot-anim {
display: inline-block;
margin-left: 0; /* remove left margin if it exists */
padding-left: 0;
font-size: 1em;
animation: dots 1s steps(3, end) infinite;
}
/* Optional: reduce spacing by removing whitespace node */
button span.dot-anim {
margin-left: 0; /* forces no space even if white-space exists */
}
.dot-anim::after {
content: '.';
animation: dotPulse 1.5s steps(3, end) infinite;
}
@keyframes dotPulse {
0% { content: ''; }
33% { content: '.'; }
66% { content: '..'; }
100% { content: '...'; }
}
.modal-open {
overflow: hidden;
}

View File

@@ -139,6 +139,11 @@ td.table-empty-message {
font-family: family('sans');
}
.usa-dark-background .pill-item__label {
color: white;
text-decoration: none !important;
}
.pill-item.usa-link {
text-decoration: none !important;
}
@@ -179,19 +184,10 @@ td.table-empty-message {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
padding: 1rem 0;
padding: 1rem;
}
.user-list-item {
border: 2px solid color('gray-5');
padding: units(2);
button, .usa-accordion__content {
background-color: white;
border: 2px solid color('gray-5');
}
button:hover, button[aria-expanded="true"] {
background-color: color('gray-5');
}
@include at-media(desktop) {
width: calc(50% - units(1));
margin-bottom: 1rem;
@@ -202,12 +198,16 @@ td.table-empty-message {
word-wrap: break-word;
}
// border: 1px solid color('gray-cool-10');
// padding: units(2);
.tick-cross-list-permissions {
margin: units(1) 0;
padding-left: units(2);
}
.hint {
display: block;
font-size: size('body', 'sm');
font-weight: normal;
}
@@ -229,10 +229,6 @@ td.table-empty-message {
display: none;
}
.js-hidden {
display: none !important;
}
.folder-heading a.folder-heading-folder,
.template-list-folder {
background: url(../img/material-icons/folder.svg) no-repeat;
@@ -261,11 +257,6 @@ td.table-empty-message {
}
}
.usa-checkbox.template-list-item.template-list-item-with-checkbox.template-list-item-without-ancestors {
display: flex;
flex-direction: column;
}
.usa-checkbox__label-description {
margin: units(2px) 0 units(1) units(4);
}
@@ -297,11 +288,9 @@ td.table-empty-message {
@include u-width('mobile-lg');
margin-top: units(2);
}
input#search-by-name {
margin-top: units(1);
input#search {
width: 100%;
border: 1px solid color('gray-60');
height: 40px;
}
}
@@ -563,24 +552,6 @@ td.table-empty-message {
max-width: 100%;
}
.usa-tooltip {
&__information {
background: color('ink');
margin-top: 4px;
color: white;
border-radius: 50%;
height: units(3);
width: units(3);
border: 1px solid color('ink');
}
.usa-tooltip__body {
min-width: units('card-lg');
max-width: units('mobile');
white-space: normal;
word-wrap: break-word;
}
}
// Tabs
.tabs {
@@ -604,31 +575,19 @@ td.table-empty-message {
.big-number-smallest {
font-size: units(3);
}
.pill-item__label {
color: white;
}
&:not(.pill-item--selected):hover {
background: color('blue-warm-70v');
.pill-item__label {
color: white;
}
}
&.pill-item--selected {
.pill-item__label {
color: color('blue-60v');
}
&:hover {
.pill-item__label {
color: color('blue-60v');
}
}
&.pill-item--selected:hover {
color: color('blue-60v');
}
}
}
}
}
// Etc
.email-brand,
.browse-list {
padding: 0;
@@ -875,10 +834,6 @@ $do-dont-top-bar-width: 1;
border-radius: 2px;
}
.bg-gray-cool {
background-color: #dfe1e2;
}
.svg-circle-icon {
display: inline-block;
margin: 0;
@@ -1069,11 +1024,3 @@ nav.nav {
font-size: units(3);
font-weight: bold;
}
.form-control-error {
border: 4px solid #b10e1e
}
.usa-site-alert .usa-alert .usa-alert__body {
max-width: 75rem;
}

View File

@@ -1,5 +1,5 @@
@forward "uswds-theme";
@forward "uswds";
@forward "uswds-theme-custom-styles";
@forward "main";
@forward "legacy-styles";
@forward "data-visualization";

View File

@@ -37,7 +37,6 @@ $path: '/static/images/';
// Custom overrides
.govuk-link {
font-weight: bold;
color: #005ea5;
}
// Specific to this application

View File

@@ -12,9 +12,6 @@ class Config(object):
NOTIFY_APP_NAME = "admin"
NOTIFY_ENVIRONMENT = getenv("NOTIFY_ENVIRONMENT", "development")
API_HOST_NAME = getenv("API_HOST_NAME", "localhost")
API_PUBLIC_URL = getenv("API_PUBLIC_URL", "localhost")
API_PUBLIC_WS_URL = getenv("API_PUBLIC_WS_URL", "localhost")
ADMIN_BASE_URL = getenv("ADMIN_BASE_URL", "http://localhost:6012")
HEADER_COLOUR = (
"#81878b" # mix(govuk-colour("dark-grey"), govuk-colour("mid-grey"))
@@ -91,7 +88,7 @@ class Config(object):
],
}
FEATURE_SOCKET_ENABLED = getenv("FEATURE_SOCKET_ENABLED", "false") == "true"
FEATURE_ABOUT_PAGE_ENABLED = getenv("FEATURE_ABOUT_PAGE_ENABLED", "false") == "true"
def _s3_credentials_from_env(bucket_prefix):
@@ -133,9 +130,8 @@ class Test(Development):
WTF_CSRF_ENABLED = False
ASSET_DOMAIN = "static.example.com"
ASSET_PATH = "https://static.example.com/"
API_HOST_NAME = "http://you-forgot-to-mock-an-api-call-to"
API_PUBLIC_URL = "http://you-forgot-to-mock-an-api-call-to"
API_PUBLIC_WS_URL = "ws://you-forgot-to-mock-an-api-call-to"
REDIS_URL = "redis://you-forgot-to-mock-a-redis-call-to"
LOGO_CDN_DOMAIN = "static-logos.test.com"

View File

@@ -5,7 +5,7 @@
Explore Notify, add team members, and practice [sending messages to teammates](/using-notify/trial-mode).
2. ## Personalize content
Learn how to [personalize messages](/using-notify/how-to) to increase response.
Learn how to [personalize messages](/using-notify/guidance) to increase response.
3. ## Check delivery status
[Analyze the delivery](/using-notify/delivery-status) of your messages and download reports

View File

@@ -344,7 +344,7 @@ def nl2br(value):
html="escape",
)
).then(utils_nl2br)
) # nosec
)
return ""

View File

@@ -257,7 +257,7 @@ def govuk_text_input_field_widget(
return Markup(
render_template("components/components/input/template.njk", params=params)
) # nosec
)
class GovukTextInputField(StringField):
@@ -690,9 +690,7 @@ def govuk_checkbox_field_widget(self, field, param_extensions=None, **kwargs):
if param_extensions:
merge_jsonlike(params, param_extensions)
return Markup(
render_template("forms/fields/checkboxes/macro.njk", params=params)
) # nosec
return Markup(render_template("forms/fields/checkboxes/macro.njk", params=params))
def govuk_checkboxes_field_widget(
@@ -706,7 +704,7 @@ def govuk_checkboxes_field_widget(
f' data-field-label="{field_label}">'
f" {checkboxes_string}"
f"</div>"
) # nosec
)
return result
@@ -759,14 +757,12 @@ def govuk_checkboxes_field_widget(
return _wrap_in_collapsible(
self.field_label,
Markup(
render_template("forms/fields/checkboxes/macro.njk", params=params)
), # nosec
Markup(render_template("forms/fields/checkboxes/macro.njk", params=params)),
)
else:
return Markup(
render_template("forms/fields/checkboxes/macro.njk", params=params)
) # nosec
)
def govuk_radios_field_widget(self, field, param_extensions=None, **kwargs):
@@ -809,7 +805,7 @@ def govuk_radios_field_widget(self, field, param_extensions=None, **kwargs):
return Markup(
render_template("components/components/radios/template.njk", params=params)
) # nosec
)
class GovukCheckboxField(BooleanField):

View File

@@ -61,7 +61,7 @@ class ValidEmail:
class NoCommasInPlaceHolders:
def __init__(self, message="You cannot put commas between double parenthesis"):
def __init__(self, message="You cannot put commas between double brackets"):
self.message = message
def __call__(self, form, field):
@@ -108,17 +108,33 @@ class OnlySMSCharacters:
)
if non_sms_characters:
raise ValidationError(
"Please remove the unaccepted character {} in your message, then save again".format(
"You cannot use {} in {}. {} will not show up properly on everyones phones.".format(
formatted_list(
non_sms_characters,
conjunction="and",
conjunction="or",
before_each="",
after_each="",
),
{
"sms": "text messages",
}.get(self._template_type),
("It" if len(non_sms_characters) == 1 else "They"),
)
)
# class NoPlaceholders:
# def __init__(self, message=None):
# self.message = message or (
# 'You cant use ((double brackets)) to personalize this message'
# )
# def __call__(self, form, field):
# if Field(field.data).placeholders:
# raise ValidationError(self.message)
class LettersNumbersSingleQuotesFullStopsAndUnderscoresOnly:
regex = re.compile(r"^[a-zA-Z0-9\s\._']+$")

View File

@@ -1,25 +1,34 @@
import calendar
from datetime import datetime, timedelta
from datetime import datetime
from functools import partial
from itertools import groupby
from zoneinfo import ZoneInfo
from flask import abort, jsonify, render_template, request, session, url_for
from flask import Response, abort, jsonify, render_template, request, session, url_for
from flask_login import current_user
from werkzeug.utils import redirect
from app import (
billing_api_client,
current_service,
job_api_client,
service_api_client,
template_statistics_client,
)
from app.formatters import format_date_numeric, format_datetime_numeric, get_time_left
from app.main import main
from app.main.views.user_profile import set_timezone
from app.statistics_utils import get_formatted_percentage
from app.utils import DELIVERED_STATUSES, FAILURE_STATUSES, REQUESTED_STATUSES
from app.utils import (
DELIVERED_STATUSES,
FAILURE_STATUSES,
REQUESTED_STATUSES,
service_has_permission,
)
from app.utils.csv import Spreadsheet
from app.utils.pagination import generate_next_dict, generate_previous_dict
from app.utils.time import get_current_financial_year
from app.utils.user import user_has_permissions
from notifications_utils.recipients import format_phone_number_human_readable
@main.route("/services/<uuid:service_id>/dashboard")
@@ -39,111 +48,87 @@ def service_dashboard(service_id):
if not current_user.has_permissions("view_activity"):
return redirect(url_for("main.choose_template", service_id=service_id))
yearly_usage = billing_api_client.get_annual_usage_for_service(
service_id,
get_current_financial_year(),
)
free_sms_allowance = billing_api_client.get_free_sms_fragment_limit_for_year(
current_service.id,
)
usage_data = get_annual_usage_breakdown(yearly_usage, free_sms_allowance)
sms_sent = usage_data["sms_sent"]
sms_allowance_remaining = usage_data["sms_allowance_remaining"]
job_response = job_api_client.get_jobs(service_id)["data"]
service_data_retention_days = 7
active_jobs = [job for job in job_response if job["job_status"] != "cancelled"]
sorted_jobs = sorted(active_jobs, key=lambda job: job["created_at"], reverse=True)
job_lists = [
{**job_dict, "finished_processing": job_is_finished(job_dict)}
for job_dict in sorted_jobs
jobs = [
{
"job_id": job["id"],
"time_left": get_time_left(job["created_at"]),
"download_link": url_for(
".view_job_csv", service_id=current_service.id, job_id=job["id"]
),
"view_job_link": url_for(
".view_job", service_id=current_service.id, job_id=job["id"]
),
"created_at": job["created_at"],
"processing_finished": job.get("processing_finished"),
"processing_started": job.get("processing_started"),
"notification_count": job["notification_count"],
"created_by": job["created_by"],
"template_name": job["template_name"],
"original_file_name": job["original_file_name"],
}
for job in job_response
if job["job_status"] != "cancelled"
]
total_messages = service_api_client.get_service_message_ratio(service_id)
messages_remaining = total_messages.get("messages_remaining", 0)
messages_sent = total_messages.get("messages_sent", 0)
all_statistics = template_statistics_client.get_template_statistics_for_service(
service_id, limit_days=7
)
template_statistics = aggregate_template_usage(all_statistics)
return render_template(
"views/dashboard/dashboard.html",
jobs=job_lists,
updates_url=url_for(".service_dashboard_updates", service_id=service_id),
partials=get_dashboard_partials(service_id),
jobs=jobs,
service_data_retention_days=service_data_retention_days,
messages_remaining=messages_remaining,
messages_sent=messages_sent,
template_statistics=template_statistics,
most_used_template_count=max(
[row["count"] for row in template_statistics] or [0]
),
sms_sent=sms_sent,
sms_allowance_remaining=sms_allowance_remaining,
)
def job_is_finished(job_dict):
done_statuses = DELIVERED_STATUSES + FAILURE_STATUSES + ["cancelled"]
processed_count = sum(
stat["count"]
for stat in job_dict["statistics"]
if stat["status"] in done_statuses
)
return job_dict["notification_count"] == processed_count
@main.route("/services/<uuid:service_id>/daily-stats.json")
@user_has_permissions()
def get_daily_stats(service_id):
@main.route("/daily_stats.json")
def get_daily_stats():
service_id = session.get("service_id")
date_range = get_stats_date_range()
days = date_range["days"]
user_timezone = request.args.get("timezone", "UTC")
stats_utc = service_api_client.get_service_notification_statistics_by_day(
service_id,
start_date=date_range["start_date"],
days=days,
stats = service_api_client.get_service_notification_statistics_by_day(
service_id, start_date=date_range["start_date"], days=date_range["days"]
)
local_stats = get_local_daily_stats_for_last_x_days(stats_utc, user_timezone, days)
return jsonify(local_stats)
return jsonify(stats)
def get_local_daily_stats_for_last_x_days(stats_utc, user_timezone, days):
tz = ZoneInfo(user_timezone)
today_local = datetime.now(tz).date()
start_local = today_local - timedelta(days=days - 1)
# Generate exactly days local dates, each with zeroed stats
days_list = [
(start_local + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(days)
]
aggregator = {
d: {
"sms": {"delivered": 0, "failure": 0, "pending": 0, "requested": 0},
"email": {"delivered": 0, "failure": 0, "pending": 0, "requested": 0},
}
for d in days_list
}
# Convert each UTC timestamp to local date and iterate
for utc_ts, data in stats_utc.items():
utc_dt = datetime.strptime(utc_ts, "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=ZoneInfo("UTC")
)
local_day = utc_dt.astimezone(tz).strftime("%Y-%m-%d")
if local_day in aggregator:
for msg_type in ["sms", "email"]:
for status in ["delivered", "failure", "pending", "requested"]:
aggregator[local_day][msg_type][status] += data[msg_type][status]
return aggregator
@main.route("/services/<uuid:service_id>/daily-stats-by-user.json")
@user_has_permissions()
def get_daily_stats_by_user(service_id):
@main.route("/daily_stats_by_user.json")
def get_daily_stats_by_user():
service_id = session.get("service_id")
date_range = get_stats_date_range()
days = date_range["days"]
user_timezone = request.args.get("timezone", "UTC")
stats_utc = service_api_client.get_user_service_notification_statistics_by_day(
user_id = current_user.id
stats = service_api_client.get_user_service_notification_statistics_by_day(
service_id,
user_id=current_user.id,
user_id,
start_date=date_range["start_date"],
days=days,
days=date_range["days"],
)
return jsonify(stats)
local_stats = get_local_daily_stats_for_last_x_days(stats_utc, user_timezone, days)
return jsonify(local_stats)
@main.route("/services/<uuid:service_id>/dashboard.json")
@user_has_permissions("view_activity")
def service_dashboard_updates(service_id):
return jsonify(**get_dashboard_partials(service_id))
@main.route("/services/<uuid:service_id>/template-activity")
@user_has_permissions("view_activity")
def template_history(service_id):
return redirect(url_for("main.template_usage", service_id=service_id), code=301)
@main.route("/services/<uuid:service_id>/template-usage")
@@ -231,6 +216,103 @@ def usage(service_id):
)
@main.route("/services/<uuid:service_id>/monthly")
@user_has_permissions("view_activity")
def monthly(service_id):
year, current_financial_year = requested_and_current_financial_year(request)
return render_template(
"views/dashboard/monthly.html",
months=format_monthly_stats_to_list(
service_api_client.get_monthly_notification_stats(service_id, year)["data"]
),
years=get_tuples_of_financial_years(
partial_url=partial(url_for, ".monthly", service_id=service_id),
start=current_financial_year - 2,
end=current_financial_year,
),
selected_year=year,
)
@main.route("/services/<uuid:service_id>/inbox")
@user_has_permissions("view_activity")
@service_has_permission("inbound_sms")
def inbox(service_id):
return render_template(
"views/dashboard/inbox.html",
partials=get_inbox_partials(service_id),
updates_url=url_for(
".inbox_updates", service_id=service_id, page=request.args.get("page")
),
)
@main.route("/services/<uuid:service_id>/inbox.json")
@user_has_permissions("view_activity")
@service_has_permission("inbound_sms")
def inbox_updates(service_id):
return jsonify(get_inbox_partials(service_id))
@main.route("/services/<uuid:service_id>/inbox.csv")
@user_has_permissions("view_activity")
def inbox_download(service_id):
return Response(
Spreadsheet.from_rows(
[
[
"Phone number",
"Message",
"Received",
]
]
+ [
[
format_phone_number_human_readable(message["user_number"]),
message["content"].lstrip(("=+-@")),
format_datetime_numeric(message["created_at"]),
]
for message in service_api_client.get_inbound_sms(service_id)["data"]
]
).as_csv_data,
mimetype="text/csv",
headers={
"Content-Disposition": 'inline; filename="Received text messages {}.csv"'.format(
format_date_numeric(datetime.utcnow().isoformat())
)
},
)
def get_inbox_partials(service_id):
page = int(request.args.get("page", 1))
inbound_messages_data = service_api_client.get_most_recent_inbound_sms(
service_id, page=page
)
inbound_messages = inbound_messages_data["data"]
if not inbound_messages:
inbound_number = current_service.inbound_number
else:
inbound_number = None
prev_page = None
if page > 1:
prev_page = generate_previous_dict("main.inbox", service_id, page)
next_page = None
if inbound_messages_data["has_next"]:
next_page = generate_next_dict("main.inbox", service_id, page)
return {
"messages": render_template(
"views/dashboard/_inbox_messages.html",
messages=inbound_messages,
inbound_number=inbound_number,
prev_page=prev_page,
next_page=next_page,
)
}
def filter_out_cancelled_stats(template_statistics):
return [s for s in template_statistics if s["status"] != "cancelled"]
@@ -262,6 +344,71 @@ def aggregate_template_usage(template_statistics, sort_key="count"):
return sorted(templates, key=lambda x: x[sort_key], reverse=True)
def aggregate_notifications_stats(template_statistics):
template_statistics = filter_out_cancelled_stats(template_statistics)
notifications = {
template_type: {status: 0 for status in ("requested", "delivered", "failed")}
for template_type in ["sms", "email"]
}
for stat in template_statistics:
notifications[stat["template_type"]]["requested"] += stat["count"]
if stat["status"] in DELIVERED_STATUSES:
notifications[stat["template_type"]]["delivered"] += stat["count"]
elif stat["status"] in FAILURE_STATUSES:
notifications[stat["template_type"]]["failed"] += stat["count"]
return notifications
def get_dashboard_partials(service_id):
all_statistics = template_statistics_client.get_template_statistics_for_service(
service_id, limit_days=7
)
template_statistics = aggregate_template_usage(all_statistics)
stats = aggregate_notifications_stats(all_statistics)
dashboard_totals = (get_dashboard_totals(stats),)
free_sms_allowance = billing_api_client.get_free_sms_fragment_limit_for_year(
current_service.id,
)
# These 2 calls will update the dashboard sms allowance count while in trial mode.
billing_api_client.get_monthly_usage_for_service(
service_id, get_current_financial_year()
)
billing_api_client.create_or_update_free_sms_fragment_limit(
service_id, free_sms_fragment_limit=free_sms_allowance
)
yearly_usage = billing_api_client.get_annual_usage_for_service(
service_id,
get_current_financial_year(),
)
return {
"upcoming": render_template(
"views/dashboard/_upcoming.html",
),
"inbox": render_template(
"views/dashboard/_inbox.html",
),
"totals": render_template(
"views/dashboard/_totals.html",
service_id=service_id,
statistics=dashboard_totals[0],
),
"template-statistics": render_template(
"views/dashboard/template-statistics.html",
template_statistics=template_statistics,
most_used_template_count=max(
[row["count"] for row in template_statistics] or [0]
),
),
"usage": render_template(
"views/dashboard/_usage.html",
**get_annual_usage_breakdown(yearly_usage, free_sms_allowance),
),
}
def get_dashboard_totals(statistics):
for msg_type in statistics.values():

View File

@@ -1,5 +1,3 @@
import logging
from flask import (
abort,
current_app,
@@ -21,23 +19,20 @@ from app.main.views.sub_navigation_dictionaries import (
)
from app.utils.user import user_is_logged_in
logger = logging.getLogger(__name__)
# Hook to check for feature flags
@main.before_request
def check_feature_flags():
# Placeholder for future feature flag checks
# Example:
# if request.path.startswith("/some-feature") and not current_app.config.get("FEATURE_SOME_FEATURE_ENABLED", False):
# abort(404)
pass
if request.path.startswith("/about") and not current_app.config.get(
"FEATURE_ABOUT_PAGE_ENABLED", False
):
abort(404)
@main.route("/test/feature-flags")
def test_feature_flags():
return jsonify(
{"FEATURE_SOCKET_ENABLED": current_app.config["FEATURE_SOCKET_ENABLED"]}
{"FEATURE_ABOUT_PAGE_ENABLED": current_app.config["FEATURE_ABOUT_PAGE_ENABLED"]}
)
@@ -222,11 +217,11 @@ def benchmark_performance():
)
@main.route("/using-notify/how-to")
@main.route("/using-notify/guidance")
@user_is_logged_in
def how_to():
def guidance_index():
return render_template(
"views/how-to/index.html",
"views/guidance/index.html",
navigation_links=using_notify_nav(),
)
@@ -263,37 +258,37 @@ def why_text_messaging():
)
@main.route("/notify-service-ending")
@user_is_logged_in
def notify_service_ending():
@main.route("/join-notify")
def join_notify():
return render_template(
"views/notify-service-ending.html",
"views/join-notify.html",
navigation_links=about_notify_nav(),
)
@main.route("/using-notify/how-to/create-and-send-messages")
@main.route("/using-notify/guidance/create-and-send-messages")
@user_is_logged_in
def create_and_send_messages():
return render_template(
"views/how-to/create-and-send-messages.html",
"views/guidance/create-and-send-messages.html",
navigation_links=using_notify_nav(),
)
@main.route("/using-notify/how-to/edit-and-format-messages")
@main.route("/using-notify/guidance/edit-and-format-messages")
@user_is_logged_in
def edit_and_format_messages():
return render_template(
"views/how-to/edit-and-format-messages.html",
"views/guidance/edit-and-format-messages.html",
navigation_links=using_notify_nav(),
)
@main.route("/using-notify/how-to/send-files-by-email")
@main.route("/using-notify/guidance/send-files-by-email")
@user_is_logged_in
def send_files_by_email():
return render_template(
"views/how-to/send-files-by-email.html",
"views/guidance/send-files-by-email.html",
navigation_links=using_notify_nav(),
)

View File

@@ -23,7 +23,7 @@ def accept_invite(token):
<a href={url_for("main.sign_out")} class="usa-link">Sign out</a>
and click the link again to accept this invite.
"""
) # nosec
)
flash(message=message)
@@ -98,7 +98,7 @@ def accept_org_invite(token):
""".format(
current_user.email_address, url_for("main.sign_out")
)
) # nosec
)
flash(message=message)

View File

@@ -1,11 +1,10 @@
# -*- coding: utf-8 -*-
import os
from functools import partial
from flask import (
Response,
abort,
current_app,
jsonify,
redirect,
render_template,
@@ -58,12 +57,9 @@ def view_job(service_id, job_id):
filter_args = parse_filter_args(request.args)
filter_args["status"] = set_status_filters(filter_args)
api_public_url = os.environ.get("API_PUBLIC_URL")
return render_template(
"views/jobs/job.html",
api_public_url=api_public_url,
FEATURE_SOCKET_ENABLED=current_app.config["FEATURE_SOCKET_ENABLED"],
job=job,
status=request.args.get("status", ""),
updates_url=url_for(
@@ -356,7 +352,7 @@ def _get_job_counts(job):
Markup(
f"""total<span class="usa-sr-only">
{"text message" if job_type == "sms" else job_type}s</span>"""
), # nosec
),
"",
job.notification_count,
],
@@ -364,7 +360,7 @@ def _get_job_counts(job):
Markup(
f"""pending<span class="usa-sr-only">
{message_count_noun(job.notifications_sending, job_type)}</span>"""
), # nosec
),
"pending",
job.notifications_sending,
],
@@ -372,7 +368,7 @@ def _get_job_counts(job):
Markup(
f"""delivered<span class="usa-sr-only">
{message_count_noun(job.notifications_delivered, job_type)}</span>"""
), # nosec
),
"delivered",
job.notifications_delivered,
],
@@ -380,7 +376,7 @@ def _get_job_counts(job):
Markup(
f"""failed<span class="usa-sr-only">
{message_count_noun(job.notifications_failed, job_type)}</span>"""
), # nosec
),
"failed",
job.notifications_failed,
],
@@ -406,9 +402,7 @@ def get_job_partials(job):
)
if request.referrer is not None:
session["arrived_from_preview_page"] = ("check" in request.referrer) or (
"help=0" in request.referrer
)
session["arrived_from_preview_page"] = "check" in request.referrer
else:
session["arrived_from_preview_page"] = False
@@ -470,4 +464,4 @@ def get_preview_of_content(notification):
notification["personalisation"],
redact_missing_personalisation=True,
).subject
) # nosec
)

View File

@@ -116,70 +116,6 @@ def download_all_users():
return response
@main.route("/platform-admin/get-redis-report")
@user_is_platform_admin
def get_redis_report():
memory_info = redis_client.info("memory")
memory_used = memory_info.get("used_memory_human", "N/A")
max_memory = memory_info.get("maxmemory_human", "N/A")
if max_memory == "0B":
max_memory = "No set limit"
mem_fragmentation = memory_info.get("mem_fragmentation_ratio", "N/A")
frag_quality = "Swapping (bad)"
if mem_fragmentation >= 1.0:
frag_quality = "Healthy"
if mem_fragmentation > 1.5:
frag_quality = "Problematic"
if mem_fragmentation > 2.0:
frag_quality = "Severe fragmentation"
frag_note = ""
if mem_fragmentation > 2.0:
frag_note = "Use MEMORY PURGE.\nReplace multiple small keys with hashes.\nAvoid long keys.\nSet max_memory."
elif mem_fragmentation < 1.0:
frag_note = "Allocate more RAM.\nSet max_memory."
keys = redis_client.keys("*")
key_details = []
for key in keys:
key_type = redis_client.type(key).decode("utf-8")
ttl = redis_client.ttl(key)
ttl_str = "No Expiry" if ttl == -1 else f"{ttl} seconds"
key_details.append(
{"Key": key.decode("utf-8"), "Type": key_type, "TTL": ttl_str}
)
output = StringIO()
writer = csv.writer(
output,
)
writer.writerow(["Redis Report"])
writer.writerow([])
writer.writerow(["Memory"])
writer.writerow(["", "Memory Used", memory_used])
writer.writerow(["", "Max Memory", max_memory])
writer.writerow(["", "Memory Fragmentation Ratio", mem_fragmentation])
writer.writerow(["", "Memory Fragmentation Quality", frag_quality, frag_note])
writer.writerow([])
writer.writerow(["Keys Overview"])
writer.writerow(["", "TTL", "Type", "Key"])
for key_detail in key_details:
writer.writerow(
["", key_detail["TTL"], key_detail["Type"], key_detail["Key"][0:50]]
)
csv_data = output.getvalue()
# Create a direct download response with the CSV data and appropriate headers
response = Response(csv_data, content_type="text/csv; charset=utf-8")
response.headers["Content-Disposition"] = "attachment; filename=redis.csv"
return response
def is_over_threshold(number, total, threshold):
percentage = number / total * 100 if total else 0
return percentage > threshold

View File

@@ -4,7 +4,6 @@ import uuid
from string import ascii_uppercase
from zipfile import BadZipFile
import bleach
from flask import (
abort,
current_app,
@@ -168,12 +167,10 @@ def send_messages(service_id, template_id):
# just show the first error, as we don't expect the form to have more
# than one, since it only has one field
first_field_errors = list(form.errors.values())[0]
error_message = '<span class="error-message usa-error-message">'
error_message = '<span class="usa-error-message">'
error_message = f"{error_message}{first_field_errors[0]}"
error_message = f"{error_message}</span>"
# use 'nosec' because we applied bleach.clean to strip dangerous tags
error_message = bleach.clean(error_message)
error_message = Markup(error_message) # nosec
error_message = Markup(error_message)
flash(error_message)
column_headings = get_spreadsheet_column_headings_from_template(template)
@@ -481,7 +478,6 @@ def send_one_off_step(service_id, template_id, step_index):
),
template=template,
form=form,
current_placeholder=current_placeholder,
skip_link=get_skip_link(step_index, template),
back_link=back_link,
link_to_upload=(
@@ -561,47 +557,24 @@ def _check_messages(service_id, template_id, upload_id, preview_row, **kwargs):
)
if request.args.get("from_test"):
back_link = {
"href": {
"url": url_for(
"main.send_one_off", service_id=service_id, template_id=template.id
),
"text": "Back to message personalization",
},
"html": "Back to message personalization",
}
back_link_from_preview = {
"href": {
"url": url_for(
"main.send_one_off", service_id=service_id, template_id=template.id
),
"text": "Back to message personalization",
},
"html": "Back to message personalization",
}
# TODO: may not be required after letters code removed
back_link = url_for(
"main.send_one_off", service_id=service_id, template_id=template.id
)
back_link_from_preview = url_for(
"main.send_one_off", service_id=service_id, template_id=template.id
)
choose_time_form = None
else:
back_link = {
"href": {
"url": url_for(
"main.send_messages", service_id=service_id, template_id=template.id
),
"text": "Back to upload a file",
},
"html": "Back to upload a file",
}
back_link_from_preview = {
"href": {
"url": url_for(
"main.check_messages",
service_id=service_id,
template_id=template.id,
upload_id=upload_id,
),
"text": "Back to check messages",
},
"html": "Back to check messages",
}
back_link = url_for(
"main.send_messages", service_id=service_id, template_id=template.id
)
back_link_from_preview = url_for(
"main.check_messages",
service_id=service_id,
template_id=template.id,
upload_id=upload_id,
)
choose_time_form = ChooseTimeForm()
if preview_row < 2:
@@ -779,62 +752,31 @@ def get_back_link(
preview=False,
):
if preview:
return {
"href": {
"url": url_for(
"main.check_notification",
service_id=service_id,
template_id=template.id,
),
"text": "Back to select delivery time",
},
"html": "Back to select delivery time",
}
return url_for(
"main.check_notification",
service_id=service_id,
template_id=template.id,
)
if step_index == 0:
if should_skip_template_page(template._template):
return {
"href": {
"url": url_for(
".choose_template",
service_id=service_id,
),
"text": "Back to all templates",
},
"html": "Back to all templates",
}
return url_for(
".choose_template",
service_id=service_id,
)
else:
return {
"href": {
"url": url_for(
".view_template",
service_id=service_id,
template_id=template.id,
),
"text": "Back to confirm your template",
},
"html": "Back to confirm your template",
}
# fallback for other steps
back_to_text = (
"Back to select recipients"
if step_index == 1
else "Back to message personalization"
)
return {
"href": {
"url": url_for(
"main.send_one_off_step",
return url_for(
".view_template",
service_id=service_id,
template_id=template.id,
step_index=step_index - 1,
),
"text": back_to_text,
},
"html": back_to_text,
}
)
return url_for(
"main.send_one_off_step",
service_id=service_id,
template_id=template.id,
step_index=step_index - 1,
)
def get_skip_link(step_index, template):
@@ -934,7 +876,7 @@ def _check_notification(service_id, template_id, exception=None, **kwargs):
if (not session.get("recipient")) or not all_placeholders_in_session(
template.placeholders
):
raise PermanentRedirect(back_link["href"]["url"])
raise PermanentRedirect(back_link)
template.values = get_recipient_and_placeholders_from_session(
template.template_type
@@ -982,10 +924,6 @@ def get_template_error_dict(exception):
def preview_notification(service_id, template_id):
recipient = get_recipient()
if not recipient:
current_app.logger.warning(
f"No recipient found for service {service_id}, template {template_id}. Redirecting..."
)
return redirect(
url_for(
".send_one_off",

View File

@@ -62,18 +62,17 @@ def _get_access_token(code): # pragma: no cover
code_param = f"code={code}"
url = f"{base_url}{cli_assert}&{cli_assert_type}&{code_param}&grant_type=authorization_code"
headers = {"Authorization": "Bearer %s" % token}
response = requests.post(url, headers=headers, timeout=30)
response = requests.post(url, headers=headers)
response_json = response.json()
id_token = get_id_token(response_json)
nonce = id_token["nonce"]
nonce_key = f"login-nonce-{unquote(nonce)}"
if not os.getenv("NOTIFY_ENVIRONMENT") == "development":
stored_nonce = redis_client.get(nonce_key).decode("utf8")
stored_nonce = redis_client.get(nonce_key).decode("utf8")
if nonce != stored_nonce:
current_app.logger.error(f"Nonce Error: {nonce} != {stored_nonce}")
abort(403)
if nonce != stored_nonce:
current_app.logger.error(f"Nonce Error: {nonce} != {stored_nonce}")
abort(403)
try:
access_token = response_json["access_token"]
@@ -88,7 +87,10 @@ def _get_access_token(code): # pragma: no cover
def _get_user_email_and_uuid(access_token): # pragma: no cover
headers = {"Authorization": "Bearer %s" % access_token}
user_info_url = os.getenv("LOGIN_DOT_GOV_USER_INFO_URL")
user_attributes = requests.get(user_info_url, headers=headers, timeout=30)
user_attributes = requests.get(
user_info_url,
headers=headers,
)
user_email = user_attributes.json()["email"]
user_uuid = user_attributes.json()["sub"]
return user_email, user_uuid
@@ -110,7 +112,7 @@ def _do_login_dot_gov(): # $ pragma: no cover
verify_key = f"login-verify_email-{unquote(state)}"
verify_path = bool(redis_client.get(verify_key))
if not verify_path and not os.getenv("NOTIFY_ENVIRONMENT") == "development":
if not verify_path:
state_key = f"login-state-{unquote(state)}"
stored_state = unquote(redis_client.get(state_key).decode("utf8"))
if state != stored_state:

View File

@@ -17,7 +17,7 @@ def _sign_out_at_login_dot_gov():
url = f"{base_url}{client_id}&{post_logout_redirect_uri}"
current_app.logger.info(f"url={url}")
response = requests.post(url, timeout=30)
response = requests.post(url)
# response = requests.post(url)
current_app.logger.info(f"login.gov response: {response.text}")

View File

@@ -2,7 +2,7 @@ def using_notify_nav():
nav_items = [
{"name": "Get started", "link": "main.get_started"},
{
"name": "Best practices",
"name": "Best Practices",
"link": "main.best_practices",
"sub_navigation_items": [
{
@@ -33,8 +33,8 @@ def using_notify_nav():
},
{"name": "Trial mode", "link": "main.trial_mode_new"},
{"name": "Tracking usage", "link": "main.pricing"},
{"name": "Delivery status", "link": "main.message_status"},
{"name": "How to", "link": "main.how_to"},
{"name": "Delivery Status", "link": "main.message_status"},
{"name": "Guidance", "link": "main.guidance_index"},
]
return nav_items
@@ -56,6 +56,10 @@ def about_notify_nav():
},
],
},
{
"name": "Join Notify",
"link": "main.join_notify",
},
{
"name": "Contact us",
"link": "main.contact",

View File

@@ -680,44 +680,42 @@ def count_content_length(service_id, template_type):
)
def _is_latin1(s):
return bool(s.encode(encoding="latin-1", errors="strict"))
def _get_content_count_error_and_message_for_template(template):
url = "https://en.wikipedia.org/wiki/ISO/IEC_8859-1"
if template.template_type == "sms":
s1 = (
"<html><body>Looks like your template may have one of these characters "
"• ™ ∞ ≤ or ≥ or emoji, which won't save."
)
s2 = "<br>Please remove any unaccepted characters or emojis and try again.</body></html>"
s1 = f"<html><body>Use of characters outside the <a href='{url}'>IEC_8859-1</a> character set may increase "
s2 = "the message fragment count, resulting in additional charges, and these IEC_8859-1 "
s3 = "characters may not display properly on some older mobile devices.</body></html>"
# Define characters that should be blocked
BLOCKED_CHARACTERS = {"", "", "", "", ""}
warning = ""
try:
_is_latin1(template.content)
except UnicodeEncodeError:
warning = f"{s1}{s2}{s3}"
def contains_blocked_characters(content):
"""Check if the content contains explicitly blocked characters."""
return any(c in BLOCKED_CHARACTERS for c in content)
# Check for blocked characters
if contains_blocked_characters(template.content):
warning = f"{s1}{s2}"
return False, Markup(warning) # nosec
# If message is too long, return the length error
if template.is_message_too_long():
return True, (
f"You have "
f"{character_count(template.content_count_without_prefix - SMS_CHAR_COUNT_LIMIT)} "
f"too many"
)
# Show charge message as usual if no warning
if template.placeholders:
return False, Markup(
f"Will be charged as {message_count(template.fragment_count, template.template_type)} "
f"(not including personalization)."
) # nosec
return False, Markup(
f"Will be charged as {message_count(template.fragment_count, template.template_type)}."
) # nosec
return False, (
Markup(
f"Will be charged as {message_count(template.fragment_count, template.template_type)} "
f"(not including personalization). {warning}"
)
)
return False, (
# Markup marks html contents safe so that they render properly. Don't use it if there is user input.
Markup(
f"Will be charged as {message_count(template.fragment_count, template.template_type)}. {warning} "
)
)
@main.route(

View File

@@ -139,28 +139,14 @@ def tour_step(service_id, template_id, step_index):
def _get_tour_step_back_link(service_id, template_id, step_index):
if step_index == 1:
return {
"href": {
"url": url_for(
"main.begin_tour", service_id=service_id, template_id=template_id
),
"text": "Back to tour start",
},
"html": "Back to tour start",
}
else:
return {
"href": {
"url": url_for(
"main.tour_step",
service_id=service_id,
template_id=template_id,
step_index=step_index - 1,
),
"text": "Back to previous step",
},
"html": "Back to previous step",
}
return url_for(".begin_tour", service_id=service_id, template_id=template_id)
return url_for(
".tour_step",
service_id=service_id,
template_id=template_id,
step_index=step_index - 1,
)
@main.route(
@@ -197,18 +183,12 @@ def check_tour_notification(service_id, template_id):
)
)
back_link = {
"href": {
"url": url_for(
"main.tour_step",
service_id=current_service.id,
template_id=template_id,
step_index=len(placeholders),
),
"text": "Back to previous step",
},
"html": "Back to previous step",
}
back_link = url_for(
".tour_step",
service_id=current_service.id,
template_id=template_id,
step_index=len(placeholders),
)
template.values = get_recipient_and_placeholders_from_session(
template.template_type

View File

@@ -54,10 +54,12 @@ class HeaderNavigation(Navigation):
"pricing",
"trial_mode_new",
"message_status",
"how_to",
"guidance_index",
},
"accounts-or-dashboard": {
"conversation",
"inbox",
"monthly",
"service_dashboard",
"template_usage",
"view_notification",
@@ -159,6 +161,8 @@ class MainNavigation(Navigation):
},
"dashboard": {
"conversation",
"inbox",
"monthly",
"service_dashboard",
"template_usage",
"view_notification",

View File

@@ -6,36 +6,17 @@ from app.notify_client import NotifyAdminAPIClient
class BillingAPIClient(NotifyAdminAPIClient):
def get_monthly_usage_for_service(self, service_id, year):
monthly_usage = redis_client.get(f"monthly-usage-summary-{service_id}-{year}")
if monthly_usage is not None:
return json.loads(monthly_usage.decode("utf-8"))
result = self.get(
return self.get(
"/service/{0}/billing/monthly-usage".format(service_id),
params=dict(year=year),
)
redis_client.set(
f"monthly-usage-summary-{service_id}-{year}",
json.dumps(result),
ex=30,
)
return result
def get_annual_usage_for_service(self, service_id, year=None):
annual_usage = redis_client.get(f"yearly-usage-summary-{service_id}-{year}")
if annual_usage is not None:
return json.loads(annual_usage.decode("utf-8"))
result = self.get(
return self.get(
"/service/{0}/billing/yearly-usage-summary".format(service_id),
params=dict(year=year),
)
redis_client.set(
f"yearly-usage-summary-{service_id}-{year}",
json.dumps(result),
ex=30,
)
return result
def get_free_sms_fragment_limit_for_year(self, service_id, year=None):
frag_limit = redis_client.get(f"free-sms-fragment-limit-{service_id}-{year}")
if frag_limit is not None:
@@ -67,28 +48,13 @@ class BillingAPIClient(NotifyAdminAPIClient):
)
def get_data_for_billing_report(self, start_date, end_date):
x_start_date = str(start_date)
x_start_date = x_start_date.replace(" ", "_")
x_end_date = str(end_date)
x_end_date = x_end_date.replace(" ", "_")
billing_data = redis_client.get(
f"get-data-for-billing-report-{x_start_date}-{x_end_date}"
)
if billing_data is not None:
return json.loads(billing_data.decode("utf-8"))
result = self.get(
return self.get(
url="/platform-stats/data-for-billing-report",
params={
"start_date": str(start_date),
"end_date": str(end_date),
},
)
redis_client.set(
f"get-data-for-billing-report-{x_start_date}-{x_end_date}",
json.dumps(result),
ex=30,
)
return result
def get_data_for_volumes_by_service_report(self, start_date, end_date):
return self.get(

View File

@@ -1,6 +1,3 @@
import json
from app.extensions import redis_client
from app.notify_client import NotifyAdminAPIClient, _attach_current_user
@@ -44,7 +41,7 @@ class NotificationApiClient(NotifyAdminAPIClient):
if job_id:
return method(
url="/service/{}/job/{}/notifications".format(service_id, job_id),
**kwargs,
**kwargs
)
else:
if limit_days is not None:
@@ -99,20 +96,9 @@ class NotificationApiClient(NotifyAdminAPIClient):
)
def get_notification_count_for_job_id(self, *, service_id, job_id):
counts = redis_client.get(
f"notification-count-for-job-id-{service_id}-{job_id}"
)
if counts is not None:
return json.loads(counts.decode("utf-8"))
result = self.get(
return self.get(
url="/service/{}/job/{}/notification_count".format(service_id, job_id)
)
redis_client.set(
f"notification-count-for-job-id-{service_id}-{job_id}",
json.dumps(result["count"]),
ex=30,
)
return result["count"]
)["count"]
notification_api_client = NotificationApiClient()

View File

@@ -1,8 +1,6 @@
import json
from datetime import datetime, timezone
from flask import current_app
from app.extensions import redis_client
from app.notify_client import NotifyAdminAPIClient, _attach_current_user, cache
@@ -83,13 +81,7 @@ class ServiceAPIClient(NotifyAdminAPIClient):
"""
Retrieve a list of live services data with contact names and notification counts.
"""
try:
return self.get("/service/live-services-data", params=params_dict)
except Exception as e:
current_app.logger.error(
f"Error getting live services data {str(e)}", exc_info=True
)
raise e
return self.get("/service/live-services-data", params=params_dict)
def get_active_services(self, params_dict=None):
"""
@@ -144,29 +136,19 @@ class ServiceAPIClient(NotifyAdminAPIClient):
@cache.delete("live-service-and-organization-counts")
def update_status(self, service_id, live):
try:
return self.update_service(
service_id,
message_limit=250000 if live else 50,
restricted=(not live),
go_live_at=str(datetime.utcnow()) if live else None,
)
except Exception as e:
current_app.logger.error(f"Error updating status {str(e)}", exc_info=True)
raise e
return self.update_service(
service_id,
message_limit=250000 if live else 50,
restricted=(not live),
go_live_at=str(datetime.utcnow()) if live else None,
)
@cache.delete("live-service-and-organization-counts")
def update_count_as_live(self, service_id, count_as_live):
try:
return self.update_service(
service_id,
count_as_live=count_as_live,
)
except Exception as e:
current_app.logger.error(
f"Error updating count as live {str(e)}", exc_info=True
)
raise e
return self.update_service(
service_id,
count_as_live=count_as_live,
)
# This method is not cached because it calls through to one which is
def update_service_with_properties(self, service_id, properties):
@@ -555,11 +537,6 @@ class ServiceAPIClient(NotifyAdminAPIClient):
"""
return self.get("/service/invite/redis/{0}".format(redis_key))
def get_service_message_ratio(self, service_id):
return self.get(
url="service/get-service-message-ratio?service_id={0}".format(service_id),
)
service_api_client = ServiceAPIClient()

View File

@@ -116,7 +116,7 @@ class UserApiClient(NotifyAdminAPIClient):
data["next"] = next_string
if code_type == "email":
data["email_auth_link_host"] = self.admin_url
endpoint = f"/user/{user_id}/{code_type}-code"
endpoint = f"/user/{user_id}/{code_type}-code"
current_app.logger.warn(hilite(f"Sending verify_code {code_type} to {user_id}"))
self.post(endpoint, data=data)

View File

@@ -28,17 +28,8 @@ def get_csv_upload(service_id, upload_id):
return get_s3_object(*get_csv_location(service_id, upload_id))
def remove_blank_lines(filedata):
# sometimes people upload files with hundreds of blank lines at the end
data = filedata["data"]
cleaned_data = "\r\n".join(line for line in data.splitlines() if line.strip())
filedata["data"] = cleaned_data
return filedata
def s3upload(service_id, filedata):
filedata = remove_blank_lines(filedata)
upload_id = str(uuid.uuid4())
bucket_name, file_location, access_key, secret_key, region = get_csv_location(
service_id, upload_id

View File

@@ -11,17 +11,13 @@
{% include "components/head.html" %}
</head>
<body class="usa-template__body {{ bodyClasses }}">
<div id="upload-status-live"
class="usa-sr-only"
aria-live="assertive"
tabindex="-1"
role="status">
</div>
<script nonce="{{ csp_nonce() }}">document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled');</script>
{% block bodyStart %}
{% block extra_javascripts_before_body %}
<noscript><iframe sandbox src="https://www.googletagmanager.com/ns.html?id=GTM-WX5NGWF"
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WX5NGWF"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
{% endblock %}
{% endblock %}
@@ -39,7 +35,7 @@
{% endblock %}
{% block main %}
<div class="grid-container minh-mobile">
<div class="grid-container">
{% block beforeContent %}
{% block backLink %}{% endblock %}
{% endblock %}
@@ -100,10 +96,10 @@
{% block footer %}
{% if current_service and current_service.research_mode %}
{% set meta_suffix = 'Built by the <a href="https://tts.gsa.gov/" class="usa-link">Technology Transformation Services</a><span id="research-mode" class="research-mode">research mode</span>' %}
{% set meta_suffix = 'Built by the <a href="https://www.gsa.gov/about-us/organization/federal-acquisition-service/technology-transformation-services/tts-solutions" class="usa-link">Technology Transformation Services</a><span id="research-mode" class="research-mode">research mode</span>' %}
{% else %}
{% set commit_hash = ", Latest version: " + config['COMMIT_HASH'] %}
{% set long_link = '<a href="https://tts.gsa.gov/" class="usa-link">Technology Transformation Services</a>' %}
{% set long_link = '<a href="https://www.gsa.gov/about-us/organization/federal-acquisition-service/technology-transformation-services/tts-solutions" class="usa-link">Technology Transformation Services</a>' %}
{% set meta_suffix = "Built by the " + long_link + commit_hash %}
{% endif %}
@@ -114,7 +110,7 @@
<dialog class="usa-modal" id="sessionTimer" aria-labelledby="sessionTimerHeading" aria-describedby="timeLeft">
<div class="usa-modal__content">
<div class="usa-modal__main">
<h2 class="usa-modal__heading font-body-lg" id="sessionTimerHeading">
<h2 class="usa-modal__heading" id="sessionTimerHeading">
Your session will end soon.
<span class="usa-sr-only">Please choose to extend your session or sign out. Your session will expire in 5 minutes or less.</span>
</h2>
@@ -131,7 +127,7 @@
</button>
</li>
<li class="usa-button-group__item">
<button type="button" class="text-center usa-button usa-button--unstyled padding-105" id="logOutTimer"
<button type="button" class="usa-button usa-button--unstyled padding-105 text-center" id="logOutTimer"
data-close-modal>
Sign out
</button>
@@ -149,8 +145,10 @@
{% block bodyEnd %}
{% block extra_javascripts %}
{% endblock %}
<!--[if gt IE 8]><!-->
<script type="text/javascript" src="{{ asset_url('javascripts/all.js') }}"></script>
<script src="{{ asset_url('js/uswds.min.js') }}"></script>
<script type="text/javascript" src="{{ asset_url('js/uswds.min.js') }}"></script>
<!--<![endif]-->
{% endblock %}
</body>
</html>

View File

@@ -4,6 +4,10 @@
{% macro banner(body, type=None, with_tick=False, delete_button=None, subhead=None, context=None, action=None, id=None, thing=None) %}
<div
class='banner{% if type %}-{{ type }}{% endif %}{% if with_tick %}-with-tick{% endif %}'
{% if type == 'dangerous' %}
role='group'
tabindex='-1'
{% endif %}
{% if id %}
id={{ id }}
{% endif %}

View File

@@ -1,3 +1,3 @@
{% macro usaBackLink(params) %}
{%- include "./template.njk" with context %}
{%- include "./template.njk" -%}
{% endmacro %}

View File

@@ -1,6 +1,4 @@
<nav class="usa-breadcrumb" aria-label="Breadcrumb">
<a href="{{ params.href.url or params.href or '#' }}" class="usa-link usa-back-link display-inline-flex {{ params.classes or '' }}"
{%- for attribute, value in params.attributes %} {{ attribute }}="{{ value }}" {% endfor %}>
{{- params.html | safe or params.href.text or 'Back' -}}
</a>
{%- for attribute, value in params.attributes %} {{ attribute }}="{{ value }}" {% endfor %}>{{ params.html | safe or params.href.text or 'Back' }}</a>
</nav>

View File

@@ -1,4 +1,5 @@
{# Determine type of element to use, if not explicitly set -#}
{% if params.element %}
{% set element = params.element | lower %}
{% else %}
@@ -9,35 +10,26 @@
{% endif %}
{% endif %}
{# Define common attributes to use across all element types -#}
{#- Define common attributes that we can use across all element types #}
{%- set commonAttributes %} class="usa-button{% if params.classes %} {{ params.classes }}{% endif %}{% if params.disabled %} usa-button--disabled{% endif %}"{% for attribute, value in params.attributes %} {{attribute}}="{{value}}"{% endfor %}{% endset %}
{# Define attributes for button/input -#}
{%- set buttonAttributes %}{% if params.name %} name="{{ params.name | trim }}"{% endif %} type="{{ params.type if params.type else 'submit' }}"{% if params.disabled %} disabled="disabled" aria-disabled="true"{% endif %}{% if params.preventDoubleClick %} data-prevent-double-click="true"{% endif %}{% endset %}
{#- Define common attributes we can use for both button and input types #}
{# Auto-append .dot-anim span for Send/Schedule buttons -#}
{%- set isSendOrSchedule = params.name and (params.name | lower == 'send' or params.name | lower == 'schedule') -%}
{%- set textContent %}
{%- set buttonAttributes %}{% if params.name %} name="{{ params.name }}"{% endif %} type="{{ params.type if params.type else 'submit' }}"{% if params.disabled %} disabled="disabled" aria-disabled="true"{% endif %}{% if params.preventDoubleClick %} data-prevent-double-click="true"{% endif %}{% endset %}
{#- Actually create a button... or a link! #}
{%- if element == 'a' %}
<a href="{{ params.href if params.href else '#' }}" role="button" draggable="false" {{- commonAttributes | safe }}>
{{ params.html | safe if params.html else params.text }}
{%- if isSendOrSchedule -%}<span class="dot-anim" aria-hidden="true"></span>{%- endif -%}
{%- endset %}
</a>
{# Render the appropriate element -#}
{% if element == 'a' %}
<a href="{{ params.href if params.href else '#' }}" role="button" draggable="false" {{ commonAttributes | safe }}>
{{ textContent | safe }}
</a>
{%- elseif element == 'button' %}
<button {%- if params.value %} value="{{ params.value }}"{% endif %} {{- buttonAttributes | safe }} {{- commonAttributes | safe }} {% if params.disabled %}disabled{% endif %}>
{{ params.html | safe if params.html else params.text }}
</button>
{% elseif element == 'button' %}
<button
{% if params.value %} value="{{ params.value }}"{% endif %}
{{ buttonAttributes | safe }}
{{ commonAttributes | safe }}
{% if params.disabled %}disabled{% endif %}
>
{{ textContent | safe }}
</button>
{% elseif element == 'input' %}
<input value="{{ params.text }}" {{ buttonAttributes | safe }} {{ commonAttributes | safe }}>
{% endif %}
{%- elseif element == 'input' %}
<input value="{{ params.text }}" {{- buttonAttributes | safe }} {{- commonAttributes | safe }}>
{%- endif %}

View File

@@ -2,10 +2,9 @@
{% from "../hint/macro.njk" import usaHint %}
{% from "../label/macro.njk" import usaLabel %}
{# Generate a consistent input ID #}
{% set inputId = params.id if params.id else params.label.text | default('unknown') | slugify %}
{#- a record of other elements that we need to associate with the input using
aria-describedby for example hints or error messages -#}
{% set describedBy = params.describedBy if params.describedBy else "" %}
<div class="usa-form-group {%- if params.errorMessage %} usa-form-group--error{% endif %} {%- if params.formGroup.classes %} {{ params.formGroup.classes }}{% endif %}">
{{ usaLabel({
html: params.label.html,
@@ -13,46 +12,35 @@
classes: params.label.classes,
isPageHeading: params.label.isPageHeading,
attributes: params.label.attributes,
for: inputId
for: params.id
}) | indent(2) | trim }}
{% if params.hint %}
{% set hintId = inputId + '-hint' %}
{% set describedBy = describedBy + ' ' + hintId if describedBy else hintId %}
{{ usaHint({
id: hintId,
classes: params.hint.classes,
attributes: params.hint.attributes,
html: params.hint.html,
text: params.hint.text
}) | indent(2) | trim }}
{% endif %}
{% if params.errorMessage %}
{% set errorId = inputId + '-error' %}
{% set describedBy = describedBy + ' ' + errorId if describedBy else errorId %}
{{ usaErrorMessage({
id: errorId,
classes: params.errorMessage.classes,
attributes: params.errorMessage.attributes,
html: params.errorMessage.html,
text: params.errorMessage.text,
visuallyHiddenText: params.errorMessage.visuallyHiddenText,
}) | indent(2) | trim }}
{% endif %}
<input
class="usa-input{%- if params.classes %} {{ params.classes }}{% endif %}{%- if params.errorMessage %} usa-input--error{% endif %}"
id="{{ inputId }}"
name="{{ params.name }}"
type="{{ params.type | default('text') }}"
{%- if params.value %} value="{{ params.value }}"{% endif %}
{%- if describedBy %} aria-describedby="{{ describedBy | trim }}"{% endif %}
{# Uncomment below if you want to use aria-labelledby too
aria-labelledby="{{ inputId }}-label" #}
{%- if params.autocomplete %} autocomplete="{{ params.autocomplete }}"{% endif %}
{%- if params.pattern %} pattern="{{ params.pattern }}"{% endif %}
{%- for attribute, value in params.attributes %} {{ attribute }}="{{ value }}"{% endfor -%}
{%- if params.required %} required{% endif %}
/>
{% if params.hint %}
{% set hintId = params.id + '-hint' %}
{% set describedBy = describedBy + ' ' + hintId if describedBy else hintId %}
{{ usaHint({
id: hintId,
classes: params.hint.classes,
attributes: params.hint.attributes,
html: params.hint.html,
text: params.hint.text
}) | indent(2) | trim }}
{% endif %}
{% if params.errorMessage %}
{% set errorId = params.id + '-error' %}
{% set describedBy = describedBy + ' ' + errorId if describedBy else errorId %}
{{ usaErrorMessage({
id: errorId,
classes: params.errorMessage.classes,
attributes: params.errorMessage.attributes,
html: params.errorMessage.html,
text: params.errorMessage.text,
visuallyHiddenText: params.errorMessage.visuallyHiddenText
}) | indent(2) | trim }}
{% endif %}
<input class="usa-input {%- if params.classes %} {{ params.classes }}{% endif %} {%- if params.errorMessage %} usa-input--error{% endif %}" id="{{ params.id }}" name="{{ params.name }}" type="{{ params.type | default('text') }}"
{%- if params.value %} value="{{ params.value}}"{% endif %}
{%- if describedBy %} aria-describedby="{{ describedBy }}"{% endif %}
{%- if params.autocomplete %} autocomplete="{{ params.autocomplete}}"{% endif %}
{%- if params.pattern %} pattern="{{ params.pattern }}"{% endif %}
{%- for attribute, value in params.attributes %} {{ attribute }}="{{ value }}"{% endfor -%}>
</div>

View File

@@ -20,28 +20,24 @@
</span>
{% endif %}
{% if field.errors and show_errors %}
<span class="error-message usa-error-message">
<span class="error-message">
{{ field.errors[0] }}
</span>
{% endif %}
</label>
{{ field(**{
'class': 'file-upload-field',
'id': field.name,
'accept': allowed_file_extensions|format_list_items('.{item}')|join(',')|e
}) }}
<button type="button"
class="usa-button file-upload-button"
data-module="upload-trigger"
data-file-input-id="{{ field.name }}">
{{ button_text }}
</button>
<label class="file-upload-button" for="{{ field.name }}">
{{ button_text }}
</label>
{% if alternate_link and alternate_link_text %}
<span class="file-upload-alternate-link">
or <a class="usa-link" href="{{ alternate_link }}">{{ alternate_link_text }}</a>
</span>
{% endif %}
<span class="file-upload-filename" aria-live="polite"></span>
<label class="file-upload-filename" for="{{ field.name }}"></label>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
{{ usaButton({ "text": "Submit", "classes": "file-upload-submit" }) }}
</form>

View File

@@ -5,8 +5,7 @@
class=None,
id=None,
module=None,
data_kwargs={},
data_force_focus=False
data_kwargs={}
) %}
<form
method="{{ method }}"
@@ -20,7 +19,6 @@
data-{{ key }}="{{ val }}"
{% endif %}
{% endfor %}
{% if data_force_focus %}data-force-focus="{{ data_force_focus }}"{% endif %}
novalidate
>
{{ caller() }}

View File

@@ -1,32 +1,50 @@
{% set is_about_page = request.path.startswith('/about') %}
{% set is_join_notify_page = request.path.startswith('/join-notify') %}
{% set is_contact_page = request.path.startswith('/contact') %}
{% set is_information_section = is_about_page or is_join_notify_page or is_contact_page %}
{% if current_user.is_authenticated %}
{% set navigation = [
{"href": url_for("main.show_accounts_or_dashboard"), "text": "Current service", "active": request.path.startswith('/accounts')},
{"href": url_for('main.get_started'), "text": "Using Notify", "active": request.path.startswith('/using-notify')},
{"href": url_for('main.support'), "text": "Contact us", "active": header_navigation.is_selected('support')}
] %}
{% if current_user.platform_admin %}
{% set navigation = navigation + [{"href": url_for('main.platform_admin_splash_page'), "text": "Platform admin", "active": header_navigation.is_selected('platform-admin')}] %}
{% else %}
{% set navigation = navigation + [{"href": url_for('main.user_profile'), "text": "User profile", "active": header_navigation.is_selected('user-profile')}] %}
{% endif %}
{% if current_service %}
{% if current_user.has_permissions('manage_service') %}
{% set secondaryNavigation = [
{"href": url_for('main.service_settings', service_id=current_service.id), "text": "Settings", "active": secondary_navigation.is_selected('settings')},
{"href": url_for('main.sign_out'), "text": "Sign out"}
] %}
{% else %}
{% set secondaryNavigation = [
{"href": url_for('main.sign_out'), "text": "Sign out"}
] %}
{% endif %}
{% else %}
{% set secondaryNavigation = [{"href": url_for('main.sign_out'), "text": "Sign out"}] %}
{% endif %}
{% set navigation = [
{"href": url_for("main.show_accounts_or_dashboard"), "text": "Current service", "active": request.path.startswith('/accounts')},
{"href": url_for('main.get_started'), "text": "Using Notify", "active": request.path.startswith('/using-notify')},
{"href": url_for('main.support'), "text": "Contact us", "active": header_navigation.is_selected('support')}
] %}
{% if current_user.platform_admin %}
{% set navigation = navigation + [{"href": url_for('main.platform_admin_splash_page'), "text": "Platform admin", "active": header_navigation.is_selected('platform-admin')}] %}
{% else %}
{% set navigation = navigation + [{"href": url_for('main.user_profile'), "text": "User profile", "active": header_navigation.is_selected('user-profile')}] %}
{% endif %}
{% if current_service %}
{% if current_user.has_permissions('manage_service') %}
{% set secondaryNavigation = [
{"href": url_for('main.service_settings', service_id=current_service.id), "text": "Settings", "active": secondary_navigation.is_selected('settings')},
{"href": url_for('main.sign_out'), "text": "Sign out"}
] %}
{% else %}
{% set secondaryNavigation = [
{"href": url_for('main.sign_out'), "text": "Sign out"}
] %}
{% endif %}
{% else %}
{% set secondaryNavigation = [{"href": url_for('main.sign_out'), "text": "Sign out"}] %}
{% endif %}
{% else %}
{% set navigation = [
{"href": url_for('main.about_notify'), "text": "About Notify", "active": is_about_page},
{"href": url_for('main.join_notify'), "text": "Join Notify", "active": is_join_notify_page},
{"href": url_for('main.contact'), "text": "Contact us", "active": is_contact_page}
] %}
{% endif %}
<header class="usa-header usa-header--extended">
<div class="usa-nav-container">
<div class="usa-navbar">
@@ -43,7 +61,16 @@
<button type="button" class="usa-menu-btn">Menu</button>
{% endif %}
</div>
{% if not current_user.is_authenticated and is_information_section%}
<div class="usa-nav__login">
<a class="usa-button usa-button login-button login-button--primary margin-right-2"
href="{{ initial_signin_url }}">Sign
in with <img src="{{ asset_url('images/logo-login.svg') }}" alt="Login.gov logo">
</a>
</div>
{% endif %}
</div>
</div>
<nav aria-label="Primary navigation" class="usa-nav">
<div class="usa-nav__inner">
@@ -78,6 +105,7 @@
{% endif %}
</ul>
</div>
</div>
</nav>
</div>

View File

@@ -3,7 +3,7 @@
show=False,
form=None,
label=None,
autofocus=True
autofocus=False
) %}
{%- set search_label = label or form.search.label.text %}
@@ -13,7 +13,7 @@
} %}
{% if autofocus %}
{% set _ = param_extensions.__setitem__("attributes", {"autofocus": "autofocus"}) %}
{% set x=param_extensions.__setitem__("attributes", {"data-module": "autofocus"}) %}
{% endif %}
{% if show %}

View File

@@ -32,7 +32,7 @@
<legend class="form-label {% if bold_legend %}bold{% endif %}">
{{ field.label.text }}
{% if field.errors %}
<span class="error-message usa-error-message" data-module="track-error" data-error-type="{{ field.errors[0] }}" data-error-label="{{ field.name }}">
<span class="error-message" data-module="track-error" data-error-type="{{ field.errors[0] }}" data-error-label="{{ field.name }}">
{{ field.errors[0] }}
</span>
{% endif %}

View File

@@ -52,7 +52,7 @@
</span>
{% endif %}
{% if field.errors %}
<span class="error-message usa-error-message" data-module="track-error" data-error-type="{{ field.errors[0] }}" data-error-label="{{ field.name }}">
<span class="error-message" data-module="track-error" data-error-type="{{ field.errors[0] }}" data-error-label="{{ field.name }}">
{{ field.errors[0] }}
</span>
{% endif %}

View File

@@ -5,6 +5,7 @@
highlight_placeholders=False,
autofocus=False,
autosize=False,
colour_preview=False,
help_link=None,
help_link_text=None,
width='2-3',
@@ -12,82 +13,60 @@
safe_error_message=False,
rows=8,
extra_form_group_classes='',
placeholder='',
input_id=None
placeholder=''
) %}
{% set field_id = kwargs.id if kwargs.id is defined else field.id %}
{% set described_by = '' %}
{% if hint %}{% set described_by = described_by + field_id ~ '-hint' %}{% endif %}
{% if field.errors %}
{% if described_by %}{% set described_by = described_by + ' ' %}{% endif %}
{% set described_by = described_by + field_id ~ '-error' %}
{% endif %}
<div
class="usa-form-group{% if field.errors %} usa-form-group--error{% endif %} {{ extra_form_group_classes }}"
class="form-group{% if field.errors %} form-group-error{% endif %} {{ extra_form_group_classes }}"
data-module="{% if autofocus %}autofocus{% elif colour_preview %}colour-preview{% endif %}"
>
<label class="usa-label" for="{{ field_id }}">
{{ label or field.label.text }}
{% if field.errors %}
<div class="usa-alert usa-alert--error edit-textbox-error-mt" role="alert">
<div class="usa-alert__body">
<h4 class="usa-alert__heading">Error message</h4>
<p class="usa-alert__text" data-module="track-error" data-error-type="{{ field.errors[0] }}" data-error-label="{{ field.name }}">
{% if not safe_error_message %}{{ field.errors[0] }}{% else %}{{ field.errors[0]|safe }}{% endif %}
</p>
</div>
</div>
{% endif %}
<label class="usa-label" for="{{ field.name }}">
{% if label %}
{{ label }}
{% else %}
{{ field.label.text }}
{% endif %}
</label>
{% if hint %}
<div class="usa-hint" id="{{ field_id }}-hint">
<div class="usa-hint">
{{ hint }}
</div>
{% endif %}
{% if field.errors %}
<span id="{{ field_id }}-error" class="error-message usa-error-message" data-module="track-error" data-error-type="{{ field.errors[0] }}" data-error-label="{{ field.name }}" tabindex="-1" aria-live="assertive" role="alert">
<span class="usa-sr-only">Error:</span>
{% if not safe_error_message %}
{{ field.errors[0] }}
{% else %}
{{ field.errors[0] | safe }}
{% endif %}
</span>
{% endif %}
{% if highlight_placeholders or autosize %}
{%
if highlight_placeholders or autosize
%}
{% set field_class = 'usa-textarea form-control-{} textbox-highlight-textbox'.format(width) %}
{% else %}
{% set field_class = 'usa-input' %}
{% set field_class = 'form-control-{} {}'.format(width, 'textbox-right-aligned' if suffix else '') %}
{% endif %}
{% set field_class = 'form-control ' ~ field_class ~ (' form-control-error' if field.errors else '') %}
{% if autosize or highlight_placeholders %}
<textarea
id="{{ field_id }}"
name="{{ field.name }}"
class="{{ field_class }}"
rows="{{ rows }}"
placeholder="{{ placeholder }}"
aria-describedby="{{ described_by.strip() }}"
{% if field.flags.required %}required{% endif %}
data-module="enhanced-textbox"
data-highlight-placeholders="true"
>{{ field._value() }}</textarea>
{% else %}
{% set input_type = 'tel' if 'phone' in field.label.text else 'text' %}
<input
id="{{ field_id }}"
name="{{ field.name }}"
type="{{ input_type }}"
class="{{ field_class }}"
value="{{ field._value() }}"
placeholder="{{ placeholder }}"
aria-describedby="{{ described_by.strip() }}"
{% if field.flags.required %}required{% endif %}
/>
{% endif %}
{%
set field_class = 'form-control ' + field_class + (
' form-control-error' if field.errors else ''
)
%}
{{ field(
class=field_class,
data_module='enhanced-textbox' if highlight_placeholders or autosize else '',
data_highlight_placeholders='true' if highlight_placeholders else 'false',
rows=rows|string,
placeholder=placeholder,
**kwargs
) }}
{% if suffix %}
<span>{{ suffix }}</span>
{% endif %}
{% if help_link and help_link_text %}
<p class="textbox-help-link">
<a class="usa-link" href="{{ help_link }}">{{ help_link_text }}</a>
<a class="usa-link" href='{{ help_link }}'>{{ help_link_text }}</a>
</p>
{% endif %}
</div>

View File

@@ -1,17 +0,0 @@
<section class="grid-container usa-section margin-top-5 margin-bottom-5">
<div class="grid-row flex-justify-center">
<div class="desktop:grid-col-3 tablet:grid-col-4 mobile:grid-col-12 flex-align-center">
<img
class="width-tablet tablet:width-full"
src="{{ asset_url('images/api-error.svg') }}"
alt="Mobile phone showing error screen"/>
</div>
<div class="desktop:grid-col-6 tablet:grid-col-12 padding-left-0 desktop:padding-left-5">
<h1 class="font-body-3xl line-height-sans-2 text-bold">
There's currently a technical issue.
</h1>
<p class="font-body-lg line-height-sans-2">Thank you for your patience while we work on it. Notify will be back soon.</p>
</div>
</div>
</div>
</section>

View File

@@ -21,11 +21,11 @@
<div class="ajax-block-container">
<p class='bottom-gutter'>
{% if not job.finished_processing %}
{% if job.still_processing or arrived_from_preview_page_url %}
{% if job.scheduled_for %}
<div class="usa-alert usa-alert--info">
<div class="usa-alert__body">
<h2 class="usa-alert__heading">Your {{ 'message has' if job.notification_count == 1 else 'messages have' }} been scheduled</h2>
<h2 class="usa-alert__heading">Your text has been scheduled</h2>
<p class="usa-alert__text">
{{ job.template_name }} - {{ current_service.name }} was scheduled on {{ job.scheduled_for|format_datetime_normal }} by {{ job.created_by.name }}
</p>
@@ -33,46 +33,18 @@
</div>
{{display_message_status}}
{% else %}
{% if job.processing_started %}
<div class="usa-alert usa-alert--success">
<div class="usa-alert__body">
<h2 class="usa-alert__heading">
Your {{ 'message is' if job.notification_count == 1 else 'messages are' }} sending
</h2>
<p class="usa-alert__text">
{{ job.template_name }} - {{ current_service.name }}
has been sending since {{job.processing_started| format_datetime_normal}} by {{ job.created_by.name }}
</p>
</div>
<div class="usa-alert usa-alert--success">
<div class="usa-alert__body">
<h2 class="usa-alert__heading">Your text has been sent</h2>
<p class="usa-alert__text">
{{ job.template_name }} - {{ current_service.name }} was sent on {% if job.processing_started %}
{{ job.processing_started|format_datetime_table }} {% else %}
{{ job.created_at|format_datetime_table }} {% endif %} by {{ job.created_by.name }}
</p>
</div>
{% else %}
<div class="usa-alert usa-alert--info">
<div class="usa-alert__body">
<h2 class="usa-alert__heading">
Your {{ 'message is' if job.notification_count == 1 else 'messages are' }} pending
</h2>
<p class="usa-alert__text">
{{ job.template_name }} - {{ current_service.name }}
has been pending since {{job.created_at|format_datetime_normal}} by {{ job.created_by.name }}
</p>
</div>
</div>
{% endif %}
</div>
{{display_message_status}}
{% endif %}
{% elif arrived_from_preview_page_url %}
<div class="usa-alert usa-alert--success">
<div class="usa-alert__body">
<h2 class="usa-alert__heading">
Your {{ 'message has' if job.notification_count == 1 else 'messages have' }} been sent
</h2>
<p class="usa-alert__text">
{{ job.template_name }} - {{ current_service.name }}
was sent on {{job.processing_started|format_datetime_normal}} by {{ job.created_by.name }}
</p>
</div>
</div>
{{display_message_status}}
{% endif %}
</p>
{% if job.status == 'sending limits exceeded'%}

View File

@@ -5,6 +5,10 @@
</h3>
<div id="message-length" class="usa-accordion__content usa-prose">
<p class="usa-body">
Each message sent to a recipient counts as one text. Keep track on your Dashboard of how many messages have sent and are remaining.
If your message is long then it will
cost more.
</p>
<p class="usa-body">
See <a class="usa-link" href="{{ url_for('.pricing') }}">pricing</a> for details.
</p>
</div>

View File

@@ -7,7 +7,7 @@
</h3>
<div id="m-a2" class="usa-accordion__content usa-prose">
<p class="usa-body">
Use double parenthesis and ?? to define optional content.
Use double brackets and ?? to define optional content.
</p>
<p class="bottom-gutter-1-3">
For example if you only want to show something to people who are under

View File

@@ -7,10 +7,11 @@
</h3>
<div id="personalization" class="usa-accordion__content usa-prose">
<p class="bottom-gutter-1-3">
Use double parenthesis to personalize your message:
Use double brackets to personalize your message:
</p>
{{ usaInsetText({
"text": "Hello ((first name)), your reference is ((ref number))",
"classes": ""})
}}
</div>

View File

@@ -4,7 +4,7 @@
Send a document by email
</h2>
<p class="usa-body">
Use double parenthesis to add a placeholder field to your template. This will contain a secure link to download the document.
Use double brackets to add a placeholder field to your template. This will contain a secure link to download the document.
</p>
{{ usaInsetText({
"text": "Download your document at: ((link_to_file))",

View File

@@ -16,10 +16,7 @@
<li>More effectively deliver program outcomes</li>
<li>Save administrative costs</li>
<li>Implement <a class="use-link usa-link--external"
href="https://digital.gov/resources/delivering-digital-first-public-experience/"
rel="noopener noreferrer"
target="_blank"
aria-label="21st Century IDEA (opens in a new tab)">21st Century
href="https://digital.gov/resources/delivering-digital-first-public-experience/" target="_blank">21st Century
IDEA</a> and other directives</li>
</ul>
<p>Notify.gov is an easy-to-use, web-based platform. It requires no technical expertise or system integration — users
@@ -69,6 +66,7 @@
</li>
{% endfor %}
</ul>
<p><a href="/join-notify">See if Notify is right for you</a></p>
<p>Notify.gov is a product of the <a href="/studio">Public Benefits Studio</a>, a product accelerator inside
the federal government. </p>
</section>

View File

@@ -22,26 +22,16 @@
</ul>
<p>
Notify.gov operates under a full three-year <a class="use-link usa-link--external"
href="https://digital.gov/resources/an-introduction-to-ato/"
target="_blank"
rel="noopener noreferrer"
aria-label="Authority-to-Operate (ATO) (opens in a new tab)">Authority-to-Operate (ATO)</a>. This
href="https://digital.gov/resources/an-introduction-to-ato/" target="_blank">Authority-to-Operate (ATO)</a>. This
federal security authorization process leverages security
controls provided by National Institute of Standards and Technology (NIST).
</p>
<p>
Our infrastructure runs on <a class="use-link usa-link--external"
href="https://www.cloud.gov/"
target="_blank"
rel="noopener noreferrer"
aria-label="cloud dot gov (opens in a new tab)">cloud.gov</a> and utilizes several
Our infrastructure runs on <a class="use-link usa-link--external" href="https://www.cloud.gov/"
target="_blank">cloud.gov</a> and utilizes several
services through Amazon Web
Services (AWS), including <a class="use-link usa-link--external"
href="https://aws.amazon.com/sns/"
rel="noopener noreferrer"
target="_blank"
aria-label="AWS SNS (opens in a new tab)">
Services (AWS), including <a class="use-link usa-link--external" href="https://aws.amazon.com/sns/" target="_blank">
AWS SNS </a> for sending SMS
messages.
</p>
@@ -63,22 +53,15 @@
</p>
<h2>Multi-Factor Authentication</h2>
<p>
Notify.gov uses <a class="use-link usa-link--external"
href="https://login.gov/what-is-login/"
rel="noopener noreferrer"
target="_blank"
aria-label="Login dot gov (opens in a new tab)">Login.gov</a> for enhanced security.
Notify.gov uses <a class="use-link usa-link--external" href="https://login.gov/what-is-login/"
target="_blank">Login.gov</a> for enhanced security.
Login.gov is an extra layer of security created by the government that uses multi-factor authentication and stronger
passwords to protect your account.
</p>
<p>
To access Notify.gov, users will use a Login.gov account associated with their agency (.gov) email with one of the
<a class="use-link usa-link--external"
href="https://login.gov/help/get-started/authentication-methods/"
rel="noopener noreferrer"
target="_blank"
aria-label="login dot gov multi-factor authentication methods (opens in a new tab)"
>multi-factor authentication
<a class="use-link usa-link--external" href="https://login.gov/help/get-started/authentication-methods/"
target="_blank">multi-factor authentication
methods</a> offered through Login.gov.
</p>
</section>

Some files were not shown because too many files have changed in this diff Show More