Coverage for benefits/enrollment/views.py: 100%
98 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-23 20:53 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-23 20:53 +0000
1"""
2The enrollment application: view definitions for the benefits enrollment flow.
3"""
5import logging
6from dataclasses import asdict, dataclass
7from typing import Any, Optional
9from django.template.defaultfilters import date
10from django.urls import reverse
11from django.views.generic import RedirectView, TemplateView
13from benefits.core import models, session
14from benefits.core.context_processors import formatted_gettext_lazy as _
15from benefits.core.mixins import (
16 AgencySessionRequiredMixin,
17 EligibleSessionRequiredMixin,
18 FlowSessionRequiredMixin,
19 PageViewMixin,
20)
21from benefits.core.models import SystemName
22from benefits.routes import routes
24from . import analytics
26logger = logging.getLogger(__name__)
29@dataclass
30class EnrollmentIndex:
31 alert_include: Optional[str] = ""
33 def dict(self):
34 return asdict(self)
37@dataclass
38class CalFreshEnrollmentIndex(EnrollmentIndex):
39 def __init__(self):
40 super().__init__(
41 alert_include="enrollment/includes/alert-box--warning--calfresh.html",
42 )
45class IndexContextMixin(FlowSessionRequiredMixin):
46 def get_context_data(self, **kwargs) -> dict[str, Any]:
47 enrollment_index = {
48 SystemName.COURTESY_CARD: EnrollmentIndex(),
49 SystemName.REDUCED_FARE_MOBILITY_ID: EnrollmentIndex(),
50 SystemName.CALFRESH: CalFreshEnrollmentIndex(),
51 }
52 context = enrollment_index.get(self.flow.system_name, EnrollmentIndex())
53 return context.dict()
56class IndexView(AgencySessionRequiredMixin, EligibleSessionRequiredMixin, RedirectView):
57 """CBV for the enrollment landing page."""
59 route_origin = routes.ENROLLMENT_INDEX
61 def get_redirect_url(self, *args, **kwargs):
62 route_name = self.agency.enrollment_index_route
63 return reverse(route_name)
65 def get(self, request, *args, **kwargs):
66 flow = session.flow(request)
67 group = models.EnrollmentGroup.objects.get(transit_agency=self.agency, enrollment_flow=flow)
68 session.update(request, origin=reverse(self.route_origin), group=group)
69 return super().get(request, *args, **kwargs)
72class ReenrollmentErrorView(FlowSessionRequiredMixin, EligibleSessionRequiredMixin, TemplateView):
73 """View handler for a re-enrollment attempt that is not yet within the re-enrollment window."""
75 template_name = "enrollment/reenrollment-error.html"
77 def get_context_data(self, **kwargs):
78 context = super().get_context_data(**kwargs)
80 request = self.request
82 flow = self.flow
83 expiry = session.enrollment_expiry(request)
84 reenrollment = session.enrollment_reenrollment(request)
86 if flow.system_name == SystemName.CALFRESH:
87 does_not_expire_until = _("Your CalFresh Cardholder transit benefit does not expire until")
88 reenroll_on = _("You can re-enroll for this benefit beginning on")
89 try_again = _("Please try again then.")
91 context["paragraphs"] = [
92 f"{does_not_expire_until} {date(expiry)}. {reenroll_on} {date(reenrollment)}. {try_again}"
93 ]
95 return context
97 def get(self, request, *args, **kwargs):
98 flow = self.flow
100 if session.logged_in(request) and flow.supports_sign_out:
101 # overwrite origin for a logged in user
102 # if they click the logout button, they are taken to the new route
103 session.update(request, origin=reverse(routes.LOGGED_OUT))
105 return super().get(request, *args, **kwargs)
108class RetryView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, EligibleSessionRequiredMixin, TemplateView):
109 """View handler for a recoverable failure condition."""
111 template_name = "enrollment/retry.html"
112 enrollment_method = models.EnrollmentMethods.SELF_SERVICE
114 def dispatch(self, request, *args, **kwargs):
115 # for Littlepay, the Javascript in enrollment_littlepay/index.html sends a form POST to this view
116 # to simplify, we check the method here and process POSTs rather than implementing as a FormView, which requires
117 # instantiating the enrollment.forms.CardTokenizeFailForm, needing additional parameters such as a form id and
118 # action_url, that are already specified in the enrollment_littlepay/views.IndexView
119 #
120 # Switchio doesn't use this view at all
122 # call super().dispatch() first to ensure all mixins are processed (i.e. so we have a self.flow and self.agency)
123 response = super().dispatch(request, *args, **kwargs)
124 if request.method == "POST":
125 agency = self.agency
126 enrollment_group = str(self.group.group_id) # needs to be a string for the API call
127 transit_processor = agency.transit_processor_system_name
128 analytics.returned_retry(
129 request,
130 agency=agency,
131 enrollment_group=enrollment_group,
132 transit_processor=transit_processor,
133 enrollment_method=self.enrollment_method,
134 )
135 # TemplateView doesn't implement POST, just return the template via GET
136 return super().get(request, *args, **kwargs)
137 # for other request methods, we don't want/need to serve the retry template since users should only arrive via the form
138 # POST, returning super().dispatch() results in a 200 User Error response
139 return response
142class SystemErrorView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, EligibleSessionRequiredMixin, TemplateView):
143 """View handler for an enrollment system error."""
145 template_name = "enrollment/system_error.html"
147 def get_origin_url(self):
148 return self.agency.index_url
150 def get(self, request, *args, **kwargs):
151 # overwrite origin so that CTA takes user to agency index
152 origin_url = self.get_origin_url()
153 session.update(request, origin=origin_url)
154 return super().get(request, *args, **kwargs)
156 def post(self, request, *args, **kwargs):
157 # the Javascript in enrollment_littlepay/index.html and enrollment_switchio/index.html sends a form POST to this view
158 # rather than implementing this view as a FormView, which requires instantiating the
159 # enrollment.forms.CardTokenizeFailForm, we implement post() to simply return the template via get()
160 # we thus avoid interfering with the view's lifecycle and dispatch() method
161 return self.get(request, *args, **kwargs)
164class SuccessView(PageViewMixin, FlowSessionRequiredMixin, EligibleSessionRequiredMixin, TemplateView):
165 """View handler for the final success page."""
167 template_name = "enrollment/success.html"
168 only_active_agencies = True
170 def get_context_data(self, **kwargs):
171 context = super().get_context_data(**kwargs)
173 agency = self.agency
174 group_agencies = agency.group_agencies(only_active=self.only_active_agencies)
176 if group_agencies:
177 success_message = _(
178 "You were not charged anything today. When boarding public transit at the following providers, tap this card "
179 "and you will be charged a reduced fare:"
180 )
181 agency_short_names = agency.group_agency_short_names(only_active=self.only_active_agencies)
182 else:
183 success_message = _(
184 "You were not charged anything today. When boarding public transit provided by {short_name}, tap this "
185 "card and you will be charged a reduced fare.",
186 short_name=self.agency.short_name,
187 )
188 agency_short_names = None
190 context |= {
191 "redirect_to": self.request.path,
192 "success_message": success_message,
193 "agency_short_names": agency_short_names,
194 }
195 return context
197 def get(self, request, *args, **kwargs):
198 session.update(request, origin=reverse(routes.ENROLLMENT_SUCCESS))
200 flow = self.flow
202 if session.logged_in(request) and flow.supports_sign_out:
203 # overwrite origin for a logged in user
204 # if they click the logout button, they are taken to the new route
205 session.update(request, origin=reverse(routes.LOGGED_OUT))
207 return super().get(request, *args, **kwargs)