File size: 1,418 Bytes
df37f6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# import json

# with open("static/files/origin-codes.json", "r", encoding="utf-8") as file:
#     origin_codes = json.load(file)

# def get_origin_id_and_code(origin: str):
#     for x in origin_codes:
#         if x and x.get("name"):
#             if origin == x["name"]:
#                     id = x["id"],
#                     code = x["code"]
#                     id = id[0] if isinstance(id, tuple) else id
#                     return id, code
#     return None, None


import json
import os
from typing import Optional, Tuple

ORIGIN_CODES_PATH = "static/files/origin-codes.json"


def load_origin_codes() -> list[dict]:
    try:
        with open(ORIGIN_CODES_PATH, "r", encoding="utf-8") as file:
            return json.load(file)
    except (FileNotFoundError, json.JSONDecodeError):
        return []


def get_origin_id_and_code(origin_name: str) -> Tuple[Optional[int], Optional[str]]:
    """
    Truy xuất province_id và province_code từ file JSON tĩnh theo tên tỉnh/thành phố.

    Args:
        origin_name (str): Tên thành phố gốc

    Returns:
        Tuple[province_id, province_code] hoặc (None, None) nếu không tìm thấy
    """
    origin_name = origin_name.strip().lower()
    for entry in load_origin_codes():
        name = entry.get("name", "").lower()
        if name == origin_name:
            return entry.get("id"), entry.get("code")
    return None, None