Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions commcare_connect/opportunity/PAYMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ The claim limit row is locked with `select_for_update()` while this runs, so con

Limits are counted **per deliver unit** and exclude `over_limit` and `trial` visits. Only auto-approved visits get `review_status=agree` here. Every other visit needs a PM to agree before it can be paid.

The limit check runs only when the form arrives, so raising a limit later leaves earlier visits `over_limit`. An NM can approve them from the visit list's All tab or the visit status import. For many visits, or on opportunities with automatic visit verification (which have no PM review), run `./manage.py approve_over_limit_visits`. It is a dry run unless given `--commit`, and `--agree` marks the visits agreed so that they accrue payment without a PM.

### CompletedWork

One row per `(opportunity_access, entity_id, payment_unit)`: everything a worker delivered for one beneficiary under one payment unit. It is the unit that gets approved, accrues payment, and is invoiced.
Expand Down Expand Up @@ -216,7 +218,7 @@ Accrual is cached, not calculated on read, so every action that can change a vis
flowchart LR
subgraph Triggers
T1[Form received]
T2[Bulk approve visits]
T2[Bulk approve visits /<br/>approve_over_limit_visits command]
T3[Reject visits]
T4[PM review agree/disagree]
T5[Visit status /<br/>review status imports]
Expand All @@ -235,14 +237,14 @@ flowchart LR
B2 --> U
```

| Trigger | Entry point | Works recalculated |
| ------------------------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| Form received | `process_deliver_unit` → `update_payment_accrued_for_user(incremental=True)` | Works not yet approved with`saved_approved_count=0`, plus the work just touched |
| Bulk approve visits | `views.approve_visits` → `update_payment_accrued(incremental=True)` | Works not yet approved with`saved_approved_count=0` |
| Reject visits | `views.reject_visits` → `update_payment_accrued()` | All of the worker's works |
| PM review | `views.user_visit_review` → `update_payment_accrued()` | All of the worker's works |
| Visit or review status imports | `visit_import.*` → `tasks.bulk_update_payment_accrued` (Celery) | All works except`rejected` |
| Nightly,`auto_approve_payments` only | `tasks.bulk_approve_completed_work` (active, not-ended opportunities) | All works except`rejected` |
| Trigger | Entry point | Works recalculated |
| -------------------------------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| Form received | `process_deliver_unit` → `update_payment_accrued_for_user(incremental=True)` | Works not yet approved with`saved_approved_count=0`, plus the work just touched |
| Bulk approve visits, `approve_over_limit_visits` command | `utils.visit_approval.approve_user_visits` → `update_payment_accrued(incremental=True)` | Works not yet approved with`saved_approved_count=0` |
| Reject visits | `views.reject_visits` → `update_payment_accrued()` | All of the worker's works |
| PM review | `views.user_visit_review` → `update_payment_accrued()` | All of the worker's works |
| Visit or review status imports | `visit_import.*` → `tasks.bulk_update_payment_accrued` (Celery) | All works except`rejected` |
| Nightly,`auto_approve_payments` only | `tasks.bulk_approve_completed_work` (active, not-ended opportunities) | All works except`rejected` |

**Incremental** skips works that are already processed (approved, or with `saved_approved_count > 0`), so only works still waiting on approval are recalculated. **Full** recalculates every one of the worker's works.

Expand Down
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."))
Comment on lines +35 to +53

Copy link
Copy Markdown

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


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

Copy link
Copy Markdown

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._report has 6 arguments, max arguments = 4

Suppress


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."
)
134 changes: 134 additions & 0 deletions commcare_connect/opportunity/tests/test_approve_over_limit_visits.py
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
69 changes: 69 additions & 0 deletions commcare_connect/opportunity/utils/visit_approval.py
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ New issue: Complex Method
approve_user_visits has a cyclomatic complexity of 11, threshold = 9

Suppress



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
Loading
Loading