336 lines
12 KiB
Python
336 lines
12 KiB
Python
"""Shared helpers for adjustable daily cut-off times and batch reconciliation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import sqlite3
|
|
from datetime import date, datetime, time as dt_time, timedelta
|
|
from pathlib import Path
|
|
|
|
DEFAULT_CUTOFF_TIME = "20:00"
|
|
CUTOFF_RE = re.compile(r"^([01]?\d|2[0-3]):([0-5]\d)$")
|
|
LEGACY_BATCH1_CUTOFF_DATE = "2026-11-18"
|
|
|
|
|
|
def validate_cutoff_time(cutoff_str: str) -> str:
|
|
"""Validate and normalize an HH:MM cut-off time string."""
|
|
raw = (cutoff_str or "").strip().replace(".", ":")
|
|
m = CUTOFF_RE.match(raw)
|
|
if not m:
|
|
raise ValueError(f"Format waktu cut-off tidak valid: '{cutoff_str}' (gunakan HH:MM)")
|
|
hour, minute = int(m.group(1)), int(m.group(2))
|
|
return f"{hour:02d}:{minute:02d}"
|
|
|
|
|
|
def ensure_cutoff_tables(conn: sqlite3.Connection, default_cutoff: str = DEFAULT_CUTOFF_TIME) -> None:
|
|
"""Create site_settings and cutoff_overrides tables idempotently."""
|
|
try:
|
|
norm_default = validate_cutoff_time(default_cutoff)
|
|
except ValueError:
|
|
norm_default = DEFAULT_CUTOFF_TIME
|
|
|
|
cur = conn.cursor()
|
|
cur.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS site_settings (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
"""
|
|
)
|
|
cur.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS cutoff_overrides (
|
|
counting_date TEXT PRIMARY KEY,
|
|
cutoff_time TEXT NOT NULL,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
"""
|
|
)
|
|
cur.execute(
|
|
"INSERT OR IGNORE INTO site_settings (key, value) VALUES ('default_cutoff_time', ?)",
|
|
(norm_default,),
|
|
)
|
|
conn.commit()
|
|
|
|
|
|
def load_cutoff_config(
|
|
conn: sqlite3.Connection, fallback_default: str = DEFAULT_CUTOFF_TIME
|
|
) -> tuple[str, dict[str, str]]:
|
|
"""Return (default_cutoff_time, {counting_date: override_cutoff_time})."""
|
|
try:
|
|
norm_fallback = validate_cutoff_time(fallback_default)
|
|
except ValueError:
|
|
norm_fallback = DEFAULT_CUTOFF_TIME
|
|
|
|
cur = conn.cursor()
|
|
try:
|
|
cur.execute("SELECT value FROM site_settings WHERE key = 'default_cutoff_time'")
|
|
row = cur.fetchone()
|
|
except sqlite3.OperationalError:
|
|
ensure_cutoff_tables(conn, norm_fallback)
|
|
cur.execute("SELECT value FROM site_settings WHERE key = 'default_cutoff_time'")
|
|
row = cur.fetchone()
|
|
|
|
default_cutoff = norm_fallback
|
|
if row and row[0]:
|
|
try:
|
|
default_cutoff = validate_cutoff_time(str(row[0]))
|
|
except ValueError:
|
|
default_cutoff = norm_fallback
|
|
|
|
overrides: dict[str, str] = {}
|
|
cur.execute("SELECT counting_date, cutoff_time FROM cutoff_overrides")
|
|
for c_date, c_time in cur.fetchall():
|
|
if not c_date or not c_time:
|
|
continue
|
|
try:
|
|
overrides[str(c_date)] = validate_cutoff_time(str(c_time))
|
|
except ValueError:
|
|
continue
|
|
|
|
return default_cutoff, overrides
|
|
|
|
|
|
def deadline_for_counting_date(
|
|
counting_date_str: str,
|
|
default_cutoff: str = DEFAULT_CUTOFF_TIME,
|
|
overrides: dict[str, str] | None = None,
|
|
) -> datetime:
|
|
"""
|
|
Compute the exact datetime when operational counting date D closes.
|
|
Evening cut-off (>= 06:00) closes on calendar day D; post-midnight (< 06:00) closes on D + 1.
|
|
"""
|
|
cutoff_str = (overrides or {}).get(counting_date_str) or default_cutoff
|
|
norm = validate_cutoff_time(cutoff_str)
|
|
t: dt_time = datetime.strptime(norm, "%H:%M").time()
|
|
d = date.fromisoformat(counting_date_str)
|
|
if t.hour >= 6:
|
|
return datetime.combine(d, t)
|
|
return datetime.combine(d + timedelta(days=1), t)
|
|
|
|
|
|
def compute_counting_date(
|
|
dt: datetime | None = None,
|
|
default_cutoff: str = DEFAULT_CUTOFF_TIME,
|
|
overrides: dict[str, str] | None = None,
|
|
) -> str:
|
|
"""Determine which operational counting_date (YYYY-MM-DD) a timestamp belongs to."""
|
|
if dt is None:
|
|
dt = datetime.now()
|
|
# Strip tzinfo if aware so comparisons with naive deadline datetimes never fail
|
|
if dt.tzinfo is not None:
|
|
dt = dt.replace(tzinfo=None)
|
|
|
|
d_base = dt.date()
|
|
for delta in (-1, 0, 1, 2):
|
|
cand = d_base + timedelta(days=delta)
|
|
cand_str = cand.isoformat()
|
|
prev_str = (cand - timedelta(days=1)).isoformat()
|
|
prev_dl = deadline_for_counting_date(prev_str, default_cutoff, overrides)
|
|
curr_dl = deadline_for_counting_date(cand_str, default_cutoff, overrides)
|
|
if prev_dl <= dt < curr_dl:
|
|
return cand_str
|
|
|
|
norm = validate_cutoff_time(default_cutoff)
|
|
t = datetime.strptime(norm, "%H:%M").time()
|
|
if dt.time() < t:
|
|
return dt.date().isoformat()
|
|
return (dt.date() + timedelta(days=1)).isoformat()
|
|
|
|
|
|
def get_effective_cutoff(
|
|
conn: sqlite3.Connection,
|
|
counting_date_str: str,
|
|
fallback_default: str = DEFAULT_CUTOFF_TIME,
|
|
) -> tuple[str, bool, str]:
|
|
"""Return (effective_cutoff, is_override, default_cutoff) for a counting date."""
|
|
default_cutoff, overrides = load_cutoff_config(conn, fallback_default)
|
|
if counting_date_str in overrides:
|
|
return overrides[counting_date_str], True, default_cutoff
|
|
return default_cutoff, False, default_cutoff
|
|
|
|
|
|
def update_env_cutoff(env_path: str | Path, cutoff_time: str) -> bool:
|
|
"""Persist new default CUTOFF_TIME and DAILY_CUTOFF_TIME to .env if the file exists."""
|
|
norm = validate_cutoff_time(cutoff_time)
|
|
p = Path(env_path)
|
|
if not p.is_file():
|
|
return False
|
|
|
|
lines = p.read_text(encoding="utf-8").splitlines(keepends=True)
|
|
saw_cutoff = False
|
|
saw_daily = False
|
|
out: list[str] = []
|
|
for line in lines:
|
|
if line.startswith("CUTOFF_TIME="):
|
|
ending = "\n" if line.endswith("\n") else ""
|
|
out.append(f"CUTOFF_TIME={norm}{ending}")
|
|
saw_cutoff = True
|
|
elif line.startswith("DAILY_CUTOFF_TIME="):
|
|
ending = "\n" if line.endswith("\n") else ""
|
|
out.append(f"DAILY_CUTOFF_TIME={norm}{ending}")
|
|
saw_daily = True
|
|
else:
|
|
out.append(line)
|
|
|
|
if not saw_daily:
|
|
if out and not out[-1].endswith("\n"):
|
|
out.append("\n")
|
|
out.append(f"DAILY_CUTOFF_TIME={norm}\n")
|
|
if not saw_cutoff:
|
|
if out and not out[-1].endswith("\n"):
|
|
out.append("\n")
|
|
out.append(f"CUTOFF_TIME={norm}\n")
|
|
|
|
p.write_text("".join(out), encoding="utf-8")
|
|
return True
|
|
|
|
|
|
def _assign_numbers_for_group(
|
|
rows: list[tuple[int, int, str, str]],
|
|
counting_date: str,
|
|
main_batch_min_count: int,
|
|
) -> tuple[list[tuple[int, str]], int, int]:
|
|
"""
|
|
Assign sequential main/sub batch numbers for rows in one (counting_date, camera, label) group.
|
|
rows items: (id, count, start_time, old_batch_number) sorted chronologically.
|
|
Returns ([(id, new_batch_number), ...], main_count, total_count).
|
|
"""
|
|
planned: list[tuple[int, str]] = []
|
|
main_counter = 0
|
|
total_count = 0
|
|
sub_idx = 0
|
|
is_legacy = counting_date <= LEGACY_BATCH1_CUTOFF_DATE
|
|
|
|
for idx, (row_id, count, _st, _old_bn) in enumerate(rows):
|
|
cnt = int(count or 0)
|
|
total_count += cnt
|
|
|
|
if idx == 0 and is_legacy:
|
|
is_child = False
|
|
else:
|
|
is_child = cnt < int(main_batch_min_count)
|
|
|
|
if not is_child:
|
|
main_counter += 1
|
|
if main_counter > 1:
|
|
sub_idx = 0
|
|
planned.append((row_id, str(main_counter)))
|
|
else:
|
|
target_main = main_counter if main_counter >= 1 else 1
|
|
letter = chr(ord("a") + sub_idx) if sub_idx < 26 else f"a{sub_idx}"
|
|
sub_idx += 1
|
|
planned.append((row_id, f"{target_main}{letter}"))
|
|
|
|
return planned, main_counter, total_count
|
|
|
|
|
|
def reconcile_batches_for_cutoff_change(
|
|
conn: sqlite3.Connection,
|
|
target_date: str,
|
|
main_batch_min_count: int = 700,
|
|
fallback_default: str = DEFAULT_CUTOFF_TIME,
|
|
) -> dict:
|
|
"""
|
|
Re-evaluate counting_date for batches in (target_date, target_date + 1 day),
|
|
renumber batches cleanly without breaking SQLite UNIQUE constraints, preserve all video/recount columns,
|
|
and update daily_summaries for both dates.
|
|
"""
|
|
default_cutoff, overrides = load_cutoff_config(conn, fallback_default)
|
|
d0 = date.fromisoformat(target_date)
|
|
next_date = (d0 + timedelta(days=1)).isoformat()
|
|
prev_date = (d0 - timedelta(days=1)).isoformat()
|
|
prev_dl = deadline_for_counting_date(prev_date, default_cutoff, overrides)
|
|
|
|
cur = conn.cursor()
|
|
cur.execute(
|
|
"""
|
|
SELECT id, counting_date, batch_number, camera_name, object_label, count, start_time
|
|
FROM batches
|
|
WHERE counting_date IN (?, ?)
|
|
ORDER BY start_time ASC, id ASC
|
|
""",
|
|
(target_date, next_date),
|
|
)
|
|
rows = cur.fetchall()
|
|
|
|
grouped: dict[tuple[str, str, str], list[tuple[int, int, str, str]]] = {}
|
|
moved_count = 0
|
|
|
|
for r in rows:
|
|
row_id, old_date, old_bn, cam, lbl, count, start_time = r
|
|
try:
|
|
st_dt = datetime.fromisoformat(str(start_time))
|
|
if st_dt.tzinfo is not None:
|
|
st_dt = st_dt.replace(tzinfo=None)
|
|
except Exception:
|
|
st_dt = None
|
|
|
|
if st_dt is None:
|
|
new_date = old_date
|
|
elif st_dt < prev_dl:
|
|
# Never pull batches into prev_date outside the two-day window
|
|
new_date = old_date
|
|
else:
|
|
computed = compute_counting_date(st_dt, default_cutoff, overrides)
|
|
if computed < target_date:
|
|
new_date = target_date
|
|
elif computed > next_date:
|
|
new_date = next_date
|
|
else:
|
|
new_date = computed
|
|
|
|
if new_date != old_date:
|
|
moved_count += 1
|
|
|
|
key = (new_date, str(cam), str(lbl))
|
|
grouped.setdefault(key, []).append((int(row_id), int(count or 0), str(start_time), str(old_bn)))
|
|
|
|
# Phase 1: Temporary placeholders to prevent UNIQUE constraint collisions
|
|
for r in rows:
|
|
row_id = r[0]
|
|
cur.execute("UPDATE batches SET batch_number = ? WHERE id = ?", (f"__tmp_{row_id}", row_id))
|
|
|
|
# Phase 2: Assign final counting_date and renumbered batch_number
|
|
summary_stats: dict[str, dict[str, int]] = {
|
|
target_date: {"batches": 0, "total": 0},
|
|
next_date: {"batches": 0, "total": 0},
|
|
}
|
|
summary_rows: dict[tuple[str, str, str], tuple[int, int]] = {}
|
|
|
|
for (new_date, cam, lbl), grp_rows in grouped.items():
|
|
grp_rows.sort(key=lambda item: (item[2], item[0]))
|
|
planned, main_count, total_count = _assign_numbers_for_group(
|
|
grp_rows, new_date, main_batch_min_count
|
|
)
|
|
for row_id, new_bn in planned:
|
|
cur.execute(
|
|
"UPDATE batches SET counting_date = ?, batch_number = ? WHERE id = ?",
|
|
(new_date, new_bn, row_id),
|
|
)
|
|
summary_rows[(new_date, cam, lbl)] = (total_count, main_count)
|
|
if new_date in summary_stats:
|
|
summary_stats[new_date]["batches"] += main_count
|
|
summary_stats[new_date]["total"] += total_count
|
|
|
|
# Phase 3: Reconcile daily_summaries for target_date and next_date
|
|
cur.execute("DELETE FROM daily_summaries WHERE counting_date IN (?, ?)", (target_date, next_date))
|
|
for (s_date, cam, lbl), (tot_cnt, tot_b) in summary_rows.items():
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO daily_summaries
|
|
(counting_date, camera_name, object_label, total_count, total_batches)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
""",
|
|
(s_date, cam, lbl, tot_cnt, tot_b),
|
|
)
|
|
|
|
conn.commit()
|
|
return {
|
|
"moved_count": moved_count,
|
|
"affected_dates": [target_date, next_date],
|
|
"counts": summary_stats,
|
|
}
|