We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Invoice information consistency
During checkout, if I choose "business customer", enter a company name, and then reconsider and switch to the individual customer interface, the "company name" name field gets hidden, but its value is still visible in the next step.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/pretix/base/forms/questions.py`
Content:
```
1 import logging
2 from decimal import Decimal
3 
4 import dateutil.parser
5 import pytz
6 import vat_moss.errors
7 import vat_moss.id
8 from django import forms
9 from django.contrib import messages
10 from django.core.exceptions import ValidationError
11 from django.utils.translation import ugettext_lazy as _
12 
13 from pretix.base.forms.widgets import (
14     BusinessBooleanRadio, DatePickerWidget, SplitDateTimePickerWidget,
15     TimePickerWidget, UploadedFileWidget,
16 )
17 from pretix.base.models import InvoiceAddress, Question
18 from pretix.base.models.tax import EU_COUNTRIES
19 from pretix.control.forms import SplitDateTimeField
20 from pretix.helpers.i18n import get_format_without_seconds
21 from pretix.presale.signals import question_form_fields
22 
23 logger = logging.getLogger(__name__)
24 
25 
26 class BaseQuestionsForm(forms.Form):
27     """
28     This form class is responsible for asking order-related questions. This includes
29     the attendee name for admission tickets, if the corresponding setting is enabled,
30     as well as additional questions defined by the organizer.
31     """
32 
33     def __init__(self, *args, **kwargs):
34         """
35         Takes two additional keyword arguments:
36 
37         :param cartpos: The cart position the form should be for
38         :param event: The event this belongs to
39         """
40         cartpos = self.cartpos = kwargs.pop('cartpos', None)
41         orderpos = self.orderpos = kwargs.pop('orderpos', None)
42         pos = cartpos or orderpos
43         item = pos.item
44         questions = pos.item.questions_to_ask
45         event = kwargs.pop('event')
46 
47         super().__init__(*args, **kwargs)
48 
49         if item.admission and event.settings.attendee_names_asked:
50             self.fields['attendee_name'] = forms.CharField(
51                 max_length=255, required=event.settings.attendee_names_required,
52                 label=_('Attendee name'),
53                 initial=(cartpos.attendee_name if cartpos else orderpos.attendee_name),
54             )
55         if item.admission and event.settings.attendee_emails_asked:
56             self.fields['attendee_email'] = forms.EmailField(
57                 required=event.settings.attendee_emails_required,
58                 label=_('Attendee email'),
59                 initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email)
60             )
61 
62         for q in questions:
63             # Do we already have an answer? Provide it as the initial value
64             answers = [a for a in pos.answerlist if a.question_id == q.id]
65             if answers:
66                 initial = answers[0]
67             else:
68                 initial = None
69             tz = pytz.timezone(event.settings.timezone)
70             if q.type == Question.TYPE_BOOLEAN:
71                 if q.required:
72                     # For some reason, django-bootstrap3 does not set the required attribute
73                     # itself.
74                     widget = forms.CheckboxInput(attrs={'required': 'required'})
75                 else:
76                     widget = forms.CheckboxInput()
77 
78                 if initial:
79                     initialbool = (initial.answer == "True")
80                 else:
81                     initialbool = False
82 
83                 field = forms.BooleanField(
84                     label=q.question, required=q.required,
85                     help_text=q.help_text,
86                     initial=initialbool, widget=widget,
87                 )
88             elif q.type == Question.TYPE_NUMBER:
89                 field = forms.DecimalField(
90                     label=q.question, required=q.required,
91                     help_text=q.help_text,
92                     initial=initial.answer if initial else None,
93                     min_value=Decimal('0.00'),
94                 )
95             elif q.type == Question.TYPE_STRING:
96                 field = forms.CharField(
97                     label=q.question, required=q.required,
98                     help_text=q.help_text,
99                     initial=initial.answer if initial else None,
100                 )
101             elif q.type == Question.TYPE_TEXT:
102                 field = forms.CharField(
103                     label=q.question, required=q.required,
104                     help_text=q.help_text,
105                     widget=forms.Textarea,
106                     initial=initial.answer if initial else None,
107                 )
108             elif q.type == Question.TYPE_CHOICE:
109                 field = forms.ModelChoiceField(
110                     queryset=q.options,
111                     label=q.question, required=q.required,
112                     help_text=q.help_text,
113                     widget=forms.Select,
114                     empty_label='',
115                     initial=initial.options.first() if initial else None,
116                 )
117             elif q.type == Question.TYPE_CHOICE_MULTIPLE:
118                 field = forms.ModelMultipleChoiceField(
119                     queryset=q.options,
120                     label=q.question, required=q.required,
121                     help_text=q.help_text,
122                     widget=forms.CheckboxSelectMultiple,
123                     initial=initial.options.all() if initial else None,
124                 )
125             elif q.type == Question.TYPE_FILE:
126                 field = forms.FileField(
127                     label=q.question, required=q.required,
128                     help_text=q.help_text,
129                     initial=initial.file if initial else None,
130                     widget=UploadedFileWidget(position=pos, event=event, answer=initial),
131                 )
132             elif q.type == Question.TYPE_DATE:
133                 field = forms.DateField(
134                     label=q.question, required=q.required,
135                     help_text=q.help_text,
136                     initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None,
137                     widget=DatePickerWidget(),
138                 )
139             elif q.type == Question.TYPE_TIME:
140                 field = forms.TimeField(
141                     label=q.question, required=q.required,
142                     help_text=q.help_text,
143                     initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None,
144                     widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),
145                 )
146             elif q.type == Question.TYPE_DATETIME:
147                 field = SplitDateTimeField(
148                     label=q.question, required=q.required,
149                     help_text=q.help_text,
150                     initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None,
151                     widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),
152                 )
153             field.question = q
154             if answers:
155                 # Cache the answer object for later use
156                 field.answer = answers[0]
157             self.fields['question_%s' % q.id] = field
158 
159         responses = question_form_fields.send(sender=event, position=pos)
160         data = pos.meta_info_data
161         for r, response in sorted(responses, key=lambda r: str(r[0])):
162             for key, value in response.items():
163                 # We need to be this explicit, since OrderedDict.update does not retain ordering
164                 self.fields[key] = value
165                 value.initial = data.get('question_form_data', {}).get(key)
166 
167 
168 class BaseInvoiceAddressForm(forms.ModelForm):
169     vat_warning = False
170 
171     class Meta:
172         model = InvoiceAddress
173         fields = ('is_business', 'company', 'name', 'street', 'zipcode', 'city', 'country', 'vat_id',
174                   'internal_reference')
175         widgets = {
176             'is_business': BusinessBooleanRadio,
177             'street': forms.Textarea(attrs={'rows': 2, 'placeholder': _('Street and Number')}),
178             'company': forms.TextInput(attrs={'data-display-dependency': '#id_is_business_1'}),
179             'name': forms.TextInput(attrs={}),
180             'vat_id': forms.TextInput(attrs={'data-display-dependency': '#id_is_business_1'}),
181             'internal_reference': forms.TextInput,
182         }
183         labels = {
184             'is_business': ''
185         }
186 
187     def __init__(self, *args, **kwargs):
188         self.event = event = kwargs.pop('event')
189         self.request = kwargs.pop('request', None)
190         self.validate_vat_id = kwargs.pop('validate_vat_id')
191         super().__init__(*args, **kwargs)
192         if not event.settings.invoice_address_vatid:
193             del self.fields['vat_id']
194         if not event.settings.invoice_address_required:
195             for k, f in self.fields.items():
196                 f.required = False
197                 f.widget.is_required = False
198                 if 'required' in f.widget.attrs:
199                     del f.widget.attrs['required']
200 
201             if event.settings.invoice_name_required:
202                 self.fields['name'].required = True
203         elif event.settings.invoice_address_company_required:
204             self.initial['is_business'] = True
205 
206             self.fields['is_business'].widget = BusinessBooleanRadio(require_business=True)
207             self.fields['company'].required = True
208             self.fields['company'].widget.is_required = True
209             self.fields['company'].widget.attrs['required'] = 'required'
210             del self.fields['company'].widget.attrs['data-display-dependency']
211             if 'vat_id' in self.fields:
212                 del self.fields['vat_id'].widget.attrs['data-display-dependency']
213         else:
214             self.fields['company'].widget.attrs['data-required-if'] = '#id_is_business_1'
215             self.fields['name'].widget.attrs['data-required-if'] = '#id_is_business_0'
216 
217     def clean(self):
218         data = self.cleaned_data
219         if not data.get('name') and not data.get('company') and self.event.settings.invoice_address_required:
220             raise ValidationError(_('You need to provide either a company name or your name.'))
221 
222         if 'vat_id' in self.changed_data or not data.get('vat_id'):
223             self.instance.vat_id_validated = False
224 
225         if self.validate_vat_id and self.instance.vat_id_validated and 'vat_id' not in self.changed_data:
226             pass
227         elif self.validate_vat_id and data.get('is_business') and data.get('country') in EU_COUNTRIES and data.get('vat_id'):
228             if data.get('vat_id')[:2] != str(data.get('country')):
229                 raise ValidationError(_('Your VAT ID does not match the selected country.'))
230             try:
231                 result = vat_moss.id.validate(data.get('vat_id'))
232                 if result:
233                     country_code, normalized_id, company_name = result
234                     self.instance.vat_id_validated = True
235                     self.instance.vat_id = normalized_id
236             except vat_moss.errors.InvalidError:
237                 raise ValidationError(_('This VAT ID is not valid. Please re-check your input.'))
238             except vat_moss.errors.WebServiceUnavailableError:
239                 logger.exception('VAT ID checking failed for country {}'.format(data.get('country')))
240                 self.instance.vat_id_validated = False
241                 if self.request and self.vat_warning:
242                     messages.warning(self.request, _('Your VAT ID could not be checked, as the VAT checking service of '
243                                                      'your country is currently not available. We will therefore '
244                                                      'need to charge VAT on your invoice. You can get the tax amount '
245                                                      'back via the VAT reimbursement process.'))
246             except vat_moss.errors.WebServiceError:
247                 logger.exception('VAT ID checking failed for country {}'.format(data.get('country')))
248                 self.instance.vat_id_validated = False
249                 if self.request and self.vat_warning:
250                     messages.warning(self.request, _('Your VAT ID could not be checked, as the VAT checking service of '
251                                                      'your country returned an incorrect result. We will therefore '
252                                                      'need to charge VAT on your invoice. Please contact support to '
253                                                      'resolve this manually.'))
254         else:
255             self.instance.vat_id_validated = False
256 
257 
258 class BaseInvoiceNameForm(BaseInvoiceAddressForm):
259 
260     def __init__(self, *args, **kwargs):
261         super().__init__(*args, **kwargs)
262         for f in list(self.fields.keys()):
263             if f != 'name':
264                 del self.fields[f]
265
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/pretix/base/forms/questions.py b/src/pretix/base/forms/questions.py
--- a/src/pretix/base/forms/questions.py
+++ b/src/pretix/base/forms/questions.py
@@ -216,6 +216,8 @@
 
     def clean(self):
         data = self.cleaned_data
