File size: 3,175 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared response, time, id, and validation helpers for C_48_09_01."""
from __future__ import annotations

import copy
import re
from datetime import datetime
from typing import Any, Dict, Iterable, Optional


ID_PREFIXES: Dict[str, str] = {
    "project": "project",
    "project_user": "user",
    "event": "event",
    "instrument": "instr",
    "instrument_field": "field",
    "record": "record",
    "record_event": "revent",
    "form_instance": "form",
    "field_value": "value",
    "data_query": "query",
    "dictionary_version": "dict",
    "export_job": "export",
    "audit_log": "audit",
    "quality_rule_result": "qresult",
}

LEGACY_ID_PREFIXES: Dict[str, str] = {
    "project": "PRJ",
    "record": "REC",
    "query": "QRY",
    "export": "EXP",
}


def success_response(data: Dict[str, Any], message: str = "") -> Dict[str, Any]:
    return {"status": "success", "data": data, "message": message}


def error_response(error_code: str, message: str) -> Dict[str, Any]:
    return {"status": "error", "data": {}, "message": f"{error_code}: {message}"}


def now_iso() -> str:
    return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")


def deterministic_now() -> str:
    return "2026-02-15T12:00:00Z"


def safe_copy(value: Any) -> Any:
    return copy.deepcopy(value)


def slugify(value: str) -> str:
    text = re.sub(r"[^a-z0-9]+", "-", str(value).strip().lower()).strip("-")
    return text or "item"


def generate_id(entity_type: str, sequence: int) -> str:
    prefix = ID_PREFIXES.get(entity_type, entity_type.strip().lower() or "entity")
    return f"{prefix}-generated-{int(sequence)}"


def validate_id_format(value: str, entity_type: str) -> bool:
    prefix = ID_PREFIXES.get(entity_type)
    if prefix is None:
        return False
    return bool(re.match(rf"^{re.escape(prefix)}-[a-z0-9][a-z0-9-]*$", str(value)))


def extract_id_sequence(value: Any, entity_type: Optional[str] = None) -> Optional[int]:
    text = str(value or "")
    match = re.search(r"(\d+)(?:-[a-z0-9-]+)?$", text)
    if not match:
        return None
    try:
        return int(match.group(1))
    except ValueError:
        return None


def build_humanized_id(entity_type: str, record: Dict[str, Any], *, existing_ids: Optional[Iterable[str]] = None) -> str:
    existing = set(existing_ids or [])
    prefix = ID_PREFIXES.get(entity_type, entity_type)
    pieces = [prefix]
    for key in ("project_id", "record_id", "field_name", "instrument_name", "action", "status", "title", "name"):
        value = record.get(key)
        if value:
            text = str(value)
            if text.startswith("project-"):
                text = text.removeprefix("project-")
            pieces.append(slugify(text))
            if len(pieces) >= 4:
                break
    candidate = "-".join(pieces)
    if candidate not in existing:
        return candidate
    index = 2
    while f"{candidate}-{index}" in existing:
        index += 1
    return f"{candidate}-{index}"


def is_iso_datetime(value: Any) -> bool:
    if not isinstance(value, str) or not value:
        return False
    return bool(re.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$", value))