Skip to content
Open
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
22 changes: 22 additions & 0 deletions spp_programs/models/cycle_membership.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ class SPPCycleMembership(models.Model):
partner_id = fields.Many2one("res.partner", "Registrant", help="A beneficiary", required=True, index=True)
cycle_id = fields.Many2one("spp.cycle", "Cycle", help="A cycle", required=True, index=True)
enrollment_date = fields.Date(default=lambda self: fields.Datetime.now())

compliance_criteria = fields.Char(
string="Compliance Criteria",
compute="_compute_compliance_criteria",
help="The compliance CEL expression from the program that this registrant failed to meet",
)

state = fields.Selection(
selection=[
("draft", "Draft"),
Expand All @@ -29,6 +36,21 @@ class SPPCycleMembership(models.Model):
copy=False,
)

def _compute_compliance_criteria(self):
"""Show the compliance CEL expression from the program when non-compliant."""
for rec in self:
if rec.state == "non_compliant" and rec.cycle_id and rec.cycle_id.program_id:
program = rec.cycle_id.program_id
for wrapper in program.compliance_manager_ids:
concrete = wrapper.manager_ref_id
if hasattr(concrete, "compliance_cel_expression") and concrete.compliance_cel_expression:
rec.compliance_criteria = concrete.compliance_cel_expression
break
else:
rec.compliance_criteria = False
else:
rec.compliance_criteria = False

def _compute_display_name(self):
res = super()._compute_display_name()
# Prefetch cycle_id and partner_id to avoid N+1 queries in loop
Expand Down
50 changes: 50 additions & 0 deletions spp_programs/models/program_membership.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,56 @@ def _compute_duplicate_reason(self):
else:
rec.duplicate_reason = False

latest_cycle_state = fields.Selection(
selection=[
("draft", "Draft"),
("enrolled", "Enrolled"),
("paused", "Paused"),
("exited", "Exited"),
("not_eligible", "Not Eligible"),
("non_compliant", "Non-Compliant"),
],
string="Cycle Status",
compute="_compute_latest_cycle_state",
help="State of the most recent cycle membership for this registrant in this program",
)

def _compute_latest_cycle_state(self):
"""Get the latest cycle membership state per registrant+program."""
if not self:
return

for rec in self:
rec.latest_cycle_state = False

# Batch query: find latest cycle membership for each program membership
CycleMembership = self.env["spp.cycle.membership"]
for rec in self:
cycle_mem = CycleMembership.search(
[
("partner_id", "=", rec.partner_id.id),
("cycle_id.program_id", "=", rec.program_id.id),
],
order="id desc",
limit=1,
)
if cycle_mem:
rec.latest_cycle_state = cycle_mem.state
Comment on lines +101 to +121
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The current implementation of _compute_latest_cycle_state performs a search() inside a loop, which leads to an N+1 query pattern. This will significantly degrade performance when viewing a list of program memberships (e.g., on the registrant form). It is highly recommended to use _read_group to fetch the latest cycle membership IDs for all records in the batch in a single query.

    def _compute_latest_cycle_state(self):
        """Get the latest cycle membership state per registrant+program."""
        for rec in self:
            rec.latest_cycle_state = False

        if not self:
            return

        # Batch query: find latest cycle membership ID for each partner+program pair
        data = self.env["spp.cycle.membership"]._read_group(
            domain=[
                ("partner_id", "in", self.partner_id.ids),
                ("cycle_id.program_id", "in", self.program_id.ids),
            ],
            groupby=["partner_id", "cycle_id.program_id"],
            aggregates=["id:max"],
        )
        # Map (partner_id, program_id) -> latest_membership_id
        latest_ids = {(p.id, prog.id): max_id for p, prog, max_id in data}

        # Fetch states for all latest memberships in one query
        mems = self.env["spp.cycle.membership"].browse(latest_ids.values())
        mem_states = {m.id: m.state for m in mems}

        for rec in self:
            mem_id = latest_ids.get((rec.partner_id.id, rec.program_id.id))
            if mem_id:
                rec.latest_cycle_state = mem_states.get(mem_id)


def action_view_cycle_memberships(self):
"""Open cycle memberships for this registrant in this program."""
self.ensure_one()
return {
"name": _("%s — Cycles") % self.program_id.name,
"type": "ir.actions.act_window",
"res_model": "spp.cycle.membership",
"view_mode": "list,form",
"domain": [
("partner_id", "=", self.partner_id.id),
("cycle_id.program_id", "=", self.program_id.id),
],
}

# TODO: Implement exit reasons
# exit_reason_id = fields.Many2one("Exit Reason") Default: Completed, Opt-Out, Other

Expand Down
57 changes: 57 additions & 0 deletions spp_programs/models/registrant.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ class SPPRegistrant(models.Model):
inkind_entitlement_ids = fields.One2many("spp.entitlement.inkind", "partner_id", "In-kind Entitlements")

# Statistics
cycle_membership_count = fields.Integer(
string="# Cycles",
compute="_compute_cycle_membership_count",
store=True,
)
non_compliant_cycle_count = fields.Integer(
string="# Non-Compliant",
compute="_compute_cycle_membership_count",
store=True,
)

program_membership_count = fields.Integer(
string="# Program Memberships",
compute="_compute_program_membership_count",
Expand All @@ -34,6 +45,40 @@ class SPPRegistrant(models.Model):
compute="_compute_total_entitlements_count",
)

@api.depends("cycle_ids", "cycle_ids.state")
def _compute_cycle_membership_count(self):
"""Batch-efficient cycle membership and non-compliant counts."""
if not self:
return

registrants = self.filtered("is_registrant")
for partner in self - registrants:
partner.cycle_membership_count = 0
partner.non_compliant_cycle_count = 0

if not registrants:
return

# Total cycle memberships
total_data = self.env["spp.cycle.membership"]._read_group(
domain=[("partner_id", "in", registrants.ids)],
groupby=["partner_id"],
aggregates=["__count"],
)
total_counts = {partner.id: count for partner, count in total_data}

# Non-compliant count
nc_data = self.env["spp.cycle.membership"]._read_group(
domain=[("partner_id", "in", registrants.ids), ("state", "=", "non_compliant")],
groupby=["partner_id"],
aggregates=["__count"],
)
nc_counts = {partner.id: count for partner, count in nc_data}

for partner in registrants:
partner.cycle_membership_count = total_counts.get(partner.id, 0)
partner.non_compliant_cycle_count = nc_counts.get(partner.id, 0)

@api.depends("entitlements_count", "inkind_entitlements_count")
def _compute_total_entitlements_count(self):
"""Compute combined count of cash and in-kind entitlements."""
Expand Down Expand Up @@ -144,6 +189,18 @@ def action_view_program_memberships(self):
"context": {"default_partner_id": self.id},
}

