reports.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import inspect
  2. from functools import cached_property
  3. from django.db import models
  4. from django.urls import reverse
  5. from core.choices import ManagedFileRootPathChoices
  6. from core.models import ManagedFile
  7. from extras.utils import is_report
  8. from netbox.models.features import JobsMixin, WebhooksMixin
  9. from utilities.querysets import RestrictedQuerySet
  10. from .mixins import PythonModuleMixin
  11. __all__ = (
  12. 'Report',
  13. 'ReportModule',
  14. )
  15. class Report(JobsMixin, WebhooksMixin, models.Model):
  16. """
  17. Dummy model used to generate permissions for reports. Does not exist in the database.
  18. """
  19. class Meta:
  20. managed = False
  21. class ReportModuleManager(models.Manager.from_queryset(RestrictedQuerySet)):
  22. def get_queryset(self):
  23. return super().get_queryset().filter(file_root=ManagedFileRootPathChoices.REPORTS)
  24. class ReportModule(PythonModuleMixin, ManagedFile):
  25. """
  26. Proxy model for report module files.
  27. """
  28. objects = ReportModuleManager()
  29. class Meta:
  30. proxy = True
  31. def get_absolute_url(self):
  32. return reverse('extras:report_list')
  33. @cached_property
  34. def reports(self):
  35. def _get_name(cls):
  36. # For child objects in submodules use the full import path w/o the root module as the name
  37. return cls.full_name.split(".", maxsplit=1)[1]
  38. module = self.get_module()
  39. reports = {}
  40. ordered = getattr(module, 'report_order', [])
  41. for cls in ordered:
  42. reports[_get_name(cls)] = cls
  43. for name, cls in inspect.getmembers(module, is_report):
  44. if cls not in ordered:
  45. reports[_get_name(cls)] = cls
  46. return reports
  47. def save(self, *args, **kwargs):
  48. self.file_root = ManagedFileRootPathChoices.REPORTS
  49. return super().save(*args, **kwargs)