""" Unified reference-number generator. Format: {PREFIX}-{YYYYMM}-{SEQ:04d} e.g. CMP-202607-0001 PREFIX module prefix (CMP/INQ/OBS/APR/SGT) YYYYMM creation month SEQ 4-digit monthly sequence (global across all hospitals) The sequence is allocated atomically via ReferenceSequence so it is safe under concurrent submissions. Legacy references keep their old format ({PREFIX}-{YYYYMM}-{HOSPITAL_TOKEN}-{SEQ}) — only new records use this generator. """ import re from datetime import datetime def sanitize_hospital_token(hospital) -> str: """Derive a clean, format-safe token from a hospital instance. Kept for backward compatibility but no longer used in the output format. """ code = getattr(hospital, "code", None) if hospital else None if not code: return "GEN" token = re.sub(r"[^A-Z0-9]", "", str(code).upper()) return token or "GEN" def generate_reference(prefix: str, hospital) -> str: """Generate a unified reference number for the given module prefix. Format: CMP-202607-0001 (no hospital token in the output). All hospitals share a single global sequence per (prefix, month). """ from apps.core.models import ReferenceSequence prefix = (prefix or "").upper() year_month = datetime.now().strftime("%Y%m") number = ReferenceSequence.next_number(prefix, "GLOBAL", year_month) return f"{prefix}-{year_month}-{number:04d}"