def action_view_cycle_memberships(self):
"""Open cycle memberships for this registrant."""
self.ensure_one()
return {
"name": _("Cycle Memberships - %s") % self.name,
"type": "ir.actions.act_window",
"res_model": "spp.cycle.membership",
"view_mode": "list,form",
"domain": [("partner_id", "=", self.id)],
"context": {"default_partner_id": self.id},
}

def action_view_all_entitlements(self):
"""Open all entitlements (cash + in-kind) for this registrant."""
self.ensure_one()
Expand Down
12 changes: 11 additions & 1 deletion spp_programs/views/cycle_membership_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,14 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
decoration-primary="state=='draft'"
decoration-warning="state=='paused'"
decoration-success="state=='enrolled'"
decoration-danger="state=='exited'"
decoration-danger="state in ('exited', 'non_compliant')"
widget="badge"
/>
<field
name="compliance_criteria"
string="Compliance Criteria"
optional="show"
/>
</list>
</field>
</record>
Expand Down Expand Up @@ -124,6 +129,11 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
string="Not Eligible"
domain="[('state','=','not_eligible')]"
/>
<filter
name="non_compliant"
string="Non-Compliant"
domain="[('state','=','non_compliant')]"
/>
<separator />
<filter
string="Enrollment Date"
Expand Down
58 changes: 58 additions & 0 deletions spp_programs/views/registrant_view.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
string="Entitlements"
/>
</button>
<button
name="action_view_cycle_memberships"
type="object"
class="oe_stat_button"
icon="fa-refresh"
invisible="not is_registrant or cycle_membership_count == 0"
groups="spp_programs.group_programs_viewer"
>
<div class="o_stat_info">
<field name="cycle_membership_count" class="o_stat_value" />
<span class="o_stat_text">Cycles</span>
</div>
<field
name="non_compliant_cycle_count"
invisible="non_compliant_cycle_count == 0"
widget="statinfo"
string="Non-Compliant"
class="text-danger"
/>
</button>
</xpath>

<!-- Programs Section in Individual Participation Tab -->
Expand Down Expand Up @@ -68,6 +88,7 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
decoration-muted="state in ('exited', 'not_eligible')"
decoration-warning="state == 'paused'"
decoration-success="state == 'enrolled'"
decoration-danger="latest_cycle_state == 'non_compliant'"
>
<field name="program_id" />
<field name="state" widget="badge" />
Expand All @@ -94,6 +115,24 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
groups="spp_programs.group_programs_officer"
confirm="Are you sure you want to exit this registrant from the program?"
/>
<field
name="latest_cycle_state"
string="Latest Cycle Status"
widget="badge"
decoration-danger="latest_cycle_state == 'non_compliant'"
decoration-success="latest_cycle_state == 'enrolled'"
decoration-warning="latest_cycle_state == 'paused'"
decoration-muted="latest_cycle_state in ('exited', 'not_eligible')"
optional="show"
/>
<button
name="action_view_cycle_memberships"
type="object"
string="View Cycles"
class="btn-link"
icon="fa-list"
groups="spp_programs.group_programs_viewer"
/>
</list>
</field>
<div invisible="program_membership_count != 0" class="text-muted small">
Expand Down Expand Up @@ -188,6 +227,7 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
decoration-muted="state in ('exited', 'not_eligible')"
decoration-warning="state == 'paused'"
decoration-success="state == 'enrolled'"
decoration-danger="latest_cycle_state == 'non_compliant'"
>
<field name="program_id" />
<field name="state" widget="badge" />
Expand All @@ -214,6 +254,24 @@ Part of OpenSPP. See LICENSE file for full copyright and licensing details.
groups="spp_programs.group_programs_officer"
confirm="Are you sure you want to exit this registrant from the program?"
/>
<field
name="latest_cycle_state"
string="Latest Cycle Status"
widget="badge"
decoration-danger="latest_cycle_state == 'non_compliant'"
decoration-success="latest_cycle_state == 'enrolled'"
decoration-warning="latest_cycle_state == 'paused'"
decoration-muted="latest_cycle_state in ('exited', 'not_eligible')"
optional="show"
/>
<button
name="action_view_cycle_memberships"
type="object"
string="View Cycles"
class="btn-link"
icon="fa-list"
groups="spp_programs.group_programs_viewer"
/>
</list>
</field>
<div invisible="program_membership_count != 0" class="text-muted small">
Expand Down
Loading