Coverage for benefits/eligibility/views.py: 97%
130 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 eligibility application: view definitions for the eligibility verification flow.
3"""
5from dataclasses import asdict, dataclass
6from typing import Optional
8from django.contrib import messages
9from django.shortcuts import redirect
10from django.urls import reverse
11from django.views.generic import FormView, TemplateView
13from benefits.core import recaptcha, session
14from benefits.core.context_processors import formatted_gettext_lazy as _
15from benefits.core.mixins import AgencySessionRequiredMixin, FlowSessionRequiredMixin, RecaptchaEnabledMixin
16from benefits.core.models import EnrollmentFlow, SystemName
17from benefits.routes import routes
19from . import analytics, forms, verify
22class IndexView(AgencySessionRequiredMixin, RecaptchaEnabledMixin, FormView):
23 """View handler for the enrollment flow selection form."""
25 template_name = "eligibility/index.html"
26 form_class = forms.EnrollmentFlowSelectionForm
28 def get_form_kwargs(self):
29 """Return the keyword arguments for instantiating the form."""
30 kwargs = super().get_form_kwargs()
31 kwargs["agency"] = self.agency
32 return kwargs
34 def get_context_data(self, **kwargs):
35 """Add agency-specific context data."""
36 context = super().get_context_data(**kwargs)
38 agency = self.agency
39 group_agencies = agency.group_agencies()
41 if group_agencies:
42 form_text = _(
43 "Cal-ITP doesn’t save any of your information. {short_name} and "
44 "nearby transit providers offer reduced fares to riders who qualify.",
45 short_name=agency.short_name,
46 )
47 previous_url = routes.ADDITIONAL_AGENCIES
48 else:
49 form_text = _(
50 "Cal-ITP doesn’t save any of your information. {short_name} offers reduced fares to riders who qualify.",
51 short_name=agency.short_name,
52 )
53 previous_url = routes.INDEX
55 context.update({"form_text": [form_text], "previous_url": previous_url})
56 return context
58 def get(self, request, *args, **kwargs):
59 """Initialize session state before handling the request."""
61 session.update(request, eligible=False, origin=self.agency.index_url)
62 session.logout(request)
64 return super().get(request, *args, **kwargs)
66 def form_valid(self, form):
67 """If the form is valid, set enrollment flow."""
68 flow_id = form.cleaned_data.get("flow")
69 flow = EnrollmentFlow.objects.get(id=flow_id)
70 session.update(self.request, flow=flow)
72 analytics.selected_flow(self.request, flow)
73 return redirect(routes.ELIGIBILITY_START)
75 def form_invalid(self, form):
76 """If the form is invalid, display error messages."""
77 if recaptcha.has_error(form):
78 messages.error(self.request, "Recaptcha failed. Please try again.")
79 return super().form_invalid(form)
82@dataclass
83class CTAButton:
84 text: str
85 route: str
86 fallback_text: Optional[str] = None
87 extra_classes: Optional[str] = None
90@dataclass
91class EligibilityStart:
92 page_title: str
93 call_to_action_button: CTAButton
94 eligibility_item_headline: Optional[str] = None
95 eligibility_item_body: Optional[str] = None
97 def dict(self):
98 return asdict(self)
101class LoginGovEligibilityStart(EligibilityStart):
103 def __init__(self, page_title):
104 super().__init__(
105 page_title=page_title,
106 call_to_action_button=CTAButton(
107 text=_("Get started with"),
108 fallback_text="Login.gov",
109 route=routes.OAUTH_LOGIN,
110 extra_classes="login",
111 ),
112 )
115class AgencyCardEligibilityStart(EligibilityStart):
117 def __init__(self, eligibility_item_headline, eligibility_item_body):
118 super().__init__(
119 page_title=_("Agency card overview"),
120 eligibility_item_headline=eligibility_item_headline,
121 eligibility_item_body=eligibility_item_body,
122 call_to_action_button=CTAButton(text=_("Continue"), route=routes.ELIGIBILITY_CONFIRM),
123 )
126class StartView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, TemplateView):
127 """CBV for the eligibility verification getting started screen."""
129 template_name = "eligibility/start.html"
131 def get(self, request, *args, **kwargs):
132 session.update(request, eligible=False, origin=reverse(routes.ELIGIBILITY_START))
133 return super().get(request, *args, **kwargs)
135 def get_context_data(self, **kwargs):
136 context = super().get_context_data(**kwargs)
138 eligibility_start = {
139 SystemName.CALFRESH.value: LoginGovEligibilityStart(
140 page_title=_("CalFresh benefit overview"),
141 ),
142 SystemName.COURTESY_CARD.value: AgencyCardEligibilityStart(
143 eligibility_item_headline=_("Your current Courtesy Card number"),
144 eligibility_item_body=_(
145 "You do not need to have your physical MST Courtesy Card, but you will need to know the number."
146 ),
147 ),
148 SystemName.MEDICARE.value: EligibilityStart(
149 page_title=_("Medicare benefit overview"),
150 eligibility_item_headline=_("An online account with Medicare.gov"),
151 eligibility_item_body=_(
152 "If you do not have an account you will be able to create one using your red, white, and blue Medicare "
153 "card. We use your Medicare.gov account to verify you qualify."
154 ),
155 call_to_action_button=CTAButton(text=_("Continue to Medicare.gov"), route=routes.OAUTH_LOGIN),
156 ),
157 SystemName.OLDER_ADULT.value: LoginGovEligibilityStart(
158 page_title=_("Older adult benefit overview"),
159 ),
160 SystemName.REDUCED_FARE_MOBILITY_ID.value: AgencyCardEligibilityStart(
161 eligibility_item_headline=_("Your current Reduced Fare Mobility ID number"),
162 eligibility_item_body=_("You do not need to have your physical card, but you will need to know the number."),
163 ),
164 SystemName.VETERAN.value: LoginGovEligibilityStart(
165 page_title=_("U.S. Veteran benefit overview"),
166 ),
167 }
169 context.update(eligibility_start[self.flow.system_name].dict())
170 return context
173class ConfirmView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, RecaptchaEnabledMixin, FormView):
174 """View handler for Eligiblity Confirm form, used only by flows that support Eligibility API verification."""
176 template_name = "eligibility/confirm.html"
178 def get_form_class(self):
179 flow_system_name = self.flow.system_name
181 if flow_system_name == SystemName.COURTESY_CARD:
182 form_class = forms.MSTCourtesyCard
183 elif flow_system_name == SystemName.REDUCED_FARE_MOBILITY_ID:
184 form_class = forms.SBMTDMobilityPass
185 else:
186 raise ValueError(f"The {flow_system_name} flow does not support Eligibility API verification.")
188 return form_class
190 def get(self, request, *args, **kwargs):
191 if not session.eligible(request):
192 session.update(request, origin=reverse(routes.ELIGIBILITY_CONFIRM))
193 return super().get(request, *args, **kwargs)
194 else:
195 # an already verified user, no need to verify again
196 return redirect(routes.ENROLLMENT_INDEX)
198 def post(self, request, *args, **kwargs):
199 analytics.started_eligibility(request, self.flow)
200 return super().post(request, *args, **kwargs)
202 def form_valid(self, form):
203 agency = self.agency
204 flow = self.flow
205 request = self.request
207 # make Eligibility Verification request to get the verified confirmation
208 is_verified = verify.eligibility_from_api(flow, form, agency)
210 # Eligibility API returned errors (so eligibility is unknown), allow for correction/resubmission
211 if is_verified is None:
212 analytics.returned_error(request, flow, form.errors)
213 return self.form_invalid(form)
214 # Eligibility API returned that no type was verified
215 elif not is_verified:
216 return redirect(routes.ELIGIBILITY_UNVERIFIED)
217 # Eligibility API returned that type was verified
218 else:
219 session.update(request, eligible=True)
220 analytics.returned_success(request, flow)
222 return redirect(routes.ENROLLMENT_INDEX)
224 def form_invalid(self, form):
225 if recaptcha.has_error(form):
226 messages.error(self.request, "Recaptcha failed. Please try again.")
228 return self.get(self.request)
231@dataclass
232class EligibilityUnverified:
233 headline_text: str
234 body_text: str
235 button_text: str
237 def dict(self):
238 return asdict(self)
241class AgencyCardEligibilityUnverified(EligibilityUnverified):
242 def __init__(self, agency_card):
243 super().__init__(
244 headline_text=_("Your card information may not have been entered correctly"),
245 body_text=_(
246 "The number and last name must be entered exactly as they appear on your {agency_card}. "
247 "Please check your card and try again, or contact your transit agency for help.",
248 agency_card=agency_card,
249 ),
250 button_text=_("Try again"),
251 )
254class UnverifiedView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, TemplateView):
255 """CBV for the unverified eligibility page."""
257 template_name = "eligibility/unverified.html"
259 def get_context_data(self, **kwargs):
260 context = super().get_context_data(**kwargs)
262 eligibility_unverified = {
263 SystemName.COURTESY_CARD.value: AgencyCardEligibilityUnverified(agency_card=_("MST Courtesy Card")),
264 SystemName.REDUCED_FARE_MOBILITY_ID.value: AgencyCardEligibilityUnverified(
265 agency_card=_("SBMTD Reduced Fare Mobility ID card")
266 ),
267 }
269 context_object = eligibility_unverified.get(self.flow.system_name)
270 context.update(context_object.dict() if context_object else {})
271 return context
273 def get(self, request, *args, **kwargs):
274 analytics.returned_fail(request, self.flow)
275 return super().get(request, *args, **kwargs)