Coverage for benefits/core/models/transit.py: 99%

161 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-23 20:53 +0000

1import logging 

2import os 

3 

4from django.contrib.auth.models import Group, User 

5from django.core.exceptions import NON_FIELD_ERRORS, ValidationError 

6from django.db import models 

7from django.urls import reverse 

8from multiselectfield import MultiSelectField 

9 

10from benefits.enrollment.registry import TransitProcessorRegistry 

11from benefits.routes import routes 

12 

13from .common import Environment 

14from .enrollment import EnrollmentFlow 

15 

16logger = logging.getLogger(__name__) 

17 

18 

19class CardSchemes: 

20 VISA = "visa" 

21 MASTERCARD = "mastercard" 

22 DISCOVER = "discover" 

23 AMEX = "amex" 

24 

25 CHOICES = dict( 

26 [ 

27 (VISA, "Visa"), 

28 (MASTERCARD, "Mastercard"), 

29 (DISCOVER, "Discover"), 

30 (AMEX, "American Express"), 

31 ] 

32 ) 

33 

34 

35def agency_logo(instance, filename): 

36 base, ext = os.path.splitext(filename) 

37 return f"agencies/{instance.slug}" + ext 

38 

39 

40class TransitProcessorConfig(models.Model): 

41 id = models.AutoField(primary_key=True) 

42 environment = models.CharField( 

43 choices=Environment, 

44 help_text="A label to indicate which environment this configuration is for.", 

45 ) 

46 label = models.CharField( 

47 default="", 

48 blank=True, 

49 help_text="A label for internal use.", 

50 ) 

51 portal_url = models.URLField( 

52 default="", 

53 blank=True, 

54 help_text="The absolute base URL for the TransitProcessor's control portal.", 

55 ) 

56 

57 @property 

58 def system_name(self): 

59 return self._meta.app_config.system_name 

60 

61 @property 

62 def system_name_for_display(self): 

63 return self._meta.app_config.system_name_for_display 

64 

65 @property 

66 def info_url(self): 

67 return self._meta.app_config.info_url 

68 

69 @property 

70 def group_model(self): 

71 return self._meta.app_config.group_model 

72 

73 @property 

74 def enrollment_index_route(self): 

75 return self._meta.app_config.enrollment_index_route 

76 

77 @property 

78 def in_person_enrollment_index_route(self): 

79 return self._meta.app_config.in_person_enrollment_index_route 

80 

81 def __str__(self): 

82 environment_label = Environment(self.environment).label if self.environment else "unknown" 

83 return f"({environment_label}) {self.label}" 

84 

85 

86class TransitAgency(models.Model): 

87 """An agency offering transit service.""" 

88 

89 class Meta: 

90 verbose_name_plural = "transit agencies" 

91 

92 id = models.AutoField(primary_key=True) 

93 active = models.BooleanField(default=False, help_text="Determines if this Agency is enabled for users") 

94 slug = models.SlugField( 

95 unique=True, 

96 help_text="Used for URL navigation for this agency, e.g. the agency homepage url is /{slug}", 

97 ) 

98 short_name = models.CharField( 

99 default="", help_text="The user-facing short name for this agency. Often an uppercase acronym." 

100 ) 

101 long_name = models.CharField( 

102 default="", 

103 blank=True, 

104 help_text="The user-facing long name for this agency. Often the short_name acronym, spelled out.", 

105 ) 

106 info_url = models.URLField( 

107 default="", 

108 blank=True, 

109 help_text="URL of a website/page with more information about the agency's discounts", 

110 ) 

111 phone = models.CharField(default="", blank=True, help_text="Agency customer support phone number") 

112 enrollment_flows = models.ManyToManyField( 

113 EnrollmentFlow, 

114 help_text="Select the enrollment flows this agency supports.", 

115 ) 

