Files
thrillwiki_django_no_react/parks/models.py

236 lines
9.0 KiB
Python

from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.core.exceptions import ValidationError
from decimal import Decimal, ROUND_DOWN, InvalidOperation
from typing import Tuple, Optional, Any, TYPE_CHECKING
from django.contrib.contenttypes.fields import GenericRelation
from companies.models import Company
from history_tracking.signals import get_current_branch
from media.models import Photo
from history_tracking.models import HistoricalModel
from location.models import Location
from comments.mixins import CommentableMixin
from media.mixins import PhotoableModel
from location.mixins import LocationMixin
if TYPE_CHECKING:
from rides.models import Ride
class Park(HistoricalModel, CommentableMixin, PhotoableModel, LocationMixin):
comments = GenericRelation('comments.CommentThread') # Centralized reference
id: int # Type hint for Django's automatic id field
STATUS_CHOICES = [
("OPERATING", "Operating"),
("CLOSED_TEMP", "Temporarily Closed"),
("CLOSED_PERM", "Permanently Closed"),
("UNDER_CONSTRUCTION", "Under Construction"),
("DEMOLISHED", "Demolished"),
("RELOCATED", "Relocated"),
]
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
description = models.TextField(blank=True)
status = models.CharField(
max_length=20, choices=STATUS_CHOICES, default="OPERATING"
)
# Details
opening_date = models.DateField(null=True, blank=True)
closing_date = models.DateField(null=True, blank=True)
operating_season = models.CharField(max_length=255, blank=True)
size_acres = models.DecimalField(
max_digits=10, decimal_places=2, null=True, blank=True
)
website = models.URLField(blank=True)
# Statistics
average_rating = models.DecimalField(
max_digits=3, decimal_places=2, null=True, blank=True
)
ride_count = models.IntegerField(null=True, blank=True)
coaster_count = models.IntegerField(null=True, blank=True)
# Relationships
owner = models.ForeignKey(
Company, on_delete=models.SET_NULL, null=True, blank=True, related_name="parks"
)
areas: models.Manager['ParkArea'] # Type hint for reverse relation
rides: models.Manager['Ride'] # Type hint for reverse relation from rides app
# Metadata
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["name"]
excluded_fields = ['comments'] # Exclude from historical tracking
def __str__(self) -> str:
return self.name
def save(self, *args: Any, **kwargs: Any) -> None:
if not self.slug:
self.slug = slugify(self.name)
# Get the branch from context or use default
from history_tracking.signals import get_current_branch
current_branch = get_current_branch()
if current_branch:
# Save in the context of the current branch
super().save(*args, **kwargs)
else:
# If no branch context, save in main branch
from history_tracking.models import VersionBranch
main_branch, _ = VersionBranch.objects.get_or_create(
name='main',
defaults={'metadata': {'type': 'default_branch'}}
)
from history_tracking.signals import ChangesetContextManager
with ChangesetContextManager(branch=main_branch):
super().save(*args, **kwargs)
def get_version_info(self) -> dict:
"""Get version control information for this park"""
from history_tracking.models import VersionBranch, ChangeSet
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(self)
latest_changes = ChangeSet.objects.filter(
content_type=content_type,
object_id=self.pk,
status='applied'
).order_by('-created_at')[:5]
active_branches = VersionBranch.objects.filter(
changesets__content_type=content_type,
changesets__object_id=self.pk,
is_active=True
).distinct()
return {
'latest_changes': latest_changes,
'active_branches': active_branches,
'current_branch': get_current_branch(),
'total_changes': latest_changes.count()
}
def get_absolute_url(self) -> str:
return reverse("parks:park_detail", kwargs={"slug": self.slug})
@classmethod
def get_by_slug(cls, slug: str) -> Tuple['Park', bool]:
"""Get park by current or historical slug"""
try:
return cls.objects.get(slug=slug), False
except cls.DoesNotExist:
# Check historical slugs
history = cls.history.filter(slug=slug).order_by("-history_date").first() # type: ignore[attr-defined]
if history:
try:
return cls.objects.get(pk=history.instance.pk), True
except cls.DoesNotExist as e:
raise cls.DoesNotExist("No park found with this slug") from e
raise cls.DoesNotExist("No park found with this slug")
class ParkArea(HistoricalModel, CommentableMixin, PhotoableModel):
comments = GenericRelation('comments.CommentThread') # Centralized reference
id: int # Type hint for Django's automatic id field
park = models.ForeignKey(Park, on_delete=models.CASCADE, related_name="areas")
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
description = models.TextField(blank=True)
opening_date = models.DateField(null=True, blank=True)
closing_date = models.DateField(null=True, blank=True)
# Relationships
# Metadata
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["name"]
unique_together = ["park", "slug"]
excluded_fields = ['comments'] # Exclude from historical tracking
def __str__(self) -> str:
return f"{self.name} at {self.park.name}"
def save(self, *args: Any, **kwargs: Any) -> None:
if not self.slug:
self.slug = slugify(self.name)
# Get the branch from context or use default
from history_tracking.signals import get_current_branch
current_branch = get_current_branch()
if current_branch:
# Save in the context of the current branch
super().save(*args, **kwargs)
else:
# If no branch context, save in main branch
from history_tracking.models import VersionBranch
main_branch, _ = VersionBranch.objects.get_or_create(
name='main',
defaults={'metadata': {'type': 'default_branch'}}
)
from history_tracking.signals import ChangesetContextManager
with ChangesetContextManager(branch=main_branch):
super().save(*args, **kwargs)
def get_version_info(self) -> dict:
"""Get version control information for this park area"""
from history_tracking.models import VersionBranch, ChangeSet
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(self)
latest_changes = ChangeSet.objects.filter(
content_type=content_type,
object_id=self.pk,
status='applied'
).order_by('-created_at')[:5]
active_branches = VersionBranch.objects.filter(
changesets__content_type=content_type,
changesets__object_id=self.pk,
is_active=True
).distinct()
return {
'latest_changes': latest_changes,
'active_branches': active_branches,
'current_branch': get_current_branch(),
'total_changes': latest_changes.count(),
'parent_park_branch': self.park.get_version_info()['current_branch']
}
def get_absolute_url(self) -> str:
return reverse(
"parks:area_detail",
kwargs={"park_slug": self.park.slug, "area_slug": self.slug},
)
@classmethod
def get_by_slug(cls, slug: str) -> Tuple['ParkArea', bool]:
"""Get area by current or historical slug"""
try:
return cls.objects.get(slug=slug), False
except cls.DoesNotExist:
# Check historical slugs
history = cls.history.filter(slug=slug).order_by("-history_date").first() # type: ignore[attr-defined]
if history:
try:
return cls.objects.get(pk=history.instance.pk), True
except cls.DoesNotExist as e:
raise cls.DoesNotExist("No park area found with this slug") from e
raise cls.DoesNotExist("No park area found with this slug")