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

1""" 

2The eligibility application: view definitions for the eligibility verification flow. 

3""" 

4 

5from dataclasses import asdict, dataclass 

6from typing import Optional 

7 

8from django.contrib import messages 

9from django.shortcuts import redirect 

10from django.urls import reverse 

11from django.views.generic import FormView, TemplateView 

12 

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 

18 

19from . import analytics, forms, verify 

20 

21 

22class IndexView(AgencySessionRequiredMixin, RecaptchaEnabledMixin, FormView): 

23 """View handler for the enrollment flow selection form.""" 

24 

25 template_name = "eligibility/index.html" 

26 form_class = forms.EnrollmentFlowSelectionForm 

27 

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 

33 

34 def get_context_data(self, **kwargs): 

35 """Add agency-specific context data.""" 

36 context = super().get_context_data(**kwargs) 

37 

38 agency = self.agency 

39 group_agencies = agency.group_agencies() 

40 

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 

54 

55 context.update({"form_text": [form_text], "previous_url": previous_url}) 

56 return context 

57 

58 def get(self, request, *args, **kwargs): 

59 """Initialize session state before handling the request.""" 

60 

61 session.update(request, eligible=False, origin=self.agency.index_url) 

62 session.logout(request) 

63 

64 return super().get(request, *args, **kwargs) 

65 

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) 

71 

72 analytics.selected_flow(self.request, flow) 

73 return redirect(routes.ELIGIBILITY_START) 

74 

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) 

80 

81 

82@dataclass 

83class CTAButton: 

84 text: str 

85 route: str 

86 fallback_text: Optional[str] = None 

87 extra_classes: Optional[str] = None 

88 

89 

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 

96 

97 def dict(self): 

98 return asdict(self) 

99 

100 

101class LoginGovEligibilityStart(EligibilityStart): 

102 

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 ) 

113 

114 

115class AgencyCardEligibilityStart(EligibilityStart): 

116 

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 ) 

124 

125 

126class StartView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, TemplateView): 

127 """CBV for the eligibility verification getting started screen.""" 

128 

129 template_name = "eligibility/start.html" 

130 

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) 

134 

135 def get_context_data(self, **kwargs): 

136 context = super().get_context_data(**kwargs) 

137 

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 } 

168 

169 context.update(eligibility_start[self.flow.system_name].dict()) 

170 return context 

171 

172 

173class ConfirmView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, RecaptchaEnabledMixin, FormView): 

174 """View handler for Eligiblity Confirm form, used only by flows that support Eligibility API verification.""" 

175 

176 template_name = "eligibility/confirm.html" 

177 

178 def get_form_class(self): 

179 flow_system_name = self.flow.system_name 

180 

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.") 

187 

188 return form_class 

189 

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) 

197 

198 def post(self, request, *args, **kwargs): 

199 analytics.started_eligibility(request, self.flow) 

200 return super().post(request, *args, **kwargs) 

201 

202 def form_valid(self, form): 

203 agency = self.agency 

204 flow = self.flow 

205 request = self.request 

206 

207 # make Eligibility Verification request to get the verified confirmation 

208 is_verified = verify.eligibility_from_api(flow, form, agency) 

209 

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) 

221 

222 return redirect(routes.ENROLLMENT_INDEX) 

223 

224 def form_invalid(self, form): 

225 if recaptcha.has_error(form): 

226 messages.error(self.request, "Recaptcha failed. Please try again.") 

227 

228 return self.get(self.request) 

229 

230 

231@dataclass 

232class EligibilityUnverified: 

233 headline_text: str 

234 body_text: str 

235 button_text: str 

236 

237 def dict(self): 

238 return asdict(self) 

239 

240 

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 ) 

252 

253 

254class UnverifiedView(AgencySessionRequiredMixin, FlowSessionRequiredMixin, TemplateView): 

255 """CBV for the unverified eligibility page.""" 

256 

257 template_name = "eligibility/unverified.html" 

258 

259 def get_context_data(self, **kwargs): 

260 context = super().get_context_data(**kwargs) 

261 

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 } 

268 

269 context_object = eligibility_unverified.get(self.flow.system_name) 

270 context.update(context_object.dict() if context_object else {}) 

271 return context 

272 

273 def get(self, request, *args, **kwargs): 

274 analytics.returned_fail(request, self.flow) 

275 return super().get(request, *args, **kwargs)