-
Notifications
You must be signed in to change notification settings - Fork 532
/
models.py
725 lines (657 loc) · 23.7 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# -*- coding: utf-8 -*-
import datetime
import logging
import os
import re
import tempfile
from functools import partial
from dj.choices import Choices, Country
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import EmailMessage
from django.db import models, transaction
from django.forms import ValidationError
from django.template import Context, Template
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from ralph.accounts.models import Regionalizable
from ralph.assets.country_utils import iso2_to_iso3
from ralph.assets.models.assets import (
Asset,
AssetLastHostname,
AssetModel,
ServiceEnvironment
)
from ralph.assets.utils import move_parents_models
from ralph.attachments.helpers import add_attachment_from_disk
from ralph.lib.external_services import ExternalService, obj_to_dict
from ralph.lib.mixins.fields import NullableCharField
from ralph.lib.mixins.models import (
AdminAbsoluteUrlMixin,
NamedMixin,
TimeStampMixin
)
from ralph.lib.transitions.conf import get_report_name_for_transition_id
from ralph.lib.transitions.decorators import transition_action
from ralph.lib.transitions.fields import TransitionField
from ralph.lib.transitions.models import Transition
from ralph.licences.models import BaseObjectLicence, Licence
from ralph.reports.models import Report, ReportLanguage
IMEI_UNTIL_2003 = re.compile(r'^\d{6} *\d{2} *\d{6} *\d$')
IMEI_SINCE_2003 = re.compile(r'^\d{8} *\d{6} *\d$')
ASSET_HOSTNAME_TEMPLATE = getattr(settings, 'ASSET_HOSTNAME_TEMPLATE', None)
if not ASSET_HOSTNAME_TEMPLATE:
raise ImproperlyConfigured('"ASSET_HOSTNAME_TEMPLATE" must be specified.')
logger = logging.getLogger(__name__)
class Warehouse(
AdminAbsoluteUrlMixin,
NamedMixin,
TimeStampMixin,
models.Model
):
_allow_in_dashboard = True
stocktaking_enabled = models.BooleanField(default=False)
stocktaking_tag_suffix = models.CharField(
max_length=8,
default='',
blank=True
)
class BackOfficeAssetStatus(Choices):
_ = Choices.Choice
new = _("new")
in_progress = _("in progress")
waiting_for_release = _("waiting for release")
used = _("in use")
loan = _("loan")
damaged = _("damaged")
liquidated = _("liquidated")
in_service = _("in service")
installed = _("installed")
free = _("free")
reserved = _("reserved")
sale = _("sale")
class OfficeInfrastructure(
AdminAbsoluteUrlMixin,
NamedMixin,
TimeStampMixin,
models.Model
):
class Meta:
verbose_name = _('Office Infrastructure')
verbose_name_plural = _('Office Infrastructures')
def _is_field_in_transition_actions(actions, field_name):
"""
Returns True if there is field with given name in one of actions.
"""
for action in actions:
if field_name in getattr(action, 'form_fields', {}):
return True
return False
def get_user_iso3_country_name(user):
"""
:param user: instance of django.contrib.auth.models.User which has profile
with country attribute
"""
country_name = Country.name_from_id(int(user.country))
iso3_country_name = iso2_to_iso3(country_name)
return iso3_country_name
def _check_assets_owner(instances, **kwargs):
errors = {}
requester = kwargs.get('requester', None)
if not requester:
return {'__all__': _('requester must be specified')}
for instance in instances:
if requester and instance.owner != requester:
errors[instance] = _('requester is not an owner of the asset')
return errors
def _check_assets_user(instances, **kwargs):
errors = {}
requester = kwargs.get('requester', None)
if not requester:
return {'__all__': _('requester must be specified')}
for instance in instances:
if requester and instance.user != requester:
errors[instance] = _('requester is not an user of the asset')
return errors
def _check_user_assigned(instances, **kwargs):
errors = {}
for instance in instances:
if not instance.user:
errors[instance] = _('user not assigned')
return errors
def autocomplete_if_release_report(actions, objects, field_name='user'):
"""
Returns value of the first item in the list objects of the field_name
if release_report is actions.
Args:
actions: Transition action list
objects: Django models objects
field_name: String of name
Returns:
String value from object
"""
try:
obj = objects[0]
except IndexError:
return None
value = getattr(obj, field_name, None)
if value:
for action in actions:
if action.__name__ == 'release_report':
return str(value.pk)
return None
class BackOfficeAsset(Regionalizable, Asset):
_allow_in_dashboard = True
warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True,
related_name='assets_as_owner',
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True,
related_name='assets_as_user',
)
location = models.CharField(max_length=128, null=True, blank=True)
purchase_order = models.CharField(max_length=50, null=True, blank=True)
loan_end_date = models.DateField(
null=True, blank=True, default=None, verbose_name=_('Loan end date'),
)
status = TransitionField(
default=BackOfficeAssetStatus.new.id,
choices=BackOfficeAssetStatus(),
)
imei = NullableCharField(
max_length=18, null=True, blank=True, unique=True
)
office_infrastructure = models.ForeignKey(
OfficeInfrastructure, null=True, blank=True
)
class Meta:
verbose_name = _('Back Office Asset')
verbose_name_plural = _('Back Office Assets')
@property
def country_code(self):
iso2 = Country.name_from_id(int(self.region.country)).upper()
return iso2_to_iso3(iso2)
def __str__(self):
return '{} (BC: {} / SN: {})'.format(
self.hostname or '-', self.barcode or '-', self.sn or '-'
)
def __repr__(self):
return '<BackOfficeAsset: {}>'.format(self.id)
def validate_imei(self):
return IMEI_SINCE_2003.match(self.imei) or \
IMEI_UNTIL_2003.match(self.imei)
def clean(self):
super().clean()
if self.imei and not self.validate_imei():
raise ValidationError({
'imei': _('%(imei)s is not IMEI format') % {'imei': self.imei}
})
def is_liquidated(self, date=None):
date = date or datetime.date.today()
# check if asset has status 'liquidated' and if yes, check if it has
# this status on given date
if (
self.status == BackOfficeAssetStatus.liquidated and
self._liquidated_at(date)
):
return True
return False
def generate_hostname(self, commit=True, template_vars=None):
def render_template(template):
template = Template(template)
context = Context(template_vars or {})
return template.render(context)
logger.warning(
'Generating new hostname for {} using {} old hostname {}'.format(
self, template_vars, self.hostname
)
)
prefix = render_template(
ASSET_HOSTNAME_TEMPLATE.get('prefix', ''),
)
postfix = render_template(
ASSET_HOSTNAME_TEMPLATE.get('postfix', ''),
)
counter_length = ASSET_HOSTNAME_TEMPLATE.get('counter_length', 5)
last_hostname = AssetLastHostname.increment_hostname(prefix, postfix)
self.hostname = last_hostname.formatted_hostname(fill=counter_length)
if commit:
self.save()
# TODO: add message when hostname was changed
def _try_assign_hostname(self, commit=False, country=None, force=False):
if self.model.category and self.model.category.code:
template_vars = {
'code': self.model.category.code,
'country_code': country or self.country_code,
}
if (
force or
not self.hostname or
self.country_code not in self.hostname
):
self.generate_hostname(commit, template_vars)
@classmethod
def get_autocomplete_queryset(cls):
return cls._default_manager.exclude(
status=BackOfficeAssetStatus.liquidated.id
)
@classmethod
@transition_action(
form_fields={
'user': {
'field': forms.CharField(label=_('User')),
'autocomplete_field': 'user',
'default_value': partial(
autocomplete_if_release_report, field_name='user'
)
}
},
run_after=['unassign_user']
)
def assign_user(cls, instances, **kwargs):
user = get_user_model().objects.get(pk=int(kwargs['user']))
for instance in instances:
instance.user = user
@classmethod
@transition_action(
form_fields={
'owner': {
'field': forms.CharField(label=_('Owner')),
'autocomplete_field': 'owner',
'default_value': partial(
autocomplete_if_release_report, field_name='owner'
)
}
},
help_text=_(
'During this transition owner will be assigned as well as new '
'hostname might be generated for asset (only for particular model '
'categories and only if owner\'s country has changed)'
),
run_after=['unassign_owner']
)
def assign_owner(cls, instances, **kwargs):
owner = get_user_model().objects.get(pk=int(kwargs['owner']))
for instance in instances:
instance.owner = owner
@classmethod
@transition_action(
form_fields={
'licences': {
'field': forms.ModelMultipleChoiceField(
queryset=Licence.objects.all(), label=_('Licence'),
required=False,
),
'autocomplete_field': 'licence',
'autocomplete_model': 'licences.BaseObjectLicence',
'widget_options': {'multi': True},
}
},
run_after=['unassign_licences']
)
def assign_licence(cls, instances, **kwargs):
for instance in instances:
for obj in kwargs['licences']:
BaseObjectLicence.objects.get_or_create(
base_object=instance, licence_id=obj.id,
)
@classmethod
@transition_action(
run_after=['loan_report', 'return_report']
)
def unassign_owner(cls, instances, **kwargs):
for instance in instances:
kwargs['history_kwargs'][instance.pk][
'affected_owner'
] = str(instance.owner)
instance.owner = None
@classmethod
@transition_action(
run_after=['loan_report', 'return_report']
)
def unassign_user(cls, instances, **kwargs):
for instance in instances:
kwargs['history_kwargs'][instance.pk][
'affected_user'
] = str(instance.user)
instance.user = None
@classmethod
@transition_action(
form_fields={
'loan_end_date': {
'field': forms.DateField(
label=_('Loan end date'),
widget=forms.TextInput(attrs={'class': 'datepicker'})
)
}
},
)
def assign_loan_end_date(cls, instances, **kwargs):
for instance in instances:
instance.loan_end_date = kwargs['loan_end_date']
@classmethod
@transition_action()
def unassign_loan_end_date(cls, instances, **kwargs):
for instance in instances:
instance.loan_end_date = None
@classmethod
@transition_action(
form_fields={
'warehouse': {
'field': forms.CharField(label=_('Warehouse')),
'autocomplete_field': 'warehouse'
}
}
)
def assign_warehouse(cls, instances, **kwargs):
warehouse = Warehouse.objects.get(pk=int(kwargs['warehouse']))
for instance in instances:
instance.warehouse = warehouse
@classmethod
@transition_action(
form_fields={
'office_infrastructure': {
'field': forms.CharField(label=_('Office infrastructure')),
'autocomplete_field': 'office_infrastructure'
}
},
)
def assign_office_infrastructure(cls, instances, **kwargs):
office_inf = OfficeInfrastructure.objects.get(
pk=int(kwargs['office_infrastructure'])
)
for instance in instances:
instance.office_infrastructure = office_inf
@classmethod
@transition_action(
form_fields={
'remarks': {
'field': forms.CharField(label=_('Remarks')),
}
}
)
def add_remarks(cls, instances, **kwargs):
for instance in instances:
instance.remarks = '{}\n{}'.format(
instance.remarks, kwargs['remarks']
)
@classmethod
@transition_action(
form_fields={
'task_url': {
'field': forms.URLField(label=_('task URL')),
}
}
)
def assign_task_url(cls, instances, **kwargs):
for instance in instances:
instance.task_url = kwargs['task_url']
@classmethod
@transition_action()
def unassign_licences(cls, instances, **kwargs):
BaseObjectLicence.objects.filter(base_object__in=instances).delete()
@classmethod
@transition_action(
form_fields={
'country': {
'field': forms.ChoiceField(
label=_('Country'),
choices=Country(),
**{
'initial': Country.from_name(
settings.CHANGE_HOSTNAME_ACTION_DEFAULT_COUNTRY.lower() # noqa: E501
).id
}
if settings.CHANGE_HOSTNAME_ACTION_DEFAULT_COUNTRY else {}
),
}
},
)
def change_hostname(cls, instances, **kwargs):
country_id = kwargs['country']
country_name = Country.name_from_id(int(country_id)).upper()
iso3_country_name = iso2_to_iso3(country_name)
for instance in instances:
instance._try_assign_hostname(
country=iso3_country_name, force=True
)
@classmethod
@transition_action(
form_fields={
'user': {
'field': forms.CharField(label=_('User')),
'autocomplete_field': 'user',
},
'owner': {
'field': forms.CharField(label=_('Owner')),
'autocomplete_field': 'owner',
'condition': lambda obj, actions: bool(obj.owner),
}
}
)
def change_user_and_owner(cls, instances, **kwargs):
UserModel = get_user_model() # noqa
user_id = kwargs.get('user', None)
user = UserModel.objects.get(id=user_id)
owner_id = kwargs.get('owner', None)
for instance in instances:
instance.user = user
if not owner_id:
instance.owner = user
else:
instance.owner = UserModel.objects.get(id=owner_id)
instance.location = user.location
@classmethod
def _generate_report(cls, name, requester, instances, language):
report = Report.objects.get(name=name)
template = report.templates.filter(language=language).first()
if not template:
template = report.templates.filter(default=True).first()
template_content = ''
with open(template.template.path, 'rb') as f:
template_content = f.read()
data_instances = [
{
'sn': obj.sn,
'model': str(obj.model),
'imei': obj.imei,
'barcode': obj.barcode,
}
for obj in instances
]
service_pdf = ExternalService('PDF')
result = service_pdf.run(
template=template_content,
data={
'id': ', '.join([str(obj.id) for obj in instances]),
'now': datetime.datetime.now(),
'logged_user': obj_to_dict(requester),
'affected_user': obj_to_dict(instances[0].user),
'owner': obj_to_dict(instances[0].owner),
'assets': data_instances,
}
)
filename = "_".join([
timezone.now().isoformat()[:10],
instances[0].user.get_full_name().lower().replace(' ', '-'),
name,
]) + '.pdf'
with tempfile.TemporaryDirectory() as tmp_dirpath:
output_path = os.path.join(tmp_dirpath, filename)
with open(output_path, 'wb') as f:
f.write(result)
return add_attachment_from_disk(
instances, output_path, requester,
_('Document autogenerated by {} transition.').format(name)
)
@classmethod
@transition_action(precondition=_check_assets_owner)
def must_be_owner_of_asset(cls, instances, **kwargs):
"""Only a precondition matters"""
pass
@classmethod
@transition_action(precondition=_check_assets_user)
def must_be_user_of_asset(cls, instances, **kwargs):
"""Only a precondition matters"""
pass
@classmethod
@transition_action(
form_fields={
'accept': {
'field': forms.BooleanField(
label=_(
'I have read and fully understand and '
'accept the agreement.'
)
)
},
}
)
def accept_asset_release_agreement(cls, instances, requester, **kwargs):
pass
@classmethod
@transition_action(
run_after=['release_report']
)
def assign_requester_as_an_owner(cls, instances, requester, **kwargs):
"""Assign current user as an owner"""
for instance in instances:
instance.owner = requester
instance.save()
@classmethod
@transition_action(
form_fields={
'report_language': {
'field': forms.ModelChoiceField(
label=_('Release report language'),
queryset=ReportLanguage.objects.all().order_by('-default'),
empty_label=None
),
'exclude_from_history': True
}
},
return_attachment=True,
run_after=['assign_owner', 'assign_user']
)
def release_report(cls, instances, requester, transition_id, **kwargs):
report_name = get_report_name_for_transition_id(transition_id)
return cls._generate_report(
instances=instances, name=report_name, requester=requester,
language=kwargs['report_language']
)
@classmethod
@transition_action(run_after=['release_report', 'return_report',
'loan_report'])
def send_attachments_to_user(cls, requester, transition_id, **kwargs):
if kwargs.get('attachments'):
transition = Transition.objects.get(pk=transition_id)
email = EmailMessage(
subject='Documents for {}'.format(transition.name),
body='Please see documents provided in attachments '
'for "{}".'.format(transition.name),
from_email=settings.EMAIL_FROM,
to=[requester.email]
)
for attachment in kwargs['attachments']:
email.attach_file(attachment.file.path)
email.send()
@classmethod
@transition_action(
form_fields={
'report_language': {
'field': forms.ModelChoiceField(
label=_('Return report language'),
queryset=ReportLanguage.objects.all().order_by('-default'),
empty_label=None
),
'exclude_from_history': True
},
},
return_attachment=True,
precondition=_check_user_assigned,
)
def return_report(cls, instances, requester, **kwargs):
return cls._generate_report(
instances=instances, name='return', requester=requester,
language=kwargs['report_language']
)
@classmethod
@transition_action(
form_fields={
'report_language': {
'field': forms.ModelChoiceField(
label=_('Loan report language'),
queryset=ReportLanguage.objects.all().order_by('-default'),
empty_label=None
),
'exclude_from_history': True
}
},
return_attachment=True,
run_after=['assign_owner', 'assign_user', 'assign_loan_end_date']
)
def loan_report(cls, instances, requester, **kwargs):
return cls._generate_report(
name='loan', requester=requester, instances=instances,
language=kwargs['report_language']
)
@classmethod
@transition_action(
verbose_name=_('Convert to DataCenter Asset'),
disable_save_object=True,
only_one_action=True,
form_fields={
'rack': {
'field': forms.CharField(label=_('Rack')),
'autocomplete_field': 'rack',
'autocomplete_model': 'data_center.DataCenterAsset'
},
'position': {
'field': forms.IntegerField(label=_('Position')),
},
'model': {
'field': forms.CharField(label=_('Model')),
'autocomplete_field': 'model',
'autocomplete_model': 'data_center.DataCenterAsset'
},
'service_env': {
'field': forms.CharField(label=_('Service env')),
'autocomplete_field': 'service_env',
'autocomplete_model': 'data_center.DataCenterAsset'
}
}
)
def convert_to_data_center_asset(cls, instances, **kwargs):
from ralph.data_center.models.physical import DataCenterAsset, Rack # noqa
with transaction.atomic():
for i, instance in enumerate(instances):
data_center_asset = DataCenterAsset()
data_center_asset.rack = Rack.objects.get(pk=kwargs['rack'])
data_center_asset.position = kwargs['position']
data_center_asset.service_env = ServiceEnvironment.objects.get(
pk=kwargs['service_env']
)
data_center_asset.model = AssetModel.objects.get(
pk=kwargs['model']
)
move_parents_models(
instance, data_center_asset,
exclude_copy_fields=[
'rack', 'model', 'service_env'
]
)
data_center_asset.save()
# Save new asset to list, required to redirect url.
# RunTransitionView.get_success_url()
instances[i] = data_center_asset
@classmethod
@transition_action()
def assign_hostname_if_empty_or_country_not_match(
cls, instances, **kwargs
):
for instance in instances:
instance._try_assign_hostname(commit=False, force=False)