Test coverage report: payslip.forms

# payslip.forms: 129 total statements, 100.0% covered

Generated: Sat 2014-11-08 19:42 CET

Source file: /home/tobi/Projects/django-payslip/src/payslip/forms.py

Stats: 121 executed, 0 missed, 8 excluded, 110 ignored

1. `"""Forms for the ``payslip`` app."""`
2. `import md5`
3. ``
4. `from django.contrib.auth.models import make_password, User`
5. `from django.db.models import Q`
6. `from django import forms`
7. `from django.utils import timezone`
8. `from django.utils.translation import ugettext_lazy as _`
9. ``
10. `from dateutil.relativedelta import relativedelta`
11. ``
12. `from payslip.models import (`
13. `Company,`
14. `Employee,`
15. `ExtraField,`
16. `ExtraFieldType,`
17. `Payment,`
18. `)`
19. ``
20. ``
21. `def get_md5_hexdigest(email):`
22. `"""`
23. `Returns an md5 hash for a given email.`
24. ``
25. `The length is 30 so that it fits into Django's ``User.username`` field.`
26. ``
27. `"""`
28. `return md5.new(email).hexdigest()[0:30]`
29. ``
30. ``
31. `def generate_username(email):`
32. `"""`
33. `Generates a unique username for the given email.`
34. ``
35. `The username will be an md5 hash of the given email. If the username exists`
36. `we just append `a` to the email until we get a unique md5 hash.`
37. ``
38. `"""`
39. `username = get_md5_hexdigest(email)`
40. `found_unique_username = False`
41. `while not found_unique_username:`
42. `try:`
43. `User.objects.get(username=username)`
44. `email = '{0}a'.format(email)`
45. `username = get_md5_hexdigest(email)`
46. `except User.DoesNotExist:`
47. `found_unique_username = True`
48. `return username`
49. ``
50. ``
51. `class ExtraFieldFormMixin(object):`
52. `"""Mixin to handle extra field related functions."""`
53. `def __init__(self, *args, **kwargs):`
54. `self.extra_field_types = ExtraFieldType.objects.filter(`
55. `Q(model=self.Meta.model.__name__) | Q(model__isnull=True))`
56. `if kwargs.get('instance'):`
57. `for extra_field_type in self.extra_field_types:`
58. `try:`
59. `field = kwargs.get('instance').extra_fields.get(`
60. `field_type__name=extra_field_type.name)`
61. `except ExtraField.DoesNotExist:`
62. `pass`
63. `else:`
64. `kwargs['initial'].update({'{0}'.format(`
65. `extra_field_type.name): field.value})`
66. `super(ExtraFieldFormMixin, self).__init__(*args, **kwargs)`
67. `for extra_field_type in self.extra_field_types:`
68. `if extra_field_type.fixed_values:`
69. `choices = [(x.value, x.value)`
70. `for x in extra_field_type.extra_fields.all()]`
71. `choices.append(('', '-----'))`
72. `self.fields[extra_field_type.name] = forms.ChoiceField(`
73. `required=False,`
74. `choices=list(set(choices)),`
75. `)`
76. `else:`
77. `self.fields[extra_field_type.name] = forms.CharField(`
78. `required=False, max_length=200)`
79. ``
80. `def save(self, *args, **kwargs):`
81. `resp = super(ExtraFieldFormMixin, self).save(*args, **kwargs)`
82. `for extra_field_type in self.extra_field_types:`
83. `try:`
84. `field_to_save = self.instance.extra_fields.get(`
85. `field_type__name=extra_field_type.name)`
86. `except ExtraField.DoesNotExist:`
87. `field_to_save = None`
88. `if extra_field_type.fixed_values:`
89. `if field_to_save:`
90. `self.instance.extra_fields.remove(`
91. `self.instance.extra_fields.get(`
92. `field_type__name=extra_field_type.name))`
93. `try:`
94. `field_to_save = ExtraField.objects.get(`
95. `field_type__name=extra_field_type.name,`
96. `value=self.data.get(extra_field_type.name))`
97. `except ExtraField.DoesNotExist:`
98. `pass`
99. `else:`
100. `self.instance.extra_fields.add(field_to_save)`
101. `else:`
102. `if field_to_save:`
103. `field_to_save.value = self.data.get(extra_field_type.name)`
104. `field_to_save.save()`
105. `elif self.data.get(extra_field_type.name):`
106. `new_field = ExtraField(`
107. `field_type=extra_field_type,`
108. `value=self.data.get(extra_field_type.name),`
109. `)`
110. `new_field.save()`
111. `self.instance.extra_fields.add(new_field)`
112. `return resp`
113. ``
114. ``
115. `class EmployeeForm(ExtraFieldFormMixin, forms.ModelForm):`
116. `"""Form to create a new Employee instance."""`
117. `first_name = forms.CharField(max_length=30)`
118. `last_name = forms.CharField(max_length=30)`
119. `email = forms.EmailField()`
120. `password = forms.CharField(widget=forms.PasswordInput(), max_length=128)`
121. `retype_password = forms.CharField(widget=forms.PasswordInput(),`
122. `max_length=128)`
123. ``
124. `def __init__(self, company, *args, **kwargs):`
125. `self.company = company`
126. `if kwargs.get('instance'):`
127. `instance = kwargs.get('instance')`
128. `user = instance.user`
129. `kwargs['initial'] = {`
130. `'first_name': user.first_name,`
131. `'last_name': user.last_name,`
132. `'email': user.email,`
133. `}`
134. `super(EmployeeForm, self).__init__(*args, **kwargs)`
135. `if self.instance.id:`
136. `del self.fields['password']`
137. `del self.fields['retype_password']`
138. `if self.company and self.company.pk:`
139. `del self.fields['company']`
140. ``
141. `def clean_email(self):`
142. `"""`
143. `Validate that the username is alphanumeric and is not already`
144. `in use.`
145. ``
146. `"""`
147. `email = self.cleaned_data['email']`
148. `try:`
149. `user = User.objects.get(email__iexact=email)`
150. `except User.DoesNotExist:`
151. `return email`
152. `if self.instance.id and user == self.instance.user:`
153. `return email`
154. `raise forms.ValidationError(`
155. `_('A user with that email already exists.'))`
156. ``
157. `def clean(self):`
158. `"""`
159. `Verifiy that the values entered into the two password fields match.`
160. ``
161. `Note that an error here will end up in ``non_field_errors()`` because`
162. `it doesn't apply to a single field.`
163. ``
164. `"""`
165. `data = self.cleaned_data`
166. `if 'email' not in data:`
167. `return data`
168. `if ('password' in data and 'retype_password' in data):`
169. `if data['password'] != data['retype_password']:`
170. `raise forms.ValidationError(`
171. `_("The two password fields didn't match."))`
172. ``
173. `self.cleaned_data['username'] = generate_username(data['email'])`
174. `return self.cleaned_data`
175. ``
176. `def save(self, *args, **kwargs):`
177. `if self.instance.id:`
178. `User.objects.filter(pk=self.instance.user.pk).update(`
179. `first_name=self.cleaned_data.get('first_name'),`
180. `last_name=self.cleaned_data.get('last_name'),`
181. `email=self.cleaned_data.get('email'),`
182. `)`
183. `else:`
184. `user = User(`
185. `username=self.cleaned_data.get('email'),`
186. `first_name=self.cleaned_data.get('first_name'),`
187. `last_name=self.cleaned_data.get('last_name'),`
188. `email=self.cleaned_data.get('email'),`
189. `password=make_password(self.cleaned_data.get('password')),`
190. `)`
191. `user.save()`
192. `self.instance.user = user`
193. `if self.company and self.company.pk:`
194. `self.instance.company = Company.objects.get(pk=self.company.pk)`
195. `return super(EmployeeForm, self).save(*args, **kwargs)`
196. ``
197. `class Meta:`
198. `model = Employee`
199. `fields = ('company', 'hr_number', 'address', 'title', 'is_manager')`
200. ``
201. ``
202. `class PaymentForm(ExtraFieldFormMixin, forms.ModelForm):`
203. `"""Form to create a new Payment instance."""`
204. `class Meta:`
205. `model = Payment`
206. `fields = ('payment_type', 'employee', 'amount', 'date', 'end_date',`
207. `'description')`
208. ``
209. ``
210. `class ExtraFieldForm(forms.ModelForm):`
211. `"""Form to create a new ExtraField instance."""`
212. `def __init__(self, *args, **kwargs):`
213. `super(ExtraFieldForm, self).__init__(*args, **kwargs)`
214. `self.fields['field_type'].queryset = ExtraFieldType.objects.filter(`
215. `fixed_values=True)`
216. ``
217. `class Meta:`
218. `model = ExtraField`
219. ``
220. ``
221. `class PayslipForm(forms.Form):`
222. `"""Form to create a custom payslip."""`
223. `# First day of the last month`
224. `date_start = forms.DateField(`
225. `initial=timezone.now().replace(day=1) - relativedelta(months=1))`
226. `# Last day of the last month`
227. `date_end = forms.DateField(initial=timezone.now().replace(`
228. `month=timezone.now().month, day=1) - timezone.timedelta(days=1))`
229. `employee = forms.ChoiceField()`
230. ``
231. `def __init__(self, company, *args, **kwargs):`
232. `super(PayslipForm, self).__init__(*args, **kwargs)`
233. `self.company = company`
234. `if self.company:`
235. `self.fields['employee'].choices = [(`
236. `x.id, x) for x in self.company.employees.all()]`
237. `else:`
238. `self.fields['employee'].choices = [(`
239. `x.id, x) for x in Employee.objects.all()]`