"""문서·조각의 필드와 적용일 검사."""
from datetime import date
import re
FIELDS = ("document_id", "title", "document_type", "product_code",
"effective_from", "effective_to", "revision", "body")
CODE = re.compile(r"([A-Z]{2})[- ]?(\d{3})", re.I)
def normalize_product_code(value):
match = CODE.fullmatch(value.strip())
return f"{match[1].upper()}-{match[2]}" if match else None
def validate_document(document):
if set(document) != set(FIELDS):
raise ValueError("document fields mismatch")
for key in ("document_id", "title", "document_type", "revision", "body"):
if not isinstance(document[key], str) or not document[key].strip():
raise ValueError(f"invalid field: {key}")
code = document["product_code"]
if code is not None and (not isinstance(code, str) or normalize_product_code(code) != code):
raise ValueError("invalid product_code")
start = date.fromisoformat(document["effective_from"])
end = document["effective_to"]
if end is not None and date.fromisoformat(end) < start:
raise ValueError("effective_to precedes effective_from")
return document
def is_effective(record, as_of):
day = date.fromisoformat(as_of)
start = date.fromisoformat(record["effective_from"])
end = record["effective_to"]
return start <= day and (end is None or day <= date.fromisoformat(end))