Commit Graph

216 Commits

Author SHA1 Message Date
Katie Smith
807db037eb Update flake8 from 3.8.4 to 4.0.1
And adds `noqa` to some non-errors which are being flagged.
2022-03-02 15:52:18 +00:00
Ben Thorner
d406829b6c Tweak SMS alert to make it worth the effort
Currently we alert if a service wastes £16 of SMS. It may cost us
around that amount just to deal with the alert, especially if the
service refuses to clean up their data.

This bumps the threshold to something more alarming, which should
make it more reasonable to suspend the service if we can show that
they've already wasted public money. £160 seems like a reasonable
compromise between have wasted vs could waste.

Note: we previously compromised on 1000 [1] down from 63K [2]. I
think we can afford to go a little bit higher.

[1]: https://github.com/alphagov/notifications-api/pull/3234
[2]: https://github.com/alphagov/notifications-api/pull/3221
2022-02-25 10:37:56 +00:00
Ben Thorner
76da31c32a Remove redundant conditional for letter branding
This is no longer used when creating a service [1]. It was likely
added at a migration point when Admin _did_ specify branding.

[1]: 50c3c3e10c/app/main/views/add_service.py (L15-L22)
2021-12-16 17:54:33 +00:00
Rebecca Law
35b20ba363 Correct the daily limits cache.
Last year we had an issue with the daily limit cache and the query that was populating it. As a result we have not been checking the daily limit properly. This PR should correct all that.

The daily limit cache is not being incremented in app.notifications.process_notifications.persist_notification, this method is and should always be the only method used to create a notification.
We increment the daily limit cache is redis is enabled (and it is always enabled for production) and the key type for the notification is team or normal.

We check if the daily limit is exceed in many places:
 - app.celery.tasks.process_job
 -  app.v2.notifications.post_notifications.post_notification
 - app.v2.notifications.post_notifications.post_precompiled_letter_notification
 - app.service.send_notification.send_one_off_notification
 - app.service.send_notification.send_pdf_letter_notification

If the daily limits cache is not found, set the cache to 0 with an expiry of 24 hours. The daily limit cache key is service_id-yyy-mm-dd-count, so each day a new cache is created.

The best thing about this PR is that the app.service_dao.fetch_todays_total_message_count query has been removed. This query was not performant and had been wrong for ages.
2021-06-22 16:15:36 +01:00
Rebecca Law
08bb5c657f Fix the query to get todays totals for a service.
The query had a group by on notification_type and notification_status, this not only slows the query down but is wrong. The query only looked at the first result, but this query would return as many rows as different notification types and status, meaning the results do not include the correct number.

Are we concerned that all status types are included. For example letters can be cancelled or have validation-failures which shouldn't be included in the daily limit check.
2021-06-14 15:29:21 +01:00
Rebecca Law
ed5e3b3d9c Removed the end date in the filter.
It's always going to be in the future anyway.
After some analysis the query does perform better without it.
I'll make a note to update other queries where we get todays
notification data to remove the end date filter in a separate PR.
2021-05-26 13:47:53 +01:00
Rebecca Law
782514a0f1 Update the dao_fetch_todays_stats_for_service query.
We have an index on Notifications(service_id, created_at), by updating the query to use between created_at rather than date(created_at) this query will use the index. Changing the query plan to use an index scan rather than a sequence scan, see query plans below.
This query is still rather slow but is improved by this update.

https://www.pivotaltracker.com/story/show/178263480