116 supported_card_schemes = MultiSelectField( 

117 choices=CardSchemes.CHOICES, 

118 min_choices=1, 

119 max_choices=len(CardSchemes.CHOICES), 

120 default=[CardSchemes.VISA, CardSchemes.MASTERCARD], 

121 help_text="The contactless card schemes this agency supports.", 

122 ) 

123 sso_domain = models.CharField( 

124 blank=True, 

125 default="", 

126 help_text="The email domain of users to automatically add to this agency's staff group upon login.", 

127 ) 

128 customer_service_group = models.OneToOneField( 

129 Group, 

130 on_delete=models.PROTECT, 

131 null=True, 

132 blank=True, 

133 default=None, 

134 help_text="The group of users who are allowed to do in-person eligibility verification and enrollment.", 

135 related_name="transit_agency", 

136 ) 

137 logo = models.ImageField( 

138 default="", 

139 blank=True, 

140 upload_to=agency_logo, 

141 help_text="The transit agency's logo.", 

142 ) 

143 transit_processor_config = models.ForeignKey( 

144 TransitProcessorConfig, 

145 on_delete=models.PROTECT, 

146 null=True, 

147 blank=True, 

148 default=None, 

149 help_text="The transit processor configuration to use for enrollment.", 

150 ) 

151 

152 def __str__(self): 

153 if self.long_name: 

154 return self.long_name 

155 return self.short_name 

156 

157 @property 

158 def index_url(self): 

159 """Public-facing URL to the TransitAgency's landing page.""" 

160 return reverse(routes.AGENCY_INDEX, args=[self.slug]) 

161 

162 @property 

163 def entrypoint_url(self): 

164 """For grouped agencies, we display an interstitial view prior to commencing the eligibility check.""" 

165 if self.group_agencies(): 

166 return reverse(routes.ADDITIONAL_AGENCIES) 

167 

168 return reverse(routes.ELIGIBILITY_INDEX) 

169 

170 @property 

171 def transit_processor(self): 

172 return TransitProcessorRegistry.get_transit_processor_config(self) 

173 

174 @property 

175 def transit_processor_system_name(self): 

176 return self.transit_processor.system_name if self.transit_processor else None 

177 

178 @property 

179 def transit_processor_display_name(self): 

180 return self.transit_processor.system_name_for_display if self.transit_processor else None 

181 

182 @property 

183 def transit_processor_info_url(self): 

184 return self.transit_processor.info_url if self.transit_processor else None 

185 

186 @property 

187 def in_person_enrollment_index_route(self): 

188 """This Agency's in-person enrollment index route, based on its configured transit processor.""" 

189 if self.transit_processor: 

190 return self.transit_processor.in_person_enrollment_index_route 

191 else: 

192 raise ValueError( 

193 ("TransitAgency must have a transit processor configured in order to show in-person enrollment index.") 

194 ) 

195 

196 @property 

197 def enrollment_index_route(self): 

198 """This Agency's enrollment index route, based on its configured transit processor.""" 

199 if self.transit_processor: 

200 return self.transit_processor.enrollment_index_route 

201 else: 

202 raise ValueError("TransitAgency must have a transit processor configured in order to show enrollment index.") 

203 

204 @property 

205 def customer_service_group_name(self): 

206 """Returns the standardized name for this Agency's customer service group.""" 

207 return f"{self.short_name} Customer Service" 

208 

209 def group_agencies(self, only_active=True): 

210 """The set of agencies in all groups associated with this agency, excluding itself. 

211 If only_active is True, only active agencies are returned. If only_active is False, 

212 all agencies are returned. 

213 

214 If an agency is not associated with any other agencies via TransitAgencyGroup, 

215 this returns an empty list. 

216 """ 

217 

218 agencies_in_group = ( 

219 TransitAgency.objects.filter(transitagencygroup__in=self.transitagencygroup_set.all()) 

220 .distinct() 

221 .exclude(pk=self.pk) 

222 ) 

223 

224 if only_active: 

225 agencies_in_group = agencies_in_group.exclude(active=False) 

226 

