migrate site id to varchar instead of int
This commit is contained in:
1 parent
61f954a3bd
commit
36639d8c38
16 files changed
+448
-41
No files matched your search
@@ -1,14 +1,42 @@
|
||||
from datetime import date
|
||||
import secrets
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
from django.utils.text import slugify
|
||||
|
||||
from apps.accounts.models import User
|
||||
|
||||
|
||||
def site_name_slug(site_name: str) -> str:
|
||||
"""Slug portion of a site id (no numeric suffix)."""
|
||||
code = slugify(str(site_name or "").strip())[:55]
|
||||
if not code:
|
||||
raise ValidationError({"site_name": "Nama site tidak valid untuk dijadikan id."})
|
||||
return code
|
||||
|
||||
|
||||
def site_id_from_name(site_name: str, *, numeric_suffix: int | None = None) -> str:
|
||||
"""Site PK: `{name-slug}-{4-digit number}`, matching farm dashboard identity."""
|
||||
base = site_name_slug(site_name)
|
||||
if numeric_suffix is None:
|
||||
numeric_suffix = secrets.randbelow(10_000)
|
||||
return f"{base}-{numeric_suffix:04d}"
|
||||
|
||||
|
||||
def allocate_site_id(site_name: str) -> str:
|
||||
"""Pick an unused site_id for HQ-only creates (seeds / manual)."""
|
||||
for _ in range(32):
|
||||
candidate = site_id_from_name(site_name)
|
||||
if not Site.objects.filter(pk=candidate).exists():
|
||||
return candidate
|
||||
raise ValidationError({"site_name": "Gagal membuat id site unik — coba lagi."})
|
||||
|
||||
|
||||
class Site(models.Model):
|
||||
site_id = models.BigAutoField(primary_key=True)
|
||||
# Same shape as farm dashboard Site.site_id; when linked, equals ActiveSite.source_site_id.
|
||||
site_id = models.SlugField(primary_key=True, max_length=64)
|
||||
site_name = models.CharField(max_length=30)
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sites")
|
||||
# Linked when GM/GM Admin adds the site dashboard to their Pengaturan view list.
|
||||
@@ -29,6 +57,11 @@ class Site(models.Model):
|
||||
def __str__(self) -> str:
|
||||
return self.site_name
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.site_id:
|
||||
self.site_id = allocate_site_id(self.site_name)
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class Kandang(models.Model):
|
||||
kandang_id = models.BigAutoField(primary_key=True)
|
||||
|
||||
Reference in new issue
Block a user