Repository navigation
Command to approve over limit visits #1856
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| from django.core.management import BaseCommand, CommandError | ||
| from django.db import transaction | ||
| from django.http import Http404 | ||
|
|
||
| from commcare_connect.opportunity.models import Opportunity, UserVisit, VisitValidationStatus | ||
| from commcare_connect.opportunity.utils.visit_approval import approvable_visits, approve_user_visits | ||
| from commcare_connect.utils.db import get_object_by_uuid_or_int | ||
|
|
||
| # Saved on every flagged visit this approves. Edit it to describe the case before running the command. | ||
| JUSTIFICATION = ( | ||
| "Marked over limit before the worker's visit limit was raised. Checked against the submission and approved." | ||
| ) | ||
| JUSTIFICATION_MAX_LENGTH = UserVisit._meta.get_field("justification").max_length | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = ( | ||
| "Approve an opportunity's over-limit visits as a Network Manager would, recalculating payment accrual " | ||
| "and work area status. Dry run unless --commit is given." | ||
| ) | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument("--opportunity", required=True, help="Opportunity ID or opportunity_id UUID.") | ||
| parser.add_argument( | ||
| "--visit-ids", nargs="+", type=int, required=True, help="UserVisit IDs (primary keys) to approve." | ||
| ) | ||
| parser.add_argument( | ||
| "--agree", | ||
| action="store_true", | ||
| help="Also mark the visits agreed, as an auto-approved visit is. Only for opportunities with automatic " | ||
| "visit verification, which have no PM review; flagged visits are skipped.", | ||
| ) | ||
| parser.add_argument("--commit", action="store_true", help="Write the changes. Without it nothing is saved.") | ||
|
|
||
| def handle(self, *args, opportunity, visit_ids, agree, commit, **options): | ||
| _check_justification() | ||
| opportunity = _get_opportunity(opportunity) | ||
| _check_agree(opportunity, agree) | ||
|
|
||
| candidates = list(approvable_visits(opportunity, visit_ids)) | ||
| over_limit = [visit for visit in candidates if visit.status == VisitValidationStatus.over_limit] | ||
| flagged_skipped = [visit for visit in over_limit if visit.flagged] if agree else [] | ||
| to_approve = [visit for visit in over_limit if visit not in flagged_skipped] | ||
|
|
||
| self._report(opportunity, visit_ids, candidates, over_limit, flagged_skipped, to_approve) | ||
| self._warn_about_payment(opportunity, agree) | ||
| if not commit: | ||
| self.stdout.write(self.style.WARNING("Dry run: nothing was saved. Rerun with --commit to approve.")) | ||
| return | ||
|
|
||
| with transaction.atomic(): | ||
| approved_count = approve_user_visits(opportunity, to_approve, JUSTIFICATION, agree=agree) | ||
| self.stdout.write(self.style.SUCCESS(f"Approved {approved_count} visits.")) | ||
|
|
||
| def _report(self, opportunity, visit_ids, candidates, over_limit, flagged_skipped, to_approve): | ||
| not_over_limit = [visit for visit in candidates if visit not in over_limit] | ||
| candidate_ids = {visit.id for visit in candidates} | ||
| not_approvable_ids = [visit_id for visit_id in visit_ids if visit_id not in candidate_ids] | ||
|
|
||
| self.stdout.write(f"Opportunity {opportunity.pk} ({opportunity.name})") | ||
| self._write_ids("Will approve", to_approve) | ||
| self._write_ids(" of which flagged, saved with the justification", [v for v in to_approve if v.flagged]) | ||
| self.stdout.write(f"Justification: {JUSTIFICATION}") | ||
| self._write_ids("Skipped, flagged (--agree leaves them for review)", flagged_skipped) | ||
| self._write_ids("Skipped, not over limit", not_over_limit) | ||
| self.stdout.write( | ||
| f"Skipped, not in this opportunity or already approved: {len(not_approvable_ids)} {not_approvable_ids}" | ||
| ) | ||
|
Comment on lines
+55
to
+68
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ❌ New issue: Excess Number of Function Arguments |
||
|
|
||
| def _warn_about_payment(self, opportunity, agree): | ||
| if opportunity.automatic_visit_verification and not agree: | ||
| self.stdout.write( | ||
| self.style.WARNING( | ||
| "This opportunity has automatic visit verification, so no PM can agree to these visits and " | ||
| "they will not accrue payment. Pass --agree to mark them agreed." | ||
| ) | ||
| ) | ||
| if not opportunity.auto_approve_payments: | ||
| self.stdout.write( | ||
| self.style.WARNING("auto_approve_payments is off: approving these visits will not accrue payment.") | ||
| ) | ||
|
|
||
| def _write_ids(self, label, visits): | ||
| self.stdout.write(f"{label}: {len(visits)} {sorted(visit.id for visit in visits)}") | ||
|
|
||
|
|
||
| def _get_opportunity(identifier: str) -> Opportunity: | ||
| try: | ||
| return get_object_by_uuid_or_int(Opportunity.objects.all(), identifier, uuid_field="opportunity_id") | ||
| except Http404: | ||
| raise CommandError(f"Opportunity {identifier} does not exist.") | ||
|
|
||
|
|
||
| def _check_justification(): | ||
| if not JUSTIFICATION or len(JUSTIFICATION) > JUSTIFICATION_MAX_LENGTH: | ||
| raise CommandError(f"JUSTIFICATION must be 1 to {JUSTIFICATION_MAX_LENGTH} characters long.") | ||
|
|
||
|
|
||
| def _check_agree(opportunity: Opportunity, agree: bool): | ||
| if agree and not opportunity.automatic_visit_verification: | ||
| raise CommandError( | ||
| "--agree is only for opportunities with automatic visit verification. On this opportunity the PM " | ||
| "agrees to approved visits through review." | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| import pytest | ||
| from django.core.management import CommandError, call_command | ||
|
|
||
| from commcare_connect.microplanning.models import WorkAreaStatus | ||
| from commcare_connect.microplanning.tests.factories import WorkAreaFactory | ||
| from commcare_connect.opportunity.management.commands import approve_over_limit_visits | ||
| from commcare_connect.opportunity.models import CompletedWorkStatus, VisitReviewStatus, VisitValidationStatus | ||
| from commcare_connect.opportunity.tests.factories import ( | ||
| CompletedWorkFactory, | ||
| DeliverUnitFactory, | ||
| OpportunityAccessFactory, | ||
| PaymentUnitFactory, | ||
| UserVisitFactory, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def access(opportunity): | ||
| return OpportunityAccessFactory(opportunity=opportunity) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def over_limit_visit(opportunity, access): | ||
| payment_unit = PaymentUnitFactory(opportunity=opportunity) | ||
| completed_work = CompletedWorkFactory( | ||
| opportunity_access=access, payment_unit=payment_unit, status=CompletedWorkStatus.over_limit | ||
| ) | ||
| return UserVisitFactory( | ||
| opportunity=opportunity, | ||
| user=access.user, | ||
| opportunity_access=access, | ||
| deliver_unit=DeliverUnitFactory(payment_unit=payment_unit), | ||
| completed_work=completed_work, | ||
| status=VisitValidationStatus.over_limit, | ||
| review_status=VisitReviewStatus.pending, | ||
| flagged=False, | ||
| ) | ||
|
|
||
|
|
||
| def _approve(opportunity, visits, *args): | ||
| call_command( | ||
| "approve_over_limit_visits", | ||
| "--opportunity", | ||
| str(opportunity.opportunity_id), | ||
| "--visit-ids", | ||
| *[str(visit.id) for visit in visits], | ||
| *args, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_dry_run_saves_nothing(opportunity, over_limit_visit): | ||
| _approve(opportunity, [over_limit_visit]) | ||
|
|
||
| over_limit_visit.refresh_from_db() | ||
| assert over_limit_visit.status == VisitValidationStatus.over_limit | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_approves_only_over_limit_visits_for_pm_review(opportunity, access, over_limit_visit): | ||
| work_area = WorkAreaFactory( | ||
| opportunity=opportunity, opportunity_access=access, status=WorkAreaStatus.VISITED, expected_visit_count=1 | ||
| ) | ||
| over_limit_visit.work_area = work_area | ||
| over_limit_visit.save() | ||
| pending_visit = UserVisitFactory( | ||
| opportunity=opportunity, opportunity_access=access, status=VisitValidationStatus.pending | ||
| ) | ||
| other_opportunity_visit = UserVisitFactory(status=VisitValidationStatus.over_limit) | ||
|
|
||
| _approve(opportunity, [over_limit_visit, pending_visit, other_opportunity_visit], "--commit") | ||
|
|
||
| over_limit_visit.refresh_from_db() | ||
| assert over_limit_visit.status == VisitValidationStatus.approved | ||
| assert over_limit_visit.review_status == VisitReviewStatus.pending | ||
| assert over_limit_visit.review_created_on | ||
| work_area.refresh_from_db() | ||
| assert work_area.status == WorkAreaStatus.EXPECTED_VISIT_REACHED | ||
| pending_visit.refresh_from_db() | ||
| assert pending_visit.status == VisitValidationStatus.pending | ||
| other_opportunity_visit.refresh_from_db() | ||
| assert other_opportunity_visit.status == VisitValidationStatus.over_limit | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_flagged_visit_gets_justification(opportunity, over_limit_visit): | ||
| over_limit_visit.flagged = True | ||
| over_limit_visit.save() | ||
|
|
||
| _approve(opportunity, [over_limit_visit], "--commit") | ||
|
|
||
| over_limit_visit.refresh_from_db() | ||
| assert over_limit_visit.status == VisitValidationStatus.approved | ||
| assert over_limit_visit.justification == approve_over_limit_visits.JUSTIFICATION | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| @pytest.mark.parametrize("justification", ["", "x" * 301]) | ||
| def test_unusable_justification_saves_nothing(monkeypatch, opportunity, over_limit_visit, justification): | ||
| monkeypatch.setattr(approve_over_limit_visits, "JUSTIFICATION", justification) | ||
|
|
||
| with pytest.raises(CommandError, match="JUSTIFICATION"): | ||
| _approve(opportunity, [over_limit_visit], "--commit") | ||
|
|
||
| over_limit_visit.refresh_from_db() | ||
| assert over_limit_visit.status == VisitValidationStatus.over_limit | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_agree_refused_on_manual_verification(opportunity, over_limit_visit): | ||
| with pytest.raises(CommandError, match="automatic visit verification"): | ||
| _approve(opportunity, [over_limit_visit], "--commit", "--agree") | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_agree_approves_unflagged_visits_and_accrues_payment(opportunity, access, over_limit_visit): | ||
| opportunity.automatic_visit_verification = True | ||
| opportunity.auto_approve_payments = True | ||
| opportunity.save() | ||
| flagged_visit = UserVisitFactory( | ||
| opportunity=opportunity, opportunity_access=access, status=VisitValidationStatus.over_limit, flagged=True | ||
| ) | ||
|
|
||
| _approve(opportunity, [over_limit_visit, flagged_visit], "--commit", "--agree") | ||
|
|
||
| over_limit_visit.refresh_from_db() | ||
| assert over_limit_visit.status == VisitValidationStatus.approved | ||
| assert over_limit_visit.review_status == VisitReviewStatus.agree | ||
| over_limit_visit.completed_work.refresh_from_db() | ||
| assert over_limit_visit.completed_work.status == CompletedWorkStatus.approved | ||
| access.refresh_from_db() | ||
| assert access.payment_accrued == over_limit_visit.completed_work.payment_unit.amount | ||
| flagged_visit.refresh_from_db() | ||
| assert flagged_visit.status == VisitValidationStatus.over_limit |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| from django.db.models import Q, QuerySet | ||
| from django.utils.timezone import now | ||
|
|
||
| from commcare_connect.opportunity.models import Opportunity, UserVisit, VisitReviewStatus, VisitValidationStatus | ||
| from commcare_connect.opportunity.visit_import import update_payment_accrued | ||
|
|
||
|
|
||
| class MissingJustificationError(Exception): | ||
| pass | ||
|
|
||
|
|
||
| def approvable_visits(opportunity: Opportunity, visit_ids) -> QuerySet[UserVisit]: | ||
| """The opportunity's visits among visit_ids that are not approved yet, or that a PM disagreed with.""" | ||
| return ( | ||
| UserVisit.objects.filter(id__in=visit_ids, opportunity=opportunity) | ||
| .filter(~Q(status=VisitValidationStatus.approved) | Q(review_status=VisitReviewStatus.disagree)) | ||
| .select_related("work_area", "work_area__opportunity_access") | ||
| ) | ||
|
|
||
|
|
||
| def approve_user_visits( | ||
| opportunity: Opportunity, visits, justification: str | None = None, agree: bool = False | ||
| ) -> int: | ||
| """Approve the visits, then recalculate the workers' accrual and the visits' work areas. | ||
|
|
||
| The visits go to PM review, and one the PM disagreed with goes back to pending review. With agree, | ||
| they are marked agreed instead, as form processing does for an auto-approved visit. Flagged visits | ||
| get the justification, and MissingJustificationError is raised before anything is written if one of | ||
| them needs it and none is given. Returns the number of visits updated. | ||
| """ | ||
| visits = list(visits) | ||
| if not justification and any(visit.flagged for visit in visits): | ||
| raise MissingJustificationError("Justification is mandatory for flagged visits.") | ||
|
|
||
| approved_on = now() | ||
| for visit in visits: | ||
| _approve(visit, approved_on, justification) | ||
| if agree: | ||
| visit.review_status = VisitReviewStatus.agree | ||
| visit.review_status_modified_date = approved_on | ||
|
|
||
| approved_count = UserVisit.objects.bulk_update( | ||
| visits, | ||
| [ | ||
| "status", | ||
| "status_modified_date", | ||
| "review_created_on", | ||
| "review_status", | ||
| "review_status_modified_date", | ||
| "justification", | ||
| ], | ||
| batch_size=100, | ||
| ) | ||
| user_ids = list({visit.user_id for visit in visits}) | ||
| if user_ids: | ||
| update_payment_accrued(opportunity=opportunity, users=user_ids, incremental=True) | ||
| for work_area in {visit.work_area for visit in visits if visit.work_area}: | ||
| work_area.update_status() | ||
| return approved_count | ||
|
Comment on lines
+21
to
+59
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ❌ New issue: Complex Method |
||
|
|
||
|
|
||
| def _approve(visit: UserVisit, approved_on, justification): | ||
| visit.status = VisitValidationStatus.approved | ||
| visit.review_created_on = approved_on | ||
| if visit.review_status == VisitReviewStatus.disagree: | ||
| visit.review_status = VisitReviewStatus.pending | ||
| visit.review_status_modified_date = approved_on | ||
| if visit.flagged: | ||
| visit.justification = justification | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
❌ New issue: Excess Number of Function Arguments
Command.handle has 6 arguments, max arguments = 4
Suppress