227 return list(agencies_in_group.order_by("short_name")) 

228 

229 def group_agency_short_names(self, only_active=True): 

230 """A list of agency short names for this agency and any agencies it shares a group with. 

231 If only_active is True, only active short names are returned. If only_active is False, 

232 all short names are returned. 

233 

234 The list begins with the current agency and the rest follow in alphabetical order. 

235 If an agency is not associated with any other agencies via TransitAgencyGroup, 

236 this returns an empty list. 

237 """ 

238 agencies = [self] + self.group_agencies(only_active=only_active) 

239 

240 if len(agencies) > 1: 

241 return [agency.short_name for agency in agencies] 

242 else: 

243 return [] 

244 

245 def clean(self): 

246 field_errors = {} 

247 non_field_errors = [] 

248 

249 if self.active: 

250 message = "This field is required for active transit agencies." 

251 needed = dict( 

252 long_name=self.long_name, 

253 phone=self.phone, 

254 info_url=self.info_url, 

255 logo=self.logo, 

256 ) 

257 field_errors.update({k: ValidationError(message) for k, v in needed.items() if not v}) 

258 

259 if self.transit_processor is None: 

260 non_field_errors.append(ValidationError("Must fill out configuration for a transit processor.")) 

261 else: 

262 try: 

263 self.transit_processor.clean() 

264 except ValidationError as e: 

265 display_name = self.transit_processor.system_name_for_display 

266 message = f"{display_name} configuration is missing fields that are required when this agency is active." 

267 message += f" Missing fields: {', '.join(e.error_dict.keys())}" 

268 non_field_errors.append(ValidationError(message)) 

269 

270 if self.pk: # prohibit updating short_name with blank customer_service_group 270 ↛ 281line 270 didn't jump to line 281 because the condition on line 270 was always true

271 original_obj = TransitAgency.objects.get(pk=self.pk) 

272 if self.short_name != original_obj.short_name and not self.customer_service_group: 

273 field_errors.update( 

274 { 

275 "customer_service_group": ValidationError( 

276 "Blank not allowed. Set to its original value if changing the Short Name." 

277 ) 

278 } 

279 ) 

280 

281 all_errors = {} 

282 if field_errors: 

283 all_errors.update(field_errors) 

284 if non_field_errors: 

285 all_errors.update({NON_FIELD_ERRORS: value for value in non_field_errors}) 

286 if all_errors: 

287 raise ValidationError(all_errors) 

288 

289 @staticmethod 

290 def by_id(id): 

291 """Get a TransitAgency instance by its ID.""" 

292 logger.debug(f"Get {TransitAgency.__name__} by id: {id}") 

293 return TransitAgency.objects.get(id=id) 

294 

295 @staticmethod 

296 def by_slug(slug): 

297 """Get a TransitAgency instance by its slug.""" 

298 logger.debug(f"Get {TransitAgency.__name__} by slug: {slug}") 

299 return TransitAgency.objects.filter(slug=slug).first() 

300 

301 @staticmethod 

302 def all_active(): 

303 """Get all TransitAgency instances marked active.""" 

304 logger.debug(f"Get all active {TransitAgency.__name__}") 

305 return TransitAgency.objects.filter(active=True).order_by("long_name") 

306 

307 @staticmethod 

308 def for_user(user: User): 

309 for group in user.groups.all(): 

310 if hasattr(group, "transit_agency"): 

311 return group.transit_agency # this is looking at the TransitAgency's customer_service_group 

312 

313 # the loop above returns the first match found. Return None if no match was found. 

314 return None 

315 

316 

317class TransitAgencyGroup(models.Model): 

318 id = models.AutoField(primary_key=True) 

319 label = models.CharField( 

320 help_text="A human readable label, used as the display text in Admin.", 

321 ) 

322 transit_agencies = models.ManyToManyField( 

323 TransitAgency, 

324 help_text="Select the agencies that belong to this group.", 

325 ) 

326 

327 def __str__(self): 

328 return self.label