Coverage for benefits/enrollment_switchio/models.py: 93%
37 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-14 01:41 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-14 01:41 +0000
1from django.core.exceptions import ValidationError
2from django.db import models
4from benefits.core.models import PemData, SecretNameField, Environment
7class SwitchioConfig(models.Model):
8 """Configuration for connecting to Switchio, an entity that applies transit agency fare rules to rider transactions."""
10 id = models.AutoField(primary_key=True)
11 environment = models.TextField(
12 choices=Environment,
13 help_text="A label to indicate which environment this configuration is for.",
14 )
15 api_key = models.TextField(help_text="The API key used to access the Switchio API.", default="", blank=True)
16 api_secret_name = SecretNameField(
17 help_text="The name of the secret containing the api_secret value used to access the Switchio API.", # noqa: E501
18 default="",
19 blank=True,
20 )
21 client_certificate = models.ForeignKey(
22 PemData,
23 related_name="+",
24 on_delete=models.PROTECT,
25 help_text="The client certificate for accessing the Switchio API.",
26 null=True,
27 blank=True,
28 default=None,
29 )
30 ca_certificate = models.ForeignKey(
31 PemData,
32 related_name="+",
33 on_delete=models.PROTECT,
34 help_text="The CA certificate chain for accessing the Switchio API.",
35 null=True,
36 blank=True,
37 default=None,
38 )
39 private_key = models.ForeignKey(
40 PemData,
41 related_name="+",
42 on_delete=models.PROTECT,
43 help_text="The private key for accessing the Switchio API.",
44 null=True,
45 blank=True,
46 default=None,
47 )
49 @property
50 def api_secret(self):
51 secret_field = self._meta.get_field("api_secret_name")
52 return secret_field.secret_value(self)
54 @property
55 def transit_processor_context(self):
56 return dict(name="Switchio", website="https://switchio.com/transport/")
58 @property
59 def enrollment_index_template(self):
60 return "enrollment/index--switchio.html"
62 def clean(self, agency=None):
63 field_errors = {}
65 if agency is not None:
66 used_by_active_agency = agency.active
67 elif self.pk is not None:
68 used_by_active_agency = any((agency.active for agency in self.transitagency_set.all()))
69 else:
70 used_by_active_agency = False
72 if used_by_active_agency:
73 message = "This field is required when this configuration is referenced by an active transit agency."
74 needed = dict(
75 api_key=self.api_key,
76 api_secret_name=self.api_secret_name,
77 client_certificate=self.client_certificate,
78 ca_certificate=self.ca_certificate,
79 private_key=self.private_key,
80 )
81 field_errors.update({k: ValidationError(message) for k, v in needed.items() if not v})
83 if field_errors:
84 raise ValidationError(field_errors)
86 def __str__(self):
87 environment_label = Environment(self.environment).label if self.environment else "unknown"
88 return f"{environment_label}"