+        if not data.get('is_business'):
+            data['company'] = ''
         if not data.get('name') and not data.get('company') and self.event.settings.invoice_address_required:
             raise ValidationError(_('You need to provide either a company name or your name.'))

{"golden_diff": "diff --git a/src/pretix/base/forms/questions.py b/src/pretix/base/forms/questions.py\n--- a/src/pretix/base/forms/questions.py\n+++ b/src/pretix/base/forms/questions.py\n@@ -216,6 +216,8 @@\n \n     def clean(self):\n         data = self.cleaned_data\n+        if not data.get('is_business'):\n+            data['company'] = ''\n         if not data.get('name') and not data.get('company') and self.event.settings.invoice_address_required:\n             raise ValidationError(_('You need to provide either a company name or your name.'))\n", "issue": "Invoice information consistency\nDuring checkout, if I choose \"business customer\", enter a company name, and then reconsider and switch to the individual customer interface, the \"company name\" name field gets hidden, but its value is still visible in the next step.\n", "before_files": [{"content": "import logging\nfrom decimal import Decimal\n\nimport dateutil.parser\nimport pytz\nimport vat_moss.errors\nimport vat_moss.id\nfrom django import forms\nfrom django.contrib import messages\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom pretix.base.forms.widgets import (\n    BusinessBooleanRadio, DatePickerWidget, SplitDateTimePickerWidget,\n    TimePickerWidget, UploadedFileWidget,\n)\nfrom pretix.base.models import InvoiceAddress, Question\nfrom pretix.base.models.tax import EU_COUNTRIES\nfrom pretix.control.forms import SplitDateTimeField\nfrom pretix.helpers.i18n import get_format_without_seconds\nfrom pretix.presale.signals import question_form_fields\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseQuestionsForm(forms.Form):\n    \"\"\"\n    This form class is responsible for asking order-related questions. This includes\n    the attendee name for admission tickets, if the corresponding setting is enabled,\n    as well as additional questions defined by the organizer.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"\n        Takes two additional keyword arguments:\n\n        :param cartpos: The cart position the form should be for\n        :param event: The event this belongs to\n        \"\"\"\n        cartpos = self.cartpos = kwargs.pop('cartpos', None)\n        orderpos = self.orderpos = kwargs.pop('orderpos', None)\n        pos = cartpos or orderpos\n        item = pos.item\n        questions = pos.item.questions_to_ask\n        event = kwargs.pop('event')\n\n        super().__init__(*args, **kwargs)\n\n        if item.admission and event.settings.attendee_names_asked:\n            self.fields['attendee_name'] = forms.CharField(\n                max_length=255, required=event.settings.attendee_names_required,\n                label=_('Attendee name'),\n                initial=(cartpos.attendee_name if cartpos else orderpos.attendee_name),\n            )\n        if item.admission and event.settings.attendee_emails_asked:\n            self.fields['attendee_email'] = forms.EmailField(\n                required=event.settings.attendee_emails_required,\n                label=_('Attendee email'),\n                initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email)\n            )\n\n        for q in questions:\n            # Do we already have an answer? Provide it as the initial value\n            answers = [a for a in pos.answerlist if a.question_id == q.id]\n            if answers:\n                initial = answers[0]\n            else:\n                initial = None\n            tz = pytz.timezone(event.settings.timezone)\n            if q.type == Question.TYPE_BOOLEAN:\n                if q.required:\n                    # For some reason, django-bootstrap3 does not set the required attribute\n                    # itself.\n                    widget = forms.CheckboxInput(attrs={'required': 'required'})\n                else:\n                    widget = forms.CheckboxInput()\n\n                if initial:\n                    initialbool = (initial.answer == \"True\")\n                else:\n                    initialbool = False\n\n                field = forms.BooleanField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initialbool, widget=widget,\n                )\n            elif q.type == Question.TYPE_NUMBER:\n                field = forms.DecimalField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initial.answer if initial else None,\n                    min_value=Decimal('0.00'),\n                )\n            elif q.type == Question.TYPE_STRING:\n                field = forms.CharField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initial.answer if initial else None,\n                )\n            elif q.type == Question.TYPE_TEXT:\n                field = forms.CharField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    widget=forms.Textarea,\n                    initial=initial.answer if initial else None,\n                )\n            elif q.type == Question.TYPE_CHOICE:\n                field = forms.ModelChoiceField(\n                    queryset=q.options,\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    widget=forms.Select,\n                    empty_label='',\n                    initial=initial.options.first() if initial else None,\n                )\n            elif q.type == Question.TYPE_CHOICE_MULTIPLE:\n                field = forms.ModelMultipleChoiceField(\n                    queryset=q.options,\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    widget=forms.CheckboxSelectMultiple,\n                    initial=initial.options.all() if initial else None,\n                )\n            elif q.type == Question.TYPE_FILE:\n                field = forms.FileField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initial.file if initial else None,\n                    widget=UploadedFileWidget(position=pos, event=event, answer=initial),\n                )\n            elif q.type == Question.TYPE_DATE:\n                field = forms.DateField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None,\n                    widget=DatePickerWidget(),\n                )\n            elif q.type == Question.TYPE_TIME:\n                field = forms.TimeField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None,\n                    widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),\n                )\n            elif q.type == Question.TYPE_DATETIME:\n                field = SplitDateTimeField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None,\n                    widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),\n                )\n            field.question = q\n            if answers:\n                # Cache the answer object for later use\n                field.answer = answers[0]\n            self.fields['question_%s' % q.id] = field\n\n        responses = question_form_fields.send(sender=event, position=pos)\n        data = pos.meta_info_data\n        for r, response in sorted(responses, key=lambda r: str(r[0])):\n            for key, value in response.items():\n                # We need to be this explicit, since OrderedDict.update does not retain ordering\n                self.fields[key] = value\n                value.initial = data.get('question_form_data', {}).get(key)\n\n\nclass BaseInvoiceAddressForm(forms.ModelForm):\n    vat_warning = False\n\n    class Meta:\n        model = InvoiceAddress\n        fields = ('is_business', 'company', 'name', 'street', 'zipcode', 'city', 'country', 'vat_id',\n                  'internal_reference')\n        widgets = {\n            'is_business': BusinessBooleanRadio,\n            'street': forms.Textarea(attrs={'rows': 2, 'placeholder': _('Street and Number')}),\n            'company': forms.TextInput(attrs={'data-display-dependency': '#id_is_business_1'}),\n            'name': forms.TextInput(attrs={}),\n            'vat_id': forms.TextInput(attrs={'data-display-dependency': '#id_is_business_1'}),\n            'internal_reference': forms.TextInput,\n        }\n        labels = {\n            'is_business': ''\n        }\n\n    def __init__(self, *args, **kwargs):\n        self.event = event = kwargs.pop('event')\n        self.request = kwargs.pop('request', None)\n        self.validate_vat_id = kwargs.pop('validate_vat_id')\n        super().__init__(*args, **kwargs)\n        if not event.settings.invoice_address_vatid:\n            del self.fields['vat_id']\n        if not event.settings.invoice_address_required:\n            for k, f in self.fields.items():\n                f.required = False\n                f.widget.is_required = False\n                if 'required' in f.widget.attrs:\n                    del f.widget.attrs['required']\n\n            if event.settings.invoice_name_required:\n                self.fields['name'].required = True\n        elif event.settings.invoice_address_company_required:\n            self.initial['is_business'] = True\n\n            self.fields['is_business'].widget = BusinessBooleanRadio(require_business=True)\n            self.fields['company'].required = True\n            self.fields['company'].widget.is_required = True\n            self.fields['company'].widget.attrs['required'] = 'required'\n            del self.fields['company'].widget.attrs['data-display-dependency']\n            if 'vat_id' in self.fields:\n                del self.fields['vat_id'].widget.attrs['data-display-dependency']\n        else:\n            self.fields['company'].widget.attrs['data-required-if'] = '#id_is_business_1'\n            self.fields['name'].widget.attrs['data-required-if'] = '#id_is_business_0'\n\n    def clean(self):\n        data = self.cleaned_data\n        if not data.get('name') and not data.get('company') and self.event.settings.invoice_address_required:\n            raise ValidationError(_('You need to provide either a company name or your name.'))\n\n        if 'vat_id' in self.changed_data or not data.get('vat_id'):\n            self.instance.vat_id_validated = False\n\n        if self.validate_vat_id and self.instance.vat_id_validated and 'vat_id' not in self.changed_data:\n            pass\n        elif self.validate_vat_id and data.get('is_business') and data.get('country') in EU_COUNTRIES and data.get('vat_id'):\n            if data.get('vat_id')[:2] != str(data.get('country')):\n                raise ValidationError(_('Your VAT ID does not match the selected country.'))\n            try:\n                result = vat_moss.id.validate(data.get('vat_id'))\n                if result:\n                    country_code, normalized_id, company_name = result\n                    self.instance.vat_id_validated = True\n                    self.instance.vat_id = normalized_id\n            except vat_moss.errors.InvalidError:\n                raise ValidationError(_('This VAT ID is not valid. Please re-check your input.'))\n            except vat_moss.errors.WebServiceUnavailableError:\n                logger.exception('VAT ID checking failed for country {}'.format(data.get('country')))\n                self.instance.vat_id_validated = False\n                if self.request and self.vat_warning:\n                    messages.warning(self.request, _('Your VAT ID could not be checked, as the VAT checking service of '\n                                                     'your country is currently not available. We will therefore '\n                                                     'need to charge VAT on your invoice. You can get the tax amount '\n                                                     'back via the VAT reimbursement process.'))\n            except vat_moss.errors.WebServiceError:\n                logger.exception('VAT ID checking failed for country {}'.format(data.get('country')))\n                self.instance.vat_id_validated = False\n                if self.request and self.vat_warning:\n                    messages.warning(self.request, _('Your VAT ID could not be checked, as the VAT checking service of '\n                                                     'your country returned an incorrect result. We will therefore '\n                                                     'need to charge VAT on your invoice. Please contact support to '\n                                                     'resolve this manually.'))\n        else:\n            self.instance.vat_id_validated = False\n\n\nclass BaseInvoiceNameForm(BaseInvoiceAddressForm):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        for f in list(self.fields.keys()):\n            if f != 'name':\n                del self.fields[f]\n", "path": "src/pretix/base/forms/questions.py"}], "after_files": [{"content": "import logging\nfrom decimal import Decimal\n\nimport dateutil.parser\nimport pytz\nimport vat_moss.errors\nimport vat_moss.id\nfrom django import forms\nfrom django.contrib import messages\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom pretix.base.forms.widgets import (\n    BusinessBooleanRadio, DatePickerWidget, SplitDateTimePickerWidget,\n    TimePickerWidget, UploadedFileWidget,\n)\nfrom pretix.base.models import InvoiceAddress, Question\nfrom pretix.base.models.tax import EU_COUNTRIES\nfrom pretix.control.forms import SplitDateTimeField\nfrom pretix.helpers.i18n import get_format_without_seconds\nfrom pretix.presale.signals import question_form_fields\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseQuestionsForm(forms.Form):\n    \"\"\"\n    This form class is responsible for asking order-related questions. This includes\n    the attendee name for admission tickets, if the corresponding setting is enabled,\n    as well as additional questions defined by the organizer.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"\n        Takes two additional keyword arguments:\n\n        :param cartpos: The cart position the form should be for\n        :param event: The event this belongs to\n        \"\"\"\n        cartpos = self.cartpos = kwargs.pop('cartpos', None)\n        orderpos = self.orderpos = kwargs.pop('orderpos', None)\n        pos = cartpos or orderpos\n        item = pos.item\n        questions = pos.item.questions_to_ask\n        event = kwargs.pop('event')\n\n        super().__init__(*args, **kwargs)\n\n        if item.admission and event.settings.attendee_names_asked:\n            self.fields['attendee_name'] = forms.CharField(\n                max_length=255, required=event.settings.attendee_names_required,\n                label=_('Attendee name'),\n                initial=(cartpos.attendee_name if cartpos else orderpos.attendee_name),\n            )\n        if item.admission and event.settings.attendee_emails_asked:\n            self.fields['attendee_email'] = forms.EmailField(\n                required=event.settings.attendee_emails_required,\n                label=_('Attendee email'),\n                initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email)\n            )\n\n        for q in questions:\n            # Do we already have an answer? Provide it as the initial value\n            answers = [a for a in pos.answerlist if a.question_id == q.id]\n            if answers:\n                initial = answers[0]\n            else:\n                initial = None\n            tz = pytz.timezone(event.settings.timezone)\n            if q.type == Question.TYPE_BOOLEAN:\n                if q.required:\n                    # For some reason, django-bootstrap3 does not set the required attribute\n                    # itself.\n                    widget = forms.CheckboxInput(attrs={'required': 'required'})\n                else:\n                    widget = forms.CheckboxInput()\n\n                if initial:\n                    initialbool = (initial.answer == \"True\")\n                else:\n                    initialbool = False\n\n                field = forms.BooleanField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initialbool, widget=widget,\n                )\n            elif q.type == Question.TYPE_NUMBER:\n                field = forms.DecimalField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initial.answer if initial else None,\n                    min_value=Decimal('0.00'),\n                )\n            elif q.type == Question.TYPE_STRING:\n                field = forms.CharField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initial.answer if initial else None,\n                )\n            elif q.type == Question.TYPE_TEXT:\n                field = forms.CharField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    widget=forms.Textarea,\n                    initial=initial.answer if initial else None,\n                )\n            elif q.type == Question.TYPE_CHOICE:\n                field = forms.ModelChoiceField(\n                    queryset=q.options,\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    widget=forms.Select,\n                    empty_label='',\n                    initial=initial.options.first() if initial else None,\n                )\n            elif q.type == Question.TYPE_CHOICE_MULTIPLE:\n                field = forms.ModelMultipleChoiceField(\n                    queryset=q.options,\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    widget=forms.CheckboxSelectMultiple,\n                    initial=initial.options.all() if initial else None,\n                )\n            elif q.type == Question.TYPE_FILE:\n                field = forms.FileField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=initial.file if initial else None,\n                    widget=UploadedFileWidget(position=pos, event=event, answer=initial),\n                )\n            elif q.type == Question.TYPE_DATE:\n                field = forms.DateField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None,\n                    widget=DatePickerWidget(),\n                )\n            elif q.type == Question.TYPE_TIME:\n                field = forms.TimeField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None,\n                    widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),\n                )\n            elif q.type == Question.TYPE_DATETIME:\n                field = SplitDateTimeField(\n                    label=q.question, required=q.required,\n                    help_text=q.help_text,\n                    initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None,\n                    widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')),\n                )\n            field.question = q\n            if answers:\n                # Cache the answer object for later use\n                field.answer = answers[0]\n            self.fields['question_%s' % q.id] = field\n\n        responses = question_form_fields.send(sender=event, position=pos)\n        data = pos.meta_info_data\n        for r, response in sorted(responses, key=lambda r: str(r[0])):\n            for key, value in response.items():\n                # We need to be this explicit, since OrderedDict.update does not retain ordering\n                self.fields[key] = value\n                value.initial = data.get('question_form_data', {}).get(key)\n\n\nclass BaseInvoiceAddressForm(forms.ModelForm):\n    vat_warning = False\n\n    class Meta:\n        model = InvoiceAddress\n        fields = ('is_business', 'company', 'name', 'street', 'zipcode', 'city', 'country', 'vat_id',\n                  'internal_reference')\n        widgets = {\n            'is_business': BusinessBooleanRadio,\n            'street': forms.Textarea(attrs={'rows': 2, 'placeholder': _('Street and Number')}),\n            'company': forms.TextInput(attrs={'data-display-dependency': '#id_is_business_1'}),\n            'name': forms.TextInput(attrs={}),\n            'vat_id': forms.TextInput(attrs={'data-display-dependency': '#id_is_business_1'}),\n            'internal_reference': forms.TextInput,\n        }\n        labels = {\n            'is_business': ''\n        }\n\n    def __init__(self, *args, **kwargs):\n        self.event = event = kwargs.pop('event')\n        self.request = kwargs.pop('request', None)\n        self.validate_vat_id = kwargs.pop('validate_vat_id')\n        super().__init__(*args, **kwargs)\n        if not event.settings.invoice_address_vatid:\n            del self.fields['vat_id']\n        if not event.settings.invoice_address_required:\n            for k, f in self.fields.items():\n                f.required = False\n                f.widget.is_required = False\n                if 'required' in f.widget.attrs:\n                    del f.widget.attrs['required']\n\n            if event.settings.invoice_name_required:\n                self.fields['name'].required = True\n        elif event.settings.invoice_address_company_required:\n            self.initial['is_business'] = True\n\n            self.fields['is_business'].widget = BusinessBooleanRadio(require_business=True)\n            self.fields['company'].required = True\n            self.fields['company'].widget.is_required = True\n            self.fields['company'].widget.attrs['required'] = 'required'\n            del self.fields['company'].widget.attrs['data-display-dependency']\n            if 'vat_id' in self.fields:\n                del self.fields['vat_id'].widget.attrs['data-display-dependency']\n        else:\n            self.fields['company'].widget.attrs['data-required-if'] = '#id_is_business_1'\n            self.fields['name'].widget.attrs['data-required-if'] = '#id_is_business_0'\n\n    def clean(self):\n        data = self.cleaned_data\n        if not data.get('is_business'):\n            data['company'] = ''\n        if not data.get('name') and not data.get('company') and self.event.settings.invoice_address_required:\n            raise ValidationError(_('You need to provide either a company name or your name.'))\n\n        if 'vat_id' in self.changed_data or not data.get('vat_id'):\n            self.instance.vat_id_validated = False\n\n        if self.validate_vat_id and self.instance.vat_id_validated and 'vat_id' not in self.changed_data:\n            pass\n        elif self.validate_vat_id and data.get('is_business') and data.get('country') in EU_COUNTRIES and data.get('vat_id'):\n            if data.get('vat_id')[:2] != str(data.get('country')):\n                raise ValidationError(_('Your VAT ID does not match the selected country.'))\n            try:\n                result = vat_moss.id.validate(data.get('vat_id'))\n                if result:\n                    country_code, normalized_id, company_name = result\n                    self.instance.vat_id_validated = True\n                    self.instance.vat_id = normalized_id\n            except vat_moss.errors.InvalidError:\n                raise ValidationError(_('This VAT ID is not valid. Please re-check your input.'))\n            except vat_moss.errors.WebServiceUnavailableError:\n                logger.exception('VAT ID checking failed for country {}'.format(data.get('country')))\n                self.instance.vat_id_validated = False\n                if self.request and self.vat_warning:\n                    messages.warning(self.request, _('Your VAT ID could not be checked, as the VAT checking service of '\n                                                     'your country is currently not available. We will therefore '\n                                                     'need to charge VAT on your invoice. You can get the tax amount '\n                                                     'back via the VAT reimbursement process.'))\n            except vat_moss.errors.WebServiceError:\n                logger.exception('VAT ID checking failed for country {}'.format(data.get('country')))\n                self.instance.vat_id_validated = False\n                if self.request and self.vat_warning:\n                    messages.warning(self.request, _('Your VAT ID could not be checked, as the VAT checking service of '\n                                                     'your country returned an incorrect result. We will therefore '\n                                                     'need to charge VAT on your invoice. Please contact support to '\n                                                     'resolve this manually.'))\n        else:\n            self.instance.vat_id_validated = False\n\n\nclass BaseInvoiceNameForm(BaseInvoiceAddressForm):\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        for f in list(self.fields.keys()):\n            if f != 'name':\n                del self.fields[f]\n", "path": "src/pretix/base/forms/questions.py"}]}