explain analyze
SELECT notification_type, notification_status, count(id)
FROM notifications
WHERE service_id = 'e791dbd4-09ea-413a-b773-ead8728ddb09'
AND date(created_at) = '2021-05-23'
AND key_type != 'test'
GROUP BY notification_type, notification_status;
                                                                                     QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize GroupAggregate  (cost=6326816.31..6326926.48 rows=24 width=22) (actual time=91666.805..91712.976 rows=10 loops=1)
   Group Key: notification_type, notification_status
   ->  Gather Merge  (cost=6326816.31..6326925.88 rows=48 width=22) (actual time=91666.712..91712.962 rows=30 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         ->  Partial GroupAggregate  (cost=6325816.28..6325920.31 rows=24 width=22) (actual time=91662.907..91707.027 rows=10 loops=3)
               Group Key: notification_type, notification_status
               ->  Sort  (cost=6325816.28..6325842.23 rows=10379 width=30) (actual time=91635.890..91676.225 rows=270884 loops=3)
                     Sort Key: notification_type, notification_status
                     Sort Method: external merge  Disk: 10584kB
                     Worker 0:  Sort Method: external merge  Disk: 10648kB
                     Worker 1:  Sort Method: external merge  Disk: 10696kB
                     ->  Parallel Seq Scan on notifications  (cost=0.00..6325123.93 rows=10379 width=30) (actual time=0.036..91513.985 rows=270884 loops=3)
                           Filter: (((key_type)::text <> 'test'::text) AND (service_id = 'e791dbd4-09ea-413a-b773-ead8728ddb09'::uuid) AND (date(created_at) = '2021-05-23'::date))
                           Rows Removed by Filter: 16191366
 Planning Time: 0.760 ms
 Execution Time: 91714.500 ms
(17 rows)

explain analyze
SELECT notification_type, notification_status, count(id)
FROM notifications
WHERE service_id = 'e791dbd4-09ea-413a-b773-ead8728ddb09'
AND created_at  >= '2021-05-22 23:00'
and created_at < '2021-05-23 23:00'
AND key_type != 'test'
GROUP BY notification_type, notification_status;
                                                                                                                       QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Finalize GroupAggregate  (cost=2114273.37..2114279.57 rows=24 width=22) (actual time=21032.076..21035.725 rows=10 loops=1)
   Group Key: notification_type, notification_status
   ->  Gather Merge  (cost=2114273.37..2114278.97 rows=48 width=22) (actual time=21032.056..21035.703 rows=30 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         ->  Sort  (cost=2113273.35..2113273.41 rows=24 width=22) (actual time=21029.261..21029.265 rows=10 loops=3)
               Sort Key: notification_type, notification_status
               Sort Method: quicksort  Memory: 25kB
               Worker 0:  Sort Method: quicksort  Memory: 25kB
               Worker 1:  Sort Method: quicksort  Memory: 25kB
               ->  Partial HashAggregate  (cost=2113272.56..2113272.80 rows=24 width=22) (actual time=21029.228..21029.230 rows=10 loops=3)
                     Group Key: notification_type, notification_status
                     ->  Parallel Bitmap Heap Scan on notifications  (cost=114455.71..2111695.14 rows=210322 width=30) (actual time=4983.790..20960.581 rows=271217 loops=3)
                           Recheck Cond: ((service_id = 'e791dbd4-09ea-413a-b773-ead8728ddb09'::uuid) AND (created_at >= '2021-05-22 23:00:00'::timestamp without time zone) AND (created_at < '2021-05-23 23:00:00'::timestamp without time zone))
                           Rows Removed by Index Recheck: 1456269
                           Filter: ((key_type)::text <> 'test'::text)
                           Heap Blocks: exact=12330 lossy=123418
                           ->  Bitmap Index Scan on ix_notifications_service_created_at  (cost=0.00..114329.51 rows=543116 width=0) (actual time=4973.139..4973.140 rows=813671 loops=1)
                                 Index Cond: ((service_id = 'e791dbd4-09ea-413a-b773-ead8728ddb09'::uuid) AND (created_at >= '2021-05-22 23:00:00'::timestamp without time zone) AND (created_at < '2021-05-23 23:00:00'::timestamp without time zone))
 Planning Time: 0.191 ms
 Execution Time: 21035.770 ms
(21 rows)
2021-05-25 08:00:24 +01:00
Ben Thorner
bd45d788c0 Increase warning threshold for SMS failures
Second attempt [1]. This increases the threshold so:

- It's a more substantial amount of money lost (£16).

- It's 10% of the minimum free allowance for a service.

- It's greater than the threshold we have for TV numbers (500).

Having a higher threshold for this alert will help prevent wasted
effort investigating more negligible failures, and reduces the
ambiguity of whether we should take action: we should.

[1]: https://github.com/alphagov/notifications-api/pull/3221
2021-05-05 17:54:43 +01:00
Rebecca Law
d4009ffc52 Rename database management functions.
Rename @transactional to @autocommit.
Rename nested_transaction to tranaction.
2021-04-19 10:56:00 +01:00
Rebecca Law
93908bacda New strategy for transaction management.
Introduce a contextmanger function to handle exceptions and nested
transactions. Using the nested_transaction will start a
nested transaction with `db.session.begin_nested`, once the nested
transaction is complete the commit will happen.
`@transactional` has been updated to commit unless in a nested
transaction.
2021-04-14 07:04:17 +01:00
Rebecca Law
cf35135605 Adding @nested_transactional for transactions that require more than one
db update/insert.

Using a savepoint for the multiple transactions allows us to rollback if
there is an error when executing the second db transaction.
However, this does add a bit of complexity. Developers need to manage
the db session when calling multiple nested tranactions.

Unit tests have been added to test this functionality and some end to
end tests have been done to make sure all transactions are rollback if
there is an exception while executing the transaction.
2021-04-14 07:03:57 +01:00
Ben Thorner
a91fde2fda Run auto-correct on app/ and tests/ 2021-03-12 11:45:45 +00:00
Rebecca Law
11d10d5293 Rename to performance_dashboard
Fix totals to return totals for all time rather than for date range.
Added more test data
2021-03-10 13:16:25 +00:00
Rebecca Law
b06850e611 Add an endpoint to return all the data required for the performance
platform page.
2021-03-05 09:59:03 +00:00
Chris Hill-Scott
88cd92b946 Revert "Remove the upload letters permission" 2020-10-23 15:14:37 +01:00
Chris Hill-Scott
182bfa7e10 Remove the upload letters permission
As of https://github.com/alphagov/notifications-admin/pull/3690 it’s no
longer referred to.
2020-10-20 11:46:11 +01:00
Rebecca Law
d9fd541ab7 Add international letters as a default permission when creating a new service 2020-08-11 15:59:09 +01:00
Pea Tyczynska
9c4205c7c6 Remove statsd decorators from dao functions
This done so that we do not use statsd on our http endpoint.
We decided we do not need metrics that this gave us. If we
change our minds, we will add Prometheus-friendly decorators
instead in the future.
2020-07-07 18:02:24 +01:00
Katie Smith
64cd8f39c2 Add the date to the service name and email_reply_to when archiving
This copies what we do to a user's email address when archiving the user
by prefixing it with `_archived_{date}`. We already prefixed the
service name and email_reply_to with `_archived`, but this didn't allow
a service with the same name to be archived more than once.
2020-05-22 09:37:45 +01:00
David McDonald
2f0b3a9636 Fix edge case in func test data purging for created_by_id
When running the purge command I found about 4 users who could not be
deleted because their user id was still referenced in the services table
as they had created the service yet they were not a member of that
service anymore.

I have fixed this by checking that if they are not a member but created
the service then we also delete the service for them.

Note, I've followed the previous convention of no tests for this
function. I've run it locally and executed the code path so there should
be no major flaws in the code. There is a small chance I wasn't able to
exactly replicate the state that existed in preview on my local but
hopefully it was close enough to be accurate.
2020-05-18 10:30:28 +01:00
Leo Hemsted
885f3122bd fix purge functional test data task
* it doesn't delete service email reply to or letter contacts, or
  contact lists. I don't think the contact lists will ever be an issue
  but it doesn't hurt to add it to the list of things to remove.
* it doesn't remove users from organisations before deleting the users

there may be more tables that link to Service that should be deleted,
but for now just add these ones that I could spot.
2020-03-30 17:45:29 +01:00
Chris Hill-Scott
b3c9680487 Give new services the upload letters permission
This will switch on this feature for new services.

After this we will:
- give existing services this permission with a database migration
- remove this permission from the codebase entirely so that everyone has
  this feature and can’t switch it off
2020-02-25 14:03:43 +00:00
David McDonald
3a0aece6a1 Up threshold for sms to telephone numbers
We were just ignoring the errors and our users were not fixing things.

Given that 500 texts cost approx £8 it's not the end of the world.

In the long run we may decide to just stop letting people try and send
messages to TV numbers but this is a quick fix to stop emails coming in
which we ignore.
2020-01-17 13:26:20 +00:00
Pea Tyczynska
1b7b26bf24 Query directly for services with high failure rate 2019-12-06 16:57:56 +00:00
Pea Tyczynska
cfbb080f57 Simplify failure rate by building separate query 2019-12-06 16:57:44 +00:00
Pea Tyczynska
53efd87e28 Check for services sending sms messages to tv numbers 2019-12-06 16:57:34 +00:00
Chris Hill-Scott
8d9038c3e9 Give GP practices NHS branding by default
Previously we were doing it based on their email address. This will also
apply it if they self-select as a GP surgery, even if they don’t have an
NHS email address.
2019-08-28 15:33:00 +01:00
Pea (Malgorzata Tyczynska)
7e43b5bbc3 Merge pull request #2587 from alphagov/find_services_by_partial_name
Find services by partial name
2019-08-16 11:21:19 +01:00
Rebecca Law
fdee6cbfb2 As per PR comments:
- Remove Organisation.services
- added backref='services' to Services.organisation relationship and removed redundant foreign_keys argument.
2019-08-14 13:23:20 +01:00
Rebecca Law
55dc7184cc Add organisation_id to Service.
This is the second commit in the series to add organisation_id to Service.
- Data migration to update services.organisation_id from data in organisation_to_service
 (The rollback will lose any updates to organisation unless the script is updated to set organistion_to_service from service.organisation_id )
- Update Service.organisation relationship to a ForeignKey relationship to Organisation.
- Update Organisation.services to a backref relationship to Service.
2019-08-13 17:25:30 +01:00
Pea Tyczynska
52a1316a7e Find services by partial name 2019-08-13 17:20:37 +01:00
Rebecca Law
12f305bf86 - Migration to add Service.organisation_id
- Add oranisation_id to Service data model.
- Update methods to create service and associate service to organisation to set the organisation_id on the Service.
- Create the missing test, if the service user email matches a domain for an organisation then associate the service to the organisation and inherit crown and organisation_type from the organisation.
2019-08-12 16:03:02 +01:00
Pea Tyczynska
5b256fa64e Migrate all orgs and services onto new organisation types
Remove all mentions of generic 'nhs' organisation type.
2019-07-22 14:58:41 +01:00
Pea Tyczynska
edda816ffa Temporarily add generic 'nhs' 2019-07-19 15:13:24 +01:00
Pea Tyczynska
d89ef0594f nhs_central is crown org and also we do not update org type while
updating service anymore.
2019-07-18 17:05:24 +01:00
Pea Tyczynska
9dfc550f46 Add org types table 2019-07-18 17:05:22 +01:00
Leo Hemsted
7db2b031a2 add free_sms_fragment_limit to platform admin billing report
a little complicated because the free_sms_fragment_limit comes from
the annual_billing table. This relies on there always being at least
one row for every service on annual billing - I checked on prod and
that is true.

Join to the annual billing table, then join to a subquery getting the
latest year for that service to extract only the most recent year.
2019-06-04 11:34:10 +01:00
Leo Hemsted
968d94d350 clean up dao_fetch_live_services
a bit of DRY - use the column definitions to determine what goes into
the dict, and use a `next` iterator rather than a while loop to find
the existing service row. Take advantage of dict mutability to avoid
needing to refer to the list by index.

Also change the tests so if there's an error, the diff is slightly
more readable. But not much
2019-06-04 11:33:19 +01:00
Pea Tyczynska
689ff57c32 Add organisation type to live services report 2019-05-03 15:09:54 +01:00
Pea Tyczynska
e7add1c729 Only show live services in live services query 2019-05-02 11:15:53 +01:00
Pea Tyczynska
83f39730d0 Order results by live date ascending order 2019-05-01 15:58:08 +01:00
Pea Tyczynska
382d1de857 Only count_as_live services
Add comments to live services dao test for context
2019-05-01 15:57:59 +01:00
Pea Tyczynska
c15d7878fc Only include ft_billing data for current financial year
Test get_live_services_data endpoint

Expand dao_fetch_live_services_data test with more ft_billing records
2019-05-01 15:57:45 +01:00
Pea Tyczynska
669db0b4ca New db query that returns data about live services
This data includes service and org name, consent to research,
contact details and both intended and factual notifications
volumes by notification type.

This query was created to get data for a csv report for our
platform admins.
2019-05-01 15:57:20 +01:00
Chris Hill-Scott
96bb9e19f9 Merge pull request #2385 from alphagov/raise-if-fail-to-write-history
Raise exception if history can’t be written
2019-04-17 11:17:49 +01:00
Chris Hill-Scott
c6447c111d Don’t let admin specify branding for new service
It doesn’t need to because the API code works it all out now by looking
at the organisation.
2019-04-12 16:42:50 +01:00
Chris Hill-Scott
a39ed098b8 Merge pull request #2442 from alphagov/default-branding-for-nhs-users
Set default branding for NHS services
2019-04-12 15:29:30 +01:00
Chris Hill-Scott
6bfd999de2 Add method to count of live services and orgs
So that we don’t have to update the home page manually any more.
2019-04-11 13:54:43 +01:00
Chris Hill-Scott
5a7de22f55 Set default branding for NHS services
The NHS is a special case because it’s not one organisation, but it does
have one consistent brand. So anyone working for an NHS organisation
should have their default branding set when they create a service, even
if we know nothing about their specific organisation.
2019-04-08 10:27:26 +01:00
Chris Hill-Scott
eeb90bed57 Do all version table writes in one commit
The behaviour of stacking the version decorators does not work as
expected.

What you would expect to happen is that each decorator causes a history
row to be written for its respective model object.

What actually happens is that the first decorator adds history records
to the database session, but then causes the database session to commit.
This means that subsequent uses of this decorator find a clean session,
and therefore no changes to copy to their respective history tables.

This commit changes the intended use of the decorator so that it is only
used once per function, and accepts multiple definitions of what to
record history for. This way it can record everything that needs to go
into the history before doing anything that would risk flushing the
session.
2019-04-05 16:11:46 +01:00