From 09885a7d0a727688e0219d67cd9056c1320c0133 Mon Sep 17 00:00:00 2001 From: Alberto-Audrix Date: Mon, 16 Nov 2026 11:00:49 +0700 Subject: [PATCH] update batch can be started from API. Adjust data shown (plate, batch type) --- .gitignore | 3 - .../sdd/2026-11-13-unified-batch/progress.md | 11 + batch_crossings.csv | 75 ++++ batch_store.py | 83 ++++- config.env.example | 2 + counter_control.py | 33 +- counter_dashboard.py | 131 +++++-- docs/peer_sync_handoff.md | 263 ++++++++++++++ feedmill.db | Bin 24576 -> 32768 bytes templates/dashboard.html | 69 +++- tests/test_batch_store.py | 196 +++++++++++ tests/test_dashboard.py | 332 ++++++++++++++++++ 12 files changed, 1141 insertions(+), 57 deletions(-) create mode 100644 .superpowers/sdd/2026-11-13-unified-batch/progress.md create mode 100644 docs/peer_sync_handoff.md create mode 100644 tests/test_batch_store.py create mode 100644 tests/test_dashboard.py diff --git a/.gitignore b/.gitignore index 32262ae..b3ec7d5 100644 --- a/.gitignore +++ b/.gitignore @@ -218,6 +218,3 @@ __marimo__/ # Streamlit .streamlit/secrets.toml - -# superpower -.superpowers diff --git a/.superpowers/sdd/2026-11-13-unified-batch/progress.md b/.superpowers/sdd/2026-11-13-unified-batch/progress.md new file mode 100644 index 0000000..a4fe8ce --- /dev/null +++ b/.superpowers/sdd/2026-11-13-unified-batch/progress.md @@ -0,0 +1,11 @@ +# SDD ledger — plan: docs/superpowers/plans/2026-11-13-unified-batch.md + +Pre-flight: Task 1 produces `ensure_batch_schema`, mixed batch state, and status fields consumed by Tasks 2 and 3. No conflict. +Setup ruling: repository has no Git metadata, so task-start/task-done scripts cannot run. Track equivalent test checkpoints here — cost if wrong: audit trail differs from standard Git-based workflow, but no product behavior changes. +Task 1: complete (no Git commit, tests: `venv/bin/python -m unittest tests/test_batch_store.py -v` → 7/7 PASS; `venv/bin/python -m py_compile batch_store.py tests/test_batch_store.py` → PASS). +Task 2: complete (no Git commit, tests: `venv/bin/python -m unittest discover -s tests -v` → 16/16 PASS; `venv/bin/python -m py_compile counter_control.py counter_dashboard.py tests/test_dashboard.py` → PASS). +Task 2: Ruling: `/api/summary` keeps legacy `total_count`/`grand_total` keys and adds `count` as the documented total plus `sack_count`/`box_count` — existing dashboard JS reads `total_count`, so renaming would break it — cost if wrong: one redundant key per summary object. +Task 3: complete (no Git commit, tests: `venv/bin/python -m unittest discover -s tests -v` → 19/19 PASS; compile → PASS; smoke: `GET /`, `/api/current-batch`, `/api/summary`, `/api/batch/status` all HTTP 200). +Task 3: Ruling: day-detail table keeps a `Tipe` column (`SACK`/`BOX`/`MIXED`) plus new `Sack`/`Box`/`Total` columns — legacy rows stay readable per spec and the type pill still explains old history — cost if wrong: one extra column in day-detail view and export. +Task 4: complete (no Git commit, tests: `venv/bin/python -m unittest discover -s tests -v` → 19/19 PASS; compile → PASS; smoke: `/`, `/api/current-batch`, `/api/summary`, `/api/batch/status` HTTP 200). +Task 4: Ruling: API summary keeps legacy `total_count`, `grand_total`, and `grand_total`-style keys while adding `count`, `sack_count`, and `box_count` — dashboard JS reads `total_count`, so removing it would break the existing UI — cost if wrong: one redundant key per summary object. diff --git a/batch_crossings.csv b/batch_crossings.csv index 5d9430f..cc46623 100644 --- a/batch_crossings.csv +++ b/batch_crossings.csv @@ -8564,3 +8564,78 @@ batch,frame,timestamp,object_id 4,21548,2026-11-13T15:13:28.561606,1080 4,21564,2026-11-13T15:13:29.370161,1068 4,21771,2026-11-13T15:13:37.507197,1091 +5,9081,2026-11-13T16:50:09.878491,17 +5,9147,2026-11-13T16:50:12.533359,18 +5,9245,2026-11-13T16:50:16.465239,27 +5,9302,2026-11-13T16:50:18.756818,6 +5,9364,2026-11-13T16:50:21.252888,34 +5,9406,2026-11-13T16:50:22.938666,43 +5,9482,2026-11-13T16:50:25.985167,37 +5,9484,2026-11-13T16:50:26.068657,26 +5,9516,2026-11-13T16:50:27.352185,51 +5,9589,2026-11-13T16:50:30.289739,58 +5,9720,2026-11-13T16:50:35.554928,70 +5,9730,2026-11-13T16:50:35.956097,63 +5,9834,2026-11-13T16:50:40.131189,84 +5,9860,2026-11-13T16:50:41.181203,87 +5,9908,2026-11-13T16:50:43.106657,93 +5,9989,2026-11-13T16:50:46.363078,92 +5,10053,2026-11-13T16:50:48.934068,105 +5,10083,2026-11-13T16:50:50.141627,104 +5,10131,2026-11-13T16:50:52.064258,106 +5,10203,2026-11-13T16:50:54.959750,118 +5,10246,2026-11-13T16:50:56.685716,132 +5,10325,2026-11-13T16:50:59.862191,143 +5,10346,2026-11-13T16:51:00.707937,123 +5,10439,2026-11-13T16:51:04.443175,151 +5,10486,2026-11-13T16:51:06.330642,161 +5,10548,2026-11-13T16:51:08.824954,169 +5,10579,2026-11-13T16:51:10.063679,166 +5,10627,2026-11-13T16:51:12.005699,183 +5,10652,2026-11-13T16:51:12.994356,178 +5,10723,2026-11-13T16:51:15.853077,173 +5,10770,2026-11-13T16:51:17.739080,190 +5,10835,2026-11-13T16:51:20.347599,207 +5,10884,2026-11-13T16:51:22.321131,210 +5,10940,2026-11-13T16:51:24.566496,219 +5,10996,2026-11-13T16:51:26.823680,224 +5,11043,2026-11-13T16:51:28.703570,233 +5,11119,2026-11-13T16:51:31.757746,240 +5,11144,2026-11-13T16:51:32.770857,248 +5,11235,2026-11-13T16:51:36.422310,245 +5,11260,2026-11-13T16:51:37.426446,258 +5,11322,2026-11-13T16:51:39.916203,262 +5,11421,2026-11-13T16:51:43.910134,263 +5,11504,2026-11-13T16:51:47.229330,276 +5,11585,2026-11-13T16:51:50.482684,282 +5,11673,2026-11-13T16:51:54.028609,287 +6,15495,2026-11-13T16:54:27.578470,486 +6,15605,2026-11-13T16:54:32.001042,520 +6,15663,2026-11-13T16:54:34.329634,523 +6,15812,2026-11-13T16:54:40.316245,528 +6,15904,2026-11-13T16:54:44.011616,537 +6,16015,2026-11-13T16:54:48.470656,555 +6,16096,2026-11-13T16:54:51.729053,557 +6,16174,2026-11-13T16:54:54.859978,551 +6,16257,2026-11-13T16:54:58.194340,586 +6,16422,2026-11-13T16:55:04.875327,602 +6,16502,2026-11-13T16:55:08.034759,623 +6,16593,2026-11-13T16:55:11.694946,624 +1,18930,2026-11-16T09:42:24.036055,1229 +2,29220,2026-11-16T10:16:58.420259,1142 +3,49334,2026-11-16T10:30:23.183539,1686 +3,49373,2026-11-16T10:30:24.745742,1687 +3,49408,2026-11-16T10:30:26.146348,1684 +3,49424,2026-11-16T10:30:26.825982,1685 +3,49560,2026-11-16T10:30:32.238002,1688 +3,49706,2026-11-16T10:30:38.106639,1704 +3,49708,2026-11-16T10:30:38.185138,1705 +3,50137,2026-11-16T10:30:55.394399,1717 +3,50170,2026-11-16T10:30:56.721033,1716 +3,50276,2026-11-16T10:31:00.971357,1723 +3,50345,2026-11-16T10:31:03.738527,1725 +3,50421,2026-11-16T10:31:06.764786,1690 +3,50524,2026-11-16T10:31:10.923711,1732 +3,50550,2026-11-16T10:31:11.935220,1736 +3,50669,2026-11-16T10:31:16.680600,1738 +3,50684,2026-11-16T10:31:17.304806,1743 diff --git a/batch_store.py b/batch_store.py index 039a9cb..32087cf 100644 --- a/batch_store.py +++ b/batch_store.py @@ -56,6 +56,18 @@ def ensure_batch_schema(conn): f"ALTER TABLE {table} ADD COLUMN {column} INTEGER NOT NULL DEFAULT 0" ) + batch_columns = {row[1] for row in cur.execute("PRAGMA table_info(batches)")} + for col_name, col_type in ( + ("source", "TEXT"), + ("fcp_batch_number", "INTEGER"), + ("plate", "TEXT"), + ("do_numbers", "TEXT"), + ("expected_sack", "INTEGER"), + ("expected_box", "INTEGER"), + ): + if col_name not in batch_columns: + cur.execute(f"ALTER TABLE batches ADD COLUMN {col_name} {col_type}") + cur.execute( """ UPDATE batches @@ -70,6 +82,20 @@ def ensure_batch_schema(conn): WHERE object_label = 'box' AND box_count = 0 AND count > 0 """ ) + cur.execute( + """ + UPDATE batches + SET object_label = 'sack' + WHERE object_label = 'mixed' AND sack_count > 0 AND box_count = 0 + """ + ) + cur.execute( + """ + UPDATE batches + SET object_label = 'box' + WHERE object_label = 'mixed' AND box_count > 0 AND sack_count = 0 + """ + ) cur.execute( """ UPDATE daily_summaries @@ -196,6 +222,7 @@ class BatchStore: object_label='mixed', sack_count=state['sack_count'], box_count=state['box_count'], + metadata=state, ) self.state_file.unlink(missing_ok=True) return None @@ -261,6 +288,24 @@ class BatchStore: self.log(f'Started batch #{batch_number} for {counting_date} (mixed) [mode={self.batch_mode}]') return batch_number + def update_batch_metadata(self, metadata): + if not isinstance(metadata, dict): + return + with self.state_lock: + if self.current_state is None: + return + for key in ( + 'source', + 'fcp_batch_number', + 'plate', + 'do_numbers', + 'expected_sack', + 'expected_box', + ): + if key in metadata and metadata[key] is not None: + self.current_state[key] = metadata[key] + self.save_state() + def _reset_batch_timer(self): if self.batch_timer: self.batch_timer.cancel() @@ -365,6 +410,7 @@ class BatchStore: object_label=batch_label, sack_count=state.get('sack_count', 0), box_count=state.get('box_count', 0), + metadata=state, ) cps = state['count'] / duration_seconds if duration_seconds > 0 else 0 self.log( @@ -392,6 +438,7 @@ class BatchStore: object_label=None, sack_count=0, box_count=0, + metadata=None, ): batch_label = 'mixed' sack_count = int(sack_count or 0) @@ -403,24 +450,43 @@ class BatchStore: box_count = int(count) else: sack_count = int(count) + if sack_count > 0 and box_count > 0: + row_label = 'mixed' + elif box_count > 0 and sack_count == 0: + row_label = 'box' + elif sack_count > 0 and box_count == 0: + row_label = 'sack' + else: + row_label = batch_label + meta = metadata if isinstance(metadata, dict) else {} + do_nums = meta.get('do_numbers') + if isinstance(do_nums, (list, tuple)): + do_nums = json.dumps(list(do_nums), ensure_ascii=False) cur = self.db.cursor() cur.execute( """ INSERT INTO batches (counting_date, batch_number, camera_name, object_label, count, - sack_count, box_count, start_time, end_time) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + sack_count, box_count, start_time, end_time, + source, fcp_batch_number, plate, do_numbers, expected_sack, expected_box) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( counting_date, batch_number, self.camera_name, - batch_label, + row_label, count, sack_count, box_count, start_time, end_time, + meta.get('source'), + meta.get('fcp_batch_number'), + meta.get('plate'), + do_nums, + meta.get('expected_sack'), + meta.get('expected_box'), ), ) cur.execute( @@ -515,19 +581,26 @@ class BatchStore: if active else None ) + sack_count = self.current_state.get('sack_count', 0) if active else 0 + box_count = self.current_state.get('box_count', 0) if active else 0 return { "active": active, "status": "running" if active else "stopped", "batch_mode": self.batch_mode, "batch_number": self.current_state['batch_number'] if active else None, "object_label": obj_label, + "object_labels": ["sack", "box"] if active else [], "next_batch_number": self.get_next_batch_number(cdate) if not active else None, "count": self.current_state['count'] if active else 0, - "sack_count": self.current_state.get('sack_count', 0) if active else 0, - "box_count": self.current_state.get('box_count', 0) if active else 0, + "sack_count": sack_count, + "box_count": box_count, + "counts": {"sack": sack_count, "box": box_count}, "counting_date": self.current_state['counting_date'] if active else cdate, "start_time": self.current_state['start_time'] if active else None, "last_detection_time": self.current_state['last_detection_time'] if active else None, + "plate": self.current_state.get('plate') if active else None, + "source": self.current_state.get('source') if active else None, + "fcp_batch_number": self.current_state.get('fcp_batch_number') if active else None, } def shutdown(self): diff --git a/config.env.example b/config.env.example index cc68ac1..75db690 100644 --- a/config.env.example +++ b/config.env.example @@ -181,3 +181,5 @@ DASHBOARD_HOST=0.0.0.0 DASHBOARD_PORT=7000 FLASK_DEBUG=false CURRENT_BATCH_PATH=/opt/feedmill/bytetrack_current_batch.json +# Shared secret for FCP -> ZenAI peer sync (X-API-Key header) +PEER_API_TOKEN= diff --git a/counter_control.py b/counter_control.py index f74fab5..3b9ba31 100644 --- a/counter_control.py +++ b/counter_control.py @@ -42,33 +42,52 @@ class ControlHandler(BaseHTTPRequestHandler): "/api/batch/start/sack", "/api/batch/start/box", ): - self._read_json_body() + body = self._read_json_body() status = self.server.store.get_status() if status["active"]: + if body and hasattr(self.server.store, "update_batch_metadata"): + self.server.store.update_batch_metadata(body) + sack_c = status.get("sack_count", 0) + box_c = status.get("box_count", 0) self._send_json(200, { "success": True, "message": f"Batch #{status['batch_number']} is already running", "batch_number": status["batch_number"], "object_label": "mixed", + "object_labels": ["sack", "box"], "count": status.get("count", 0), - "sack_count": status.get("sack_count", 0), - "box_count": status.get("box_count", 0), + "sack_count": sack_c, + "box_count": box_c, + "counts": {"sack": sack_c, "box": box_c}, + "plate": body.get("plate") or status.get("plate"), "status": "running", }) else: batch_num = self.server.store.start_new_batch() + if body: + if hasattr(self.server.store, "update_batch_metadata"): + self.server.store.update_batch_metadata(body) + elif hasattr(self.server.store, "current_state") and isinstance(self.server.store.current_state, dict): + plate = body.get("plate") + if plate: + self.server.store.current_state["plate"] = plate + if hasattr(self.server.store, "save_state"): + self.server.store.save_state() self._send_json(200, { "success": True, "message": f"Started Batch #{batch_num}", "batch_number": batch_num, "object_label": "mixed", + "object_labels": ["sack", "box"], "count": 0, "sack_count": 0, "box_count": 0, + "counts": {"sack": 0, "box": 0}, + "plate": body.get("plate") or None, "status": "running", }) elif clean_path in ("/stop", "/api/stop", "/api/batch/stop"): - self._read_json_body() + body = self._read_json_body() status = self.server.store.get_status() if not status["active"]: self._send_json(200, { @@ -77,19 +96,25 @@ class ControlHandler(BaseHTTPRequestHandler): "status": "stopped", }) else: + if body and hasattr(self.server.store, "update_batch_metadata"): + self.server.store.update_batch_metadata(body) cur_num = status["batch_number"] cur_count = status["count"] cur_sack = status.get("sack_count", 0) cur_box = status.get("box_count", 0) + cur_plate = body.get("plate") or status.get("plate") ok = self.server.store.end_batch(closed_by="manual") self._send_json(200, { "success": True, "message": f"Batch #{cur_num} stopped ({cur_count} items)", "batch_number": cur_num, "object_label": "mixed", + "object_labels": ["sack", "box"], "count": cur_count, "sack_count": cur_sack, "box_count": cur_box, + "counts": {"sack": cur_sack, "box": cur_box}, + "plate": cur_plate, "persisted": ok, "status": "stopped", }) diff --git a/counter_dashboard.py b/counter_dashboard.py index b68f527..ac22f45 100644 --- a/counter_dashboard.py +++ b/counter_dashboard.py @@ -133,9 +133,9 @@ def get_next_batch_number_db(counting_date=None): return 1 -def _send_counter_command(endpoint): +def _send_counter_command(endpoint, data=b""): url = f"{COUNTER_CONTROL_URL}/{endpoint}" - req = urllib.request.Request(url, data=b"", method="POST") + req = urllib.request.Request(url, data=data, method="POST") try: with urllib.request.urlopen(req, timeout=4.0) as resp: return json.loads(resp.read().decode("utf-8")), resp.status @@ -187,6 +187,19 @@ def _separate_counts(raw_label, count, sack_count=None, box_count=None): return sacks, boxes +def _resolve_batch_label(raw_label, sack_count, box_count): + """Return 'sack', 'box', or 'mixed' based on actual counted contents.""" + sacks = int(sack_count or 0) + boxes = int(box_count or 0) + if sacks > 0 and boxes > 0: + return "mixed" + if boxes > 0 and sacks == 0: + return "box" + if sacks > 0 and boxes == 0: + return "sack" + return _normalize_obj_label(raw_label) + + @app.route("/api/current-batch") def api_current_batch(): cdate = get_counting_date() @@ -211,6 +224,7 @@ def api_current_batch(): "count": data.get("count", 0), "sack_count": sack_count, "box_count": box_count, + "plate": data.get("plate") or None, "start_time": data.get("start_time"), "last_detection_time": data.get("last_detection_time"), } @@ -229,6 +243,7 @@ def api_current_batch(): "box_count": 0, "batch_number": None, "object_label": None, + "plate": None, "next_batch_number": next_batch, "counting_date": cdate, } @@ -247,22 +262,69 @@ def api_current_batch(): "box_count": 0, "batch_number": None, "object_label": None, + "plate": None, "next_batch_number": next_batch, "counting_date": cdate, } ), 500 +def _get_peer_api_token(): + env_token = os.getenv("PEER_API_TOKEN", "").strip() + if env_token: + return env_token + for candidate in ( + os.path.join(_DEFAULT_DIR, "peer_sync_token.txt"), + os.path.join(_DEFAULT_DIR, "docs", "peer_sync_token.txt"), + ): + if os.path.isfile(candidate): + try: + with open(candidate, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if line.startswith("PEER_API_TOKEN="): + return line.split("=", 1)[1].strip() + except Exception: + pass + return "" + + +def _check_peer_api_key(): + if "X-API-Key" not in request.headers: + return None + provided = request.headers.get("X-API-Key", "").strip() + expected = _get_peer_api_token() + if not expected or provided != expected: + return jsonify({"success": False, "error": "unauthorized"}), 401 + return None + + @app.route("/api/batch/start", methods=["POST"]) @app.route("/api/batch/start/", methods=["POST"]) def api_batch_start(object_label=None): - data, code = _send_counter_command("start") + auth_err = _check_peer_api_key() + if auth_err is not None: + return auth_err + raw = request.get_data() + data, code = ( + _send_counter_command("start", data=raw) + if raw + else _send_counter_command("start") + ) return jsonify(data), code @app.route("/api/batch/stop", methods=["POST"]) def api_batch_stop(): - data, code = _send_counter_command("stop") + auth_err = _check_peer_api_key() + if auth_err is not None: + return auth_err + raw = request.get_data() + data, code = ( + _send_counter_command("stop", data=raw) + if raw + else _send_counter_command("stop") + ) return jsonify(data), code @@ -303,6 +365,7 @@ def api_batch_status(): "count": state_data.get("count", 0), "sack_count": sack_count, "box_count": box_count, + "plate": state_data.get("plate") or None, "counting_date": state_data.get("counting_date", cdate), "start_time": state_data.get("start_time"), "last_detection_time": state_data.get("last_detection_time"), @@ -316,6 +379,7 @@ def api_batch_status(): "batch_mode": BATCH_MODE, "batch_number": None, "object_label": None, + "plate": None, "next_batch_number": next_batch, "count": 0, "sack_count": 0, @@ -335,7 +399,7 @@ def api_previous_batch(): cur.execute( """ SELECT counting_date, batch_number, object_label, count, sack_count, box_count, - start_time, end_time, + plate, start_time, end_time, ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes FROM batches ORDER BY end_time DESC @@ -353,10 +417,13 @@ def api_previous_batch(): "success": True, "date": row["counting_date"], "batch_number": row["batch_number"], - "object_label": _normalize_obj_label(row["object_label"]), + "object_label": _resolve_batch_label( + row["object_label"], sack_count, box_count + ), "count": row["count"], "sack_count": sack_count, "box_count": box_count, + "plate": row["plate"] or None, "start_time": row["start_time"], "end_time": row["end_time"], "duration_minutes": row["duration_minutes"], @@ -516,7 +583,7 @@ def api_day_detail(date): cur = conn.cursor() cur.execute( """ - SELECT batch_number, object_label, count, sack_count, box_count, start_time, end_time, + SELECT batch_number, object_label, count, sack_count, box_count, plate, start_time, end_time, ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes FROM batches WHERE counting_date = ? @@ -535,10 +602,13 @@ def api_day_detail(date): batches.append( { "batch_number": row["batch_number"], - "object_label": _normalize_obj_label(row["object_label"]), + "object_label": _resolve_batch_label( + row["object_label"], sack_count, box_count + ), "count": row["count"], "sack_count": sack_count, "box_count": box_count, + "plate": row["plate"] or None, "start_time": row["start_time"], "end_time": row["end_time"], "duration_minutes": duration, @@ -584,7 +654,7 @@ def api_recent_batches(): cur.execute( """ SELECT counting_date, batch_number, object_label, count, sack_count, box_count, - start_time, end_time, + plate, start_time, end_time, ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes FROM batches ORDER BY end_time DESC @@ -601,10 +671,13 @@ def api_recent_batches(): { "date": row["counting_date"], "batch_number": row["batch_number"], - "object_label": _normalize_obj_label(row["object_label"]), + "object_label": _resolve_batch_label( + row["object_label"], sack_count, box_count + ), "count": row["count"], "sack_count": sack_count, "box_count": box_count, + "plate": row["plate"] or None, "start_time": row["start_time"], "end_time": row["end_time"], "duration_minutes": row["duration_minutes"] or 0, @@ -696,7 +769,7 @@ def export_daily_xlsx(): cur.execute( """ SELECT counting_date, batch_number, object_label, count, sack_count, box_count, - start_time, end_time, + plate, start_time, end_time, ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes FROM batches WHERE counting_date >= ? @@ -714,7 +787,7 @@ def export_daily_xlsx(): wb = Workbook() ws = wb.active ws.title = "Batch Details" - _style_header(ws, [("A", "Date"), ("B", "Batch #"), ("C", "Type"), ("D", "Sack"), ("E", "Box"), ("F", "Total"), ("G", "Start Time"), ("H", "End Time"), ("I", "Duration (min)")]) + _style_header(ws, [("A", "Date"), ("B", "Batch #"), ("C", "Plate"), ("D", "Type"), ("E", "Sack"), ("F", "Box"), ("G", "Total"), ("H", "Start Time"), ("I", "End Time"), ("J", "Duration (min)")]) for r_idx, row in enumerate(rows, 2): sack_count, box_count = _separate_counts( @@ -722,13 +795,14 @@ def export_daily_xlsx(): ) ws.cell(row=r_idx, column=1, value=row["counting_date"]) ws.cell(row=r_idx, column=2, value=row["batch_number"]) - ws.cell(row=r_idx, column=3, value=_normalize_obj_label(row["object_label"]).upper()) - ws.cell(row=r_idx, column=4, value=sack_count) - ws.cell(row=r_idx, column=5, value=box_count) - ws.cell(row=r_idx, column=6, value=row["count"]) - ws.cell(row=r_idx, column=7, value=row["start_time"]) - ws.cell(row=r_idx, column=8, value=row["end_time"]) - ws.cell(row=r_idx, column=9, value=row["duration_minutes"] or 0) + ws.cell(row=r_idx, column=3, value=row["plate"] or "-") + ws.cell(row=r_idx, column=4, value=_resolve_batch_label(row["object_label"], sack_count, box_count).upper()) + ws.cell(row=r_idx, column=5, value=sack_count) + ws.cell(row=r_idx, column=6, value=box_count) + ws.cell(row=r_idx, column=7, value=row["count"]) + ws.cell(row=r_idx, column=8, value=row["start_time"]) + ws.cell(row=r_idx, column=9, value=row["end_time"]) + ws.cell(row=r_idx, column=10, value=row["duration_minutes"] or 0) _auto_width(ws) filename = f"{SITE_NAME}_daily_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx" @@ -742,7 +816,7 @@ def export_day_xlsx(date): cur = conn.cursor() cur.execute( """ - SELECT batch_number, object_label, count, sack_count, box_count, start_time, end_time, + SELECT batch_number, object_label, count, sack_count, box_count, plate, start_time, end_time, ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes FROM batches WHERE counting_date = ? @@ -760,20 +834,21 @@ def export_day_xlsx(date): wb = Workbook() ws = wb.active ws.title = f"Day {date}" - _style_header(ws, [("A", "Batch Number"), ("B", "Type"), ("C", "Sack"), ("D", "Box"), ("E", "Total"), ("F", "Start Time"), ("G", "End Time"), ("H", "Duration (min)")]) + _style_header(ws, [("A", "Batch Number"), ("B", "Plate"), ("C", "Type"), ("D", "Sack"), ("E", "Box"), ("F", "Total"), ("G", "Start Time"), ("H", "End Time"), ("I", "Duration (min)")]) for r_idx, row in enumerate(rows, 2): sack_count, box_count = _separate_counts( row["object_label"], row["count"], row["sack_count"], row["box_count"] ) ws.cell(row=r_idx, column=1, value=row["batch_number"]) - ws.cell(row=r_idx, column=2, value=_normalize_obj_label(row["object_label"]).upper()) - ws.cell(row=r_idx, column=3, value=sack_count) - ws.cell(row=r_idx, column=4, value=box_count) - ws.cell(row=r_idx, column=5, value=row["count"]) - ws.cell(row=r_idx, column=6, value=row["start_time"]) - ws.cell(row=r_idx, column=7, value=row["end_time"]) - ws.cell(row=r_idx, column=8, value=row["duration_minutes"] or 0) + ws.cell(row=r_idx, column=2, value=row["plate"] or "-") + ws.cell(row=r_idx, column=3, value=_resolve_batch_label(row["object_label"], sack_count, box_count).upper()) + ws.cell(row=r_idx, column=4, value=sack_count) + ws.cell(row=r_idx, column=5, value=box_count) + ws.cell(row=r_idx, column=6, value=row["count"]) + ws.cell(row=r_idx, column=7, value=row["start_time"]) + ws.cell(row=r_idx, column=8, value=row["end_time"]) + ws.cell(row=r_idx, column=9, value=row["duration_minutes"] or 0) _auto_width(ws) filename = f"{SITE_NAME}_day_detail_{date}.xlsx" diff --git a/docs/peer_sync_handoff.md b/docs/peer_sync_handoff.md new file mode 100644 index 0000000..22ec292 --- /dev/null +++ b/docs/peer_sync_handoff.md @@ -0,0 +1,263 @@ +# Handoff: FCP → zenai_nano_fcp batch sync + +Status: **FCP side is DONE and shipped. zenai side is NOT done yet.** + +## 0. Test topology (read first) + +| Role | Host | Ports | Notes | +|---|---|---|---| +| FCP **mirror** (test target) | `192.168.192.89` | operator `:5000`, office `:5721` | Repo checkout + systemd services (`karung-counter`, `karung-counter-dashboard`) run here. **Use this host for all manual start/stop tests.** | +| zenai_nano_fcp (peer counter, NanoPi) | `192.168.192.209` | dashboard `:7000`, internal control `127.0.0.1:5000`, camera RTSP `:8554` | Peer API lives here. `PEER_API_URL=http://192.168.192.209:7000` | +| LIVE FCP | other host (unknown yet) | — | **DO NOT touch.** No deploy, no restart, no batch start/stop there until the owner says so. | + +Rules for the zenai-side developer: +- Test only against `192.168.192.89` (FCP mirror) and `192.168.192.209` (peer). +- The live FCP host is out of scope. Do not point `PEER_API_URL` at it. +- `PEER_API_URL` lives in the FCP `.env` (gitignored) — never commit it. +- The zenai dashboard currently has no active batch and sits in `manual` mode; + a test start/stop pair is safe. +- FCP mirror ports: operator UI `http://192.168.192.89:5000`, office UI + `http://192.168.192.89:5721` (office only: mode / model_mode / require_plate / + require_do writes, batch delete, OCR engine). +- FCP mirror batch mode was switched `auto` → `manual` on 2026-11-13 for these + tests (`/opt/jetson-counter/batch_mode.json`). Manual start/stop is rejected in + `auto` mode (HTTP 409 `wrong_mode`). + +FCP is the source of truth for counts. FCP pushes every **manual** batch +start/stop to the zenai counter (RK3588/NanoPi device, `/opt/feedmill`, +dashboard port 7000) so both sides count the same load. + +Until the zenai work below is implemented, FCP already sends the requests and +zenai answers with its **single-label** behaviour. FCP detects that and shows the +operator a warning (`Peer hanya menerima satu label (sack) …`). + +## 1. What FCP sends + +Base URL from FCP `.env`: + +``` +PEER_API_URL=http://192.168.192.209:7000 # zenai peer (empty => peer sync disabled) +PEER_API_TOKEN= # -> X-API-Key header (value in docs/peer_sync_token.txt) +PEER_API_TIMEOUT=5 # seconds, per request +``` + +Requests are plain JSON POSTs. Headers: `Content-Type: application/json`, +`X-API-Key: `. + +### 1.1 Start — `POST {PEER_API_URL}/api/batch/start` + +```json +{ + "source": "fcp-semarang", + "object_label": "sack", + "object_labels": ["sack", "box"], + "fcp_batch_number": 12, + "counting_date": "2026-11-13", + "plate": "B 1234 XYZ", + "do_numbers": ["DO-2026-0011"], + "expected_sack": 40, + "expected_box": 10, + "started_at": "2026-11-13T09:12:03" +} +``` + +### 1.2 Stop — `POST {PEER_API_URL}/api/batch/stop` + +```json +{ + "source": "fcp-semarang", + "fcp_batch_number": 12, + "counting_date": "2026-11-13", + "plate": "B 1234 XYZ", + "net_sack": 38, + "net_box": 9, + "ended_at": "2026-11-13T10:04:57" +} +``` + +`net_sack` / `net_box` are FCP's final numbers — **reference only**. zenai keeps +its own counts; FCP stays authoritative for reporting. + +## 2. What FCP expects back + +FCP accepts the **existing** zenai reply shape, no change required: + +```json +{"success": true, "message": "Started Batch #7 (SACK)", "batch_number": 7, + "object_label": "sack", "status": "running"} +``` + +Rules FCP applies to the reply: + +| Reply | FCP reaction | +|---|---| +| HTTP 200 + `success: true` | ok | +| HTTP 200 + `success: false`, error contains `No active batch` (stop only) | ok — peer was already stopped | +| HTTP 200 + `success: false`, other error | failed, warning shown | +| HTTP 4xx | failed, no retry | +| HTTP 5xx / timeout / refused | failed after 2 attempts (0.5 s apart), warning shown | + +Peer failures never block the FCP batch (fail-soft): +- **start failed** → zenai counts 0 for that batch; operator informed. +- **stop failed** → zenai keeps counting; operator must stop zenai manually. + +FCP also raises a warning when it asked for several labels (`object_labels`) but +the reply only carries a single `object_label` — that means the peer still +counts one class only. + +## 3. Work on the zenai side (not yet done) + +Repo: `/home/jetson/Feedmill_Semarang_Project/zenai_nano_fcp` (device path +`/opt/feedmill`). + +### 3.1 Multi-label batches (required) + +Today `batch_store.py` is single-label: +- `_normalize_batch_label()` accepts only `sack` / `box`. +- `start_new_batch()` stores one `object_label` and one `count`. +- `record_counted_object_crossing()` **ignores** any crossing whose label does + not equal the active batch label. + +Needed: one batch that counts `sack` and `box` separately. + +- `_normalize_batch_label` → normalise a **list** of labels + (`object_labels: ["sack", "box"]`), keep the old single `object_label` field + working for the zenai UI (it may send `object_label: "sack"`). +- Batch state: keep `counts: {"sack": N, "box": M}` (total = `sum(counts.values())`). + Migrate the old `count` int for backward compatibility. +- `record_counted_object_crossing(track_id, object_label)`: count the crossing + when the label is in the active batch's label set; keep per-label counters. + The counted-event dedup key must include the label + (`f"{label}:{track_id}"`), otherwise sack and box IDs collide. +- `end_batch()` must persist per-label counts (DB migration needed for the + `batches` table: add `counts_json` or `box_count`/`sack_count` columns). +- Batch discard rule ("discard when 0 counted") must consider the **total**. + +### 3.2 Forward the request body (required) + +`counter_dashboard.py::_send_counter_command()` posts an **empty body**, so the +JSON FCP sends is dropped before it reaches `counter_control.py`. + +- `api_batch_start` must forward the full JSON body to + `http://127.0.0.1:5000/api/batch/start` (and `api_batch_stop` likewise). +- `counter_control.py` must read the body: `object_labels` (list) or + `object_label` (single), plus the metadata (`source`, `fcp_batch_number`, + `counting_date`, `plate`, `do_numbers`, `expected_sack`, `expected_box`). +- Store the metadata on the zenai batch row (new columns or a JSON blob) so + zenai history can be joined with FCP history by `source` + `fcp_batch_number`. + +### 3.3 API key (now sent by FCP) + +- FCP sends `X-API-Key: ` on every start/stop request. +- The shared secret lives in `docs/peer_sync_token.txt` (**gitignored**) — copy + that file together with this handoff. Same value is in the FCP `.env`. +- Accept `X-API-Key` on `/api/batch/start` and `/api/batch/stop`. +- Validate **only when the header is present**, so the zenai dashboard UI keeps + working unchanged. +- Reject with HTTP 401 + `{"success": false, "error": "unauthorized"}` when the + header is present but wrong. FCP treats 4xx as failed (no retry) and warns. + +### 3.4 Idempotency (recommended) + +- Start when a batch is already active → return the existing batch, HTTP 200 + (`status: "running"`). Already the case in `counter_control.py`; keep it. +- Stop with no active batch → HTTP 200 `{"success": false, "error": "No active + batch to stop"}`. Already the case; keep it (FCP treats it as success). +- FCP re-sends a start when the operator presses "Mulai" twice; the peer must + not create a second batch. + +### 3.5 Reply shape (optional but recommended) + +When the peer supports several labels it should answer with both: + +```json +{"success": true, "batch_number": 7, "object_labels": ["sack", "box"], + "counts": {"sack": 12, "box": 3}, "status": "running"} +``` + +FCP stops warning when `object_labels` is present in the reply. + +## 4. Verification checklist (zenai side) + +```bash +# start (multi-label + metadata + api key) +curl -s -X POST http://127.0.0.1:7000/api/batch/start \ + -H 'Content-Type: application/json' \ + -H 'X-API-Key: ' \ + -d '{"source":"fcp-semarang","object_label":"sack","object_labels":["sack","box"], + "fcp_batch_number":12,"counting_date":"2026-11-13","plate":"B 1234 XYZ", + "do_numbers":["DO-2026-0011"],"expected_sack":40,"expected_box":10, + "started_at":"2026-11-13T09:12:03"}' + +# stop +curl -s -X POST http://127.0.0.1:7000/api/batch/stop \ + -H 'Content-Type: application/json' -H 'X-API-Key: ' \ + -d '{"source":"fcp-semarang","fcp_batch_number":12,"counting_date":"2026-11-13", + "plate":"B 1234 XYZ","net_sack":38,"net_box":9,"ended_at":"2026-11-13T10:04:57"}' +``` + +Check: +1. Reply has `success: true` and `object_labels: ["sack","box"]`. +2. A sack crossing and a box crossing both raise the **total** count, and the + per-label counters differ. +3. The stored batch row keeps `source` / `fcp_batch_number` / plate / DO numbers. +4. Stop replies with per-label counts and the row is persisted. + +FCP side (from the Jetson, `PEER_API_URL` set): + +```bash +# manual batch start/stop in the operator UI -> watch the FCP log +journalctl -u karung-counter-dashboard | grep PEER +``` + +## 5. Verified test results (FCP mirror, 2026-11-13) + +Full operator-button → zenai chain tested against the real peer +(`192.168.192.209:7000`), FCP mirror `192.168.192.89` in `manual` batch mode: + +| Step | FCP operator call | FCP result | zenai result | +|---|---|---|---| +| start | `POST http://192.168.192.89:5000/api/batch/start {"plate":"B 9999 TEST"}` | batch #12 started, `peer_sync.ok=true`, warning `Peer hanya menerima satu label (sack) …` | batch #4 running, `object_label: "sack"` | +| stop | `POST http://192.168.192.89:5000/api/batch/stop` | batch #12 closed, `peer_sync.ok=true` | batch #4 stopped, `count: 0` | + +Reproduce on the mirror: + +```bash +curl -s -X POST http://192.168.192.89:5000/api/batch/start \ + -H 'Content-Type: application/json' -d '{"plate":"B 9999 TEST"}' +curl -s -X POST http://192.168.192.89:5000/api/batch/stop +curl -s http://192.168.192.209:7000/api/batch/status +journalctl -u karung-counter-dashboard | grep PEER +``` + +FCP mirror side effects from that test (harmless, mirror only): batch #12 in the +mirror DB with plate `B9999TEST`, and the mirror batch mode left on `manual`. + +### 5.1 zenai defects found during that test + +1. **Single label only.** Reply carries `object_label: "sack"`; FCP asked for + `object_labels: ["sack","box"]`. → §3.1. +2. **Request body dropped.** `counter_dashboard.py::_send_counter_command()` + posts an empty body, so `plate` / `do_numbers` / `expected_*` / + `fcp_batch_number` never reach `counter_control.py`. → §3.2. +3. **Stopped batch not persisted.** The stop reply was + `{"success": true, "count": 0, "persisted": false}`. `GET /api/recent-batches` + on zenai still shows batches 1–3 for 2026-11-13 — test batch #4 is missing + from zenai history. `end_batch()` reports the DB write as failed. Must be + fixed on zenai, otherwise every synced batch vanishes from zenai history. +4. **No `X-API-Key` check.** FCP now always sends the header (random secret, + see `docs/peer_sync_token.txt`), but zenai ignores it — no 401 path exists + yet. → §3.3. + +## 6. Where the FCP code lives + +| File | Role | +|---|---| +| `src/peer_sync.py` | outbound client (stdlib urllib, retry, fail-soft) | +| `counter_dashboard.py` | hooks in `api_batch_start` / `api_batch_stop` | +| `templates/operator.html`, `templates/monitoring.html` | operator warning | +| `tests/test_peer_sync.py` | mock-peer tests | +| `docs/configuration.md` | env keys | + +FCP sends only for **manual** and **do_manual** batch modes; `auto` mode is not +synced (auto batches are started by the pipeline, not by the operator). diff --git a/feedmill.db b/feedmill.db index 2055da674ee6a5b26a01a83fc2a059655565bce5..15decb438b77bd28d72d92bcf3bdc45bd6d47630 100644 GIT binary patch delta 1338 zcmZvbPiqrF7{+I|O|sc;GHt4)GzT|r;vbqUJ3G6ZWI<~prHD{z2`DW!rb*Olo7AS2 z77A%W1r==TqImEksNh8?=?9RCXTLxdKS4ctkY1ck+TBfbA(!_zZ=UC!_nGz2aDAQG z3iS{G084+zAHN+Vhyd}y6Cb+54U#auOCxM%lR<(bNgRpkWdXMEzWy3f1Z!SNyE8|teM_x108l%kcdvOjuQb*Xml}< zFsyMiccKsM+vkWNrF2!*F$Vkfy|D}oc+fCF-_aNJ5pAMLw2X$S_&H=u<`A#hT7$Ik zf%nlBM8GaUo6K*6@76geGY^?w_#W(TZxm~5kpM8);7zBAmyJSS59=^)-@0u(izOXv zx|$S;qDd+IKaxmFNla{Fj@sy~^ZCVm`F3Gy`u-WADbG-O=ICKqZH^Tf?*dn9 zbA$9SU47H5nKl5d!_C3X@Ytm+y*WkJWh}~yoJu$h9TP>=lCnyv6+%Ih8$C*8plJra%q5DcWJ1EKO|13um2jJ4i=b=53S`{wHWd|3 z$3(;=kxa?0M8&$Qh%!z{#Nnl(Xp*?`D{!}->wU{}W=tSj1!$FKse)=7ol&Qms5jIS u4Ew2eTZ)>Q3?enIJC)Rui8f+JUDQ;Xn3PSdN6_tzMux>QNoOuiP5%WxSu0ln delta 326 zcmZo@U}`wPI6+!aoq>UY4TxcYZK94bzdD0nStl>oUj|k-4F-;yjd^?=TrG8s?BdeW zjGe)oWw@l6CNE$YoNUJ-Hu)Tn84K@JCiabu%uH;ytZd?e+LO=oOKeu+y~o7E%N)s| zz|_dV-_P`ZGEagP6I0{HMoT8;90eW*MMiOPCPznOCJrM5BQsq?LtR5-mZ;P`$IRT! ziqw?JQHkD@zb0jY90$akRudF9&(Luf zW>lE`z+PTdftT+m0~=pA1OHLJL;QXG;rt4G-9R(S`FKnfxEK_HZs7zvWpYBi2ouBN r$rBPqHy`qIViaKGk7D4z%YT@EC4WDE6n`mDiyQxB`*{Azneo#BED%j% diff --git a/templates/dashboard.html b/templates/dashboard.html index 8cda476..4100ed9 100644 --- a/templates/dashboard.html +++ b/templates/dashboard.html @@ -791,15 +791,16 @@ letter-spacing: 0.02em; background: rgba(0,0,0,0.18); } - .modal-table th:nth-child(1), .modal-table td:nth-child(1) { width: 12%; } - .modal-table th:nth-child(2), .modal-table td:nth-child(2) { width: 18%; } - .modal-table th:nth-child(3), .modal-table td:nth-child(3) { width: 15%; } + .modal-table th:nth-child(1), .modal-table td:nth-child(1) { width: 9%; } + .modal-table th:nth-child(2), .modal-table td:nth-child(2) { width: 14%; } + .modal-table th:nth-child(3), .modal-table td:nth-child(3) { width: 11%; } .modal-table th:nth-child(4), .modal-table td:nth-child(4), - .modal-table th:nth-child(5), .modal-table td:nth-child(5) { width: 15%; } - .modal-table th:nth-child(6), .modal-table td:nth-child(6) { width: 13%; } - .modal-table th:nth-child(7), .modal-table td:nth-child(7) { width: 11%; } - .modal-table th:nth-child(8), .modal-table td:nth-child(8) { width: 11%; } - .modal-table th:nth-child(9), .modal-table td:nth-child(9) { width: 11%; } + .modal-table th:nth-child(5), .modal-table td:nth-child(5) { width: 10%; } + .modal-table th:nth-child(6), .modal-table td:nth-child(6) { width: 10%; } + .modal-table th:nth-child(7), .modal-table td:nth-child(7) { width: 10%; } + .modal-table th:nth-child(8), .modal-table td:nth-child(8) { width: 10%; } + .modal-table th:nth-child(9), .modal-table td:nth-child(9) { width: 9%; } + .modal-table th:nth-child(10), .modal-table td:nth-child(10) { width: 7%; } .modal-table .mono { font-family: var(--mono); font-weight: 600; } .modal-empty { color: var(--text-muted); font-size: 12px; padding: 16px; text-align: center; @@ -946,6 +947,10 @@ nomor batch Batch #-- +
+ plat nomor + - +
waktu deteksi terakhir --:--:-- @@ -1180,6 +1185,7 @@ Batch # + Plat Nomor Tipe Sack Box @@ -1222,6 +1228,10 @@ Box: 0
+
+ Plat Nomor: + - +
Waktu Mulai: --:--:-- @@ -1258,6 +1268,9 @@ let currentBatchState = { object_label: 'mixed', next_batch_number: 1, count: 0, + sack_count: 0, + box_count: 0, + plate: null, start_time: null, }; @@ -1350,7 +1363,8 @@ async function loadCurrentBatch() { const res = await fetch('/api/current-batch'); const data = await res.json(); const isActive = Boolean(data.success && data.active !== false && data.batch_number != null); - const objTypeUpper = 'MIXED'; + const objType = (data.object_label || 'mixed').toLowerCase(); + const objTypeUpper = objType.toUpperCase(); currentBatchState.active = isActive; currentBatchState.batch_number = data.batch_number || null; @@ -1359,6 +1373,7 @@ async function loadCurrentBatch() { currentBatchState.count = data.count || 0; currentBatchState.sack_count = data.sack_count || 0; currentBatchState.box_count = data.box_count || 0; + currentBatchState.plate = data.plate || null; currentBatchState.start_time = data.start_time || null; const liveCountEl = document.getElementById('live-count'); @@ -1366,6 +1381,7 @@ async function loadCurrentBatch() { const liveSackEl = document.getElementById('live-sack-count'); const liveBoxEl = document.getElementById('live-box-count'); const liveBatchEl = document.getElementById('live-batch-number'); + const livePlateEl = document.getElementById('live-plate'); const liveLastDetEl = document.getElementById('live-last-detection'); const batchStatusEl = document.getElementById('batch-status'); const batchHintEl = document.getElementById('batch-status-hint'); @@ -1393,12 +1409,14 @@ async function loadCurrentBatch() { if (liveSackEl) liveSackEl.textContent = Number(data.sack_count || 0).toLocaleString('id-ID'); if (liveBoxEl) liveBoxEl.textContent = Number(data.box_count || 0).toLocaleString('id-ID'); if (liveBatchEl) liveBatchEl.textContent = String(data.batch_number).padStart(4, '0'); + if (livePlateEl) livePlateEl.textContent = data.plate || '-'; if (batchStatusEl) { - batchStatusEl.textContent = `RUNNING · ${objTypeUpper}`; + batchStatusEl.textContent = 'RUNNING'; batchStatusEl.className = 'badge-running'; } if (batchHintEl) { - batchHintEl.textContent = `Batch #${String(data.batch_number).padStart(4, '0')} (${objTypeUpper}) sedang berjalan`; + const plateInfo = data.plate ? ` · Plat ${data.plate}` : ''; + batchHintEl.textContent = `Batch #${String(data.batch_number).padStart(4, '0')}${plateInfo} sedang berjalan`; } if (svcCounterEl) svcCounterEl.textContent = 'Running'; if (svcCounterDot) svcCounterDot.style.background = 'var(--green)'; @@ -1418,11 +1436,13 @@ async function loadCurrentBatch() { bcStatusText.textContent = `BATCH #${data.batch_number} ACTIVE`; } if (bcMainInfo) { - bcMainInfo.textContent = `Batch #${data.batch_number} [${objTypeUpper}] Sedang Berjalan (${Number(data.count || 0).toLocaleString('id-ID')} total)`; + const plateLabel = data.plate ? ` · Plat: ${data.plate}` : ''; + bcMainInfo.textContent = `Batch #${data.batch_number}${plateLabel} Sedang Berjalan (${Number(data.count || 0).toLocaleString('id-ID')} total)`; } if (bcSubInfo) { const startTimeStr = data.start_time ? new Date(data.start_time).toLocaleTimeString('id-ID', { hour12: false }) : '--:--:--'; - bcSubInfo.textContent = `Mulai pukul ${startTimeStr} · Menghitung karung dan box`; + const plateSub = data.plate ? ` · Plat: ${data.plate}` : ''; + bcSubInfo.textContent = `Mulai pukul ${startTimeStr}${plateSub} · Menghitung karung dan box`; } if (btnStart) btnStart.style.display = 'none'; if (btnStop) { @@ -1435,6 +1455,7 @@ async function loadCurrentBatch() { if (liveSackEl) liveSackEl.textContent = '0'; if (liveBoxEl) liveBoxEl.textContent = '0'; if (liveBatchEl) liveBatchEl.textContent = '----'; + if (livePlateEl) livePlateEl.textContent = '-'; if (liveLastDetEl) liveLastDetEl.textContent = '--:--:--'; if (batchStatusEl) { batchStatusEl.textContent = 'IDLE'; @@ -1493,6 +1514,7 @@ function handleStopBatch() { const modalCount = document.getElementById('modalStopBatchCount'); const modalSack = document.getElementById('modalStopBatchSackCount'); const modalBox = document.getElementById('modalStopBatchBoxCount'); + const modalPlate = document.getElementById('modalStopBatchPlate'); const modalStart = document.getElementById('modalStopBatchStart'); if (modalName) modalName.textContent = `Batch #${currentBatchState.batch_number || '--'}`; @@ -1500,6 +1522,7 @@ function handleStopBatch() { if (modalCount) modalCount.textContent = Number(currentBatchState.count || 0).toLocaleString('id-ID'); if (modalSack) modalSack.textContent = Number(currentBatchState.sack_count || 0).toLocaleString('id-ID'); if (modalBox) modalBox.textContent = Number(currentBatchState.box_count || 0).toLocaleString('id-ID'); + if (modalPlate) modalPlate.textContent = currentBatchState.plate || '-'; if (modalStart) { modalStart.textContent = currentBatchState.start_time ? new Date(currentBatchState.start_time).toLocaleTimeString('id-ID', { hour12: false }) @@ -1702,6 +1725,16 @@ async function loadChartData(days) { } } +function resolveBatchType(b) { + const sacks = Number(b?.sack_count || 0); + const boxes = Number(b?.box_count || 0); + if (sacks > 0 && boxes > 0) return 'mixed'; + if (boxes > 0 && sacks === 0) return 'box'; + if (sacks > 0 && boxes === 0) return 'sack'; + const raw = (b?.object_label || 'mixed').toLowerCase(); + return raw === 'box' ? 'box' : (raw === 'sack' ? 'sack' : 'mixed'); +} + async function loadRecentBatches() { try { const res = await fetch('/api/recent-batches?limit=5'); @@ -1712,7 +1745,7 @@ async function loadRecentBatches() { return; } container.innerHTML = batches.map(b => { - const bType = (b.object_label || 'mixed').toLowerCase() === 'box' ? 'box' : (b.object_label || 'mixed').toLowerCase() === 'sack' ? 'sack' : 'mixed'; + const bType = resolveBatchType(b); const typePill = bType === 'mixed' ? 'MIXED' : `${bType.toUpperCase()}`; @@ -1724,6 +1757,7 @@ async function loadRecentBatches() {
${Number(b.count || 0).toLocaleString('id-ID')}
${Number(b.sack_count || 0).toLocaleString('id-ID')} karung · ${Number(b.box_count || 0).toLocaleString('id-ID')} box
+
Plat: ${b.plate || '-'}
${formatTimeShort(b.start_time)} - ${formatTimeShort(b.end_time)} · ${b.duration_minutes} menit
`; @@ -1931,8 +1965,7 @@ async function showDayDetail(date) { let tableHtml = ''; if (batches.length) { tableHtml = batches.map(b => { - const rawType = (b.object_label || 'mixed').toLowerCase(); - const bType = rawType === 'box' ? 'box' : (rawType === 'sack' ? 'sack' : 'mixed'); + const bType = resolveBatchType(b); const typePill = bType === 'mixed' ? 'MIXED' : `${bType.toUpperCase()}`; @@ -1940,6 +1973,7 @@ async function showDayDetail(date) { return ` #${b.batch_number} + ${b.plate || '-'} ${typePill} ${Number(b.sack_count || 0).toLocaleString('id-ID')} ${Number(b.box_count || 0).toLocaleString('id-ID')} @@ -1954,6 +1988,7 @@ async function showDayDetail(date) { tableHtml += ` TOTAL + - ${sackTotal.toLocaleString('id-ID')} Sack, ${boxTotal.toLocaleString('id-ID')} Box ${sackTotal.toLocaleString('id-ID')} ${boxTotal.toLocaleString('id-ID')} @@ -1964,7 +1999,7 @@ async function showDayDetail(date) { 100% `; } else { - tableHtml = `Tidak ada batch pada tanggal ini`; + tableHtml = `Tidak ada batch pada tanggal ini`; } document.getElementById('modal-table-body').innerHTML = tableHtml; diff --git a/tests/test_batch_store.py b/tests/test_batch_store.py new file mode 100644 index 0000000..d289fe2 --- /dev/null +++ b/tests/test_batch_store.py @@ -0,0 +1,196 @@ +import json +import sqlite3 +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import batch_store + + +class BatchStoreUnifiedBatchTests(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + self.root = Path(self.temp_dir.name) + self.db_path = self.root / "feedmill.db" + self.state_path = self.root / "current_batch.json" + + def tearDown(self): + self.temp_dir.cleanup() + + def make_store(self): + return batch_store.BatchStore( + db_path=self.db_path, + state_file=self.state_path, + camera_name="camera-a", + cutoff_time="23:59", + batch_mode="manual", + logger=lambda _message: None, + ) + + def test_mixed_batch_counts_sacks_and_boxes_separately(self): + store = self.make_store() + store.start_new_batch() + + store.record_counted_object_crossing(1, object_label="sack") + store.record_counted_object_crossing(2, object_label="box") + + status = store.get_status() + self.assertEqual(status["count"], 2) + self.assertEqual(status["sack_count"], 1) + self.assertEqual(status["box_count"], 1) + self.assertEqual(status["object_label"], "mixed") + store.db.close() + + def test_same_track_id_counts_once_per_class(self): + store = self.make_store() + store.start_new_batch() + + store.record_counted_object_crossing(7, object_label="sack") + store.record_counted_object_crossing(7, object_label="box") + + status = store.get_status() + self.assertEqual(status["count"], 2) + self.assertEqual(status["sack_count"], 1) + self.assertEqual(status["box_count"], 1) + store.db.close() + + def test_legacy_active_state_resumes_as_mixed_and_accepts_both_classes(self): + counting_date = "2026-11-13" + self.state_path.write_text( + json.dumps( + { + "counting_date": counting_date, + "batch_number": 4, + "object_label": "sack", + "count": 4, + "start_time": "2026-11-13T10:00:00", + "last_detection_time": "2026-11-13T10:01:00", + "counted_event_ids": ["1"], + } + ), + encoding="utf-8", + ) + with patch.object( + batch_store.BatchStore, "get_counting_date", return_value=counting_date + ): + store = batch_store.BatchStore( + db_path=self.db_path, + state_file=self.state_path, + camera_name="camera-a", + cutoff_time="23:59", + batch_mode="manual", + logger=lambda _message: None, + ) + store.get_counting_date = lambda dt=None: counting_date + + status = store.get_status() + self.assertEqual(status["object_label"], "mixed") + self.assertEqual(status["count"], 4) + self.assertEqual(status["sack_count"], 4) + self.assertEqual(status["box_count"], 0) + + store.record_counted_object_crossing(2, object_label="box") + status = store.get_status() + self.assertEqual(status["count"], 5) + self.assertEqual(status["sack_count"], 4) + self.assertEqual(status["box_count"], 1) + store.db.close() + + def test_legacy_database_rows_are_backfilled_without_changing_totals(self): + conn = sqlite3.connect(self.db_path) + conn.executescript( + """ + CREATE TABLE batches ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + counting_date TEXT NOT NULL, + batch_number INTEGER NOT NULL, + camera_name TEXT NOT NULL, + object_label TEXT NOT NULL, + count INTEGER NOT NULL, + start_time TEXT NOT NULL, + end_time TEXT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(counting_date, batch_number, camera_name, object_label) + ); + CREATE TABLE daily_summaries ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + counting_date TEXT NOT NULL, + camera_name TEXT NOT NULL, + object_label TEXT NOT NULL, + total_count INTEGER NOT NULL DEFAULT 0, + total_batches INTEGER NOT NULL DEFAULT 0, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(counting_date, camera_name, object_label) + ); + INSERT INTO batches + (counting_date, batch_number, camera_name, object_label, count, start_time, end_time) + VALUES + ('2026-11-13', 1, 'camera-a', 'sack', 5, '2026-11-13T08:00:00', '2026-11-13T08:10:00'); + INSERT INTO daily_summaries + (counting_date, camera_name, object_label, total_count, total_batches) + VALUES + ('2026-11-13', 'camera-a', 'sack', 5, 1); + """ + ) + conn.commit() + conn.close() + + schema = getattr(batch_store, "ensure_batch_schema", None) + self.assertIsNotNone(schema, "ensure_batch_schema must exist") + conn = sqlite3.connect(self.db_path) + schema(conn) + row = conn.execute( + "SELECT total_count, sack_count, box_count FROM daily_summaries" + ).fetchone() + conn.close() + self.assertEqual(row, (5, 5, 0)) + + def test_mixed_batch_persists_one_row_with_separate_counts(self): + store = self.make_store() + store.start_new_batch() + store.record_counted_object_crossing(1, object_label="sack") + store.record_counted_object_crossing(2, object_label="box") + + self.assertTrue(store.end_batch(closed_by="manual")) + + row = store.db.execute( + """ + SELECT object_label, count, sack_count, box_count + FROM batches + """ + ).fetchone() + self.assertEqual(row, ("mixed", 2, 1, 1)) + store.db.close() + + def test_mixed_daily_summary_counts_batch_once(self): + store = self.make_store() + store.start_new_batch() + store.record_counted_object_crossing(1, object_label="sack") + store.record_counted_object_crossing(2, object_label="box") + store.end_batch(closed_by="manual") + + row = store.db.execute( + """ + SELECT object_label, total_count, total_batches, sack_count, box_count + FROM daily_summaries + """ + ).fetchone() + self.assertEqual(row, ("mixed", 2, 1, 1, 1)) + store.db.close() + + def test_empty_manual_batch_is_not_persisted(self): + store = self.make_store() + store.start_new_batch() + + self.assertFalse(store.end_batch(closed_by="manual")) + + batch_count = store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0] + summary_count = store.db.execute("SELECT COUNT(*) FROM daily_summaries").fetchone()[0] + self.assertEqual(batch_count, 0) + self.assertEqual(summary_count, 0) + store.db.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py new file mode 100644 index 0000000..f1323f0 --- /dev/null +++ b/tests/test_dashboard.py @@ -0,0 +1,332 @@ +import json +import os +import shutil +import sqlite3 +import tempfile +import unittest +import urllib.request +from io import BytesIO +from pathlib import Path +from unittest.mock import patch + +from openpyxl import load_workbook + +TEST_ROOT = Path(tempfile.mkdtemp(prefix="feedmill-dashboard-", dir="/tmp/opencode")) +os.environ["DB_PATH"] = str(TEST_ROOT / "import.db") +os.environ["STATE_FILE"] = str(TEST_ROOT / "import-state.json") + +import counter_dashboard +from counter_control import start_control_server + + +class DashboardUnifiedBatchTests(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory(dir="/tmp/opencode") + self.root = Path(self.temp_dir.name) + self.db_path = self.root / "feedmill.db" + self.state_path = self.root / "current_batch.json" + counter_dashboard.DB_PATH = str(self.db_path) + counter_dashboard.CURRENT_BATCH_PATH = str(self.state_path) + counter_dashboard._ensure_db() + self.client = counter_dashboard.app.test_client() + + def tearDown(self): + self.temp_dir.cleanup() + + def seed_batch(self, counting_date, batch_number=1, sack_count=3, box_count=2, plate="B 1234 XYZ"): + conn = sqlite3.connect(self.db_path) + conn.execute( + """ + INSERT INTO batches + (counting_date, batch_number, camera_name, object_label, count, + sack_count, box_count, plate, start_time, end_time) + VALUES (?, ?, 'camera-a', 'mixed', ?, ?, ?, ?, ?, ?) + """, + ( + counting_date, + batch_number, + sack_count + box_count, + sack_count, + box_count, + plate, + f"{counting_date}T08:00:00", + f"{counting_date}T08:10:00", + ), + ) + conn.execute( + """ + INSERT INTO daily_summaries + (counting_date, camera_name, object_label, total_count, total_batches, + sack_count, box_count) + VALUES (?, 'camera-a', 'mixed', ?, 1, ?, ?) + """, + (counting_date, sack_count + box_count, sack_count, box_count), + ) + conn.commit() + conn.close() + + def test_dashboard_renders_single_start_button_and_separate_counters(self): + html = self.client.get("/").get_data(as_text=True) + + self.assertIn('id="btnBatchStart"', html) + self.assertNotIn('id="btnBatchStartSack"', html) + self.assertNotIn('id="btnBatchStartBox"', html) + self.assertIn('id="live-sack-count"', html) + self.assertIn('id="live-box-count"', html) + self.assertIn('id="live-plate"', html) + self.assertIn('id="today-sack-count"', html) + self.assertIn('id="today-box-count"', html) + self.assertIn('id="modalStopBatchSackCount"', html) + self.assertIn('id="modalStopBatchBoxCount"', html) + self.assertIn('id="modalStopBatchPlate"', html) + + def test_daily_export_has_sack_and_box_columns(self): + counting_date = counter_dashboard.get_counting_date() + self.seed_batch(counting_date) + + response = self.client.get("/api/export-daily-csv?days=30") + + self.assertEqual(response.status_code, 200) + workbook = load_workbook(BytesIO(response.get_data())) + sheet = workbook.active + headers = [cell.value for cell in sheet[1]] + self.assertIn("Plate", headers) + self.assertIn("Sack", headers) + self.assertIn("Box", headers) + self.assertIn("Total", headers) + row = [cell.value for cell in sheet[2]] + self.assertEqual(row[headers.index("Plate")], "B 1234 XYZ") + self.assertEqual(row[headers.index("Sack")], 3) + self.assertEqual(row[headers.index("Box")], 2) + self.assertEqual(row[headers.index("Total")], 5) + + def test_day_export_has_sack_and_box_columns(self): + counting_date = counter_dashboard.get_counting_date() + self.seed_batch(counting_date) + + response = self.client.get(f"/api/export-day-csv/{counting_date}") + + self.assertEqual(response.status_code, 200) + workbook = load_workbook(BytesIO(response.get_data())) + sheet = workbook.active + headers = [cell.value for cell in sheet[1]] + self.assertIn("Plate", headers) + self.assertIn("Sack", headers) + self.assertIn("Box", headers) + self.assertIn("Total", headers) + row = [cell.value for cell in sheet[2]] + self.assertEqual(row[headers.index("Plate")], "B 1234 XYZ") + self.assertEqual(row[headers.index("Sack")], 3) + self.assertEqual(row[headers.index("Box")], 2) + self.assertEqual(row[headers.index("Total")], 5) + + def test_start_endpoint_sends_unified_start_command(self): + with patch( + "counter_dashboard._send_counter_command", + return_value=({"success": True, "batch_number": 1}, 200), + ) as send: + response = self.client.post("/api/batch/start") + + self.assertEqual(response.status_code, 200) + send.assert_called_once_with("start") + + def test_legacy_start_routes_send_unified_start_command(self): + for path in ("/api/batch/start/sack", "/api/batch/start/box"): + with self.subTest(path=path): + with patch( + "counter_dashboard._send_counter_command", + return_value=({"success": True, "batch_number": 1}, 200), + ) as send: + response = self.client.post(path) + + self.assertEqual(response.status_code, 200) + send.assert_called_once_with("start") + + def test_current_batch_returns_separate_counts(self): + self.state_path.write_text( + json.dumps( + { + "counting_date": counter_dashboard.get_counting_date(), + "batch_number": 4, + "object_label": "mixed", + "count": 5, + "sack_count": 3, + "box_count": 2, + "start_time": "2026-11-13T08:00:00", + "last_detection_time": "2026-11-13T08:01:00", + } + ), + encoding="utf-8", + ) + + response = self.client.get("/api/current-batch") + data = response.get_json() + + self.assertEqual(response.status_code, 200) + self.assertEqual(data["object_label"], "mixed") + self.assertEqual(data["count"], 5) + self.assertEqual(data["sack_count"], 3) + self.assertEqual(data["box_count"], 2) + + def test_summary_returns_separate_today_totals(self): + counting_date = counter_dashboard.get_counting_date() + self.seed_batch(counting_date) + + response = self.client.get("/api/summary") + data = response.get_json() + + self.assertEqual(response.status_code, 200) + self.assertEqual(data["today"]["count"], 5) + self.assertEqual(data["today"]["sack_count"], 3) + self.assertEqual(data["today"]["box_count"], 2) + self.assertEqual(data["all_time"]["count"], 5) + self.assertEqual(data["all_time"]["sack_count"], 3) + self.assertEqual(data["all_time"]["box_count"], 2) + + def test_batch_status_fallback_returns_separate_counts(self): + self.state_path.write_text( + json.dumps( + { + "counting_date": counter_dashboard.get_counting_date(), + "batch_number": 4, + "object_label": "mixed", + "count": 5, + "sack_count": 3, + "box_count": 2, + "start_time": "2026-11-13T08:00:00", + } + ), + encoding="utf-8", + ) + + with patch( + "counter_dashboard.urllib.request.urlopen", + side_effect=OSError("control server offline"), + ): + response = self.client.get("/api/batch/status") + + data = response.get_json() + self.assertEqual(response.status_code, 200) + self.assertEqual(data["count"], 5) + self.assertEqual(data["sack_count"], 3) + self.assertEqual(data["box_count"], 2) + + def test_day_detail_returns_separate_counts(self): + counting_date = counter_dashboard.get_counting_date() + self.seed_batch(counting_date) + + response = self.client.get(f"/api/day-detail/{counting_date}") + data = response.get_json() + + self.assertEqual(response.status_code, 200) + self.assertEqual(data["total_count"], 5) + self.assertEqual(data["sack_count"], 3) + self.assertEqual(data["box_count"], 2) + self.assertEqual(data["batches"][0]["sack_count"], 3) + self.assertEqual(data["batches"][0]["box_count"], 2) + self.assertEqual(data["batches"][0]["plate"], "B 1234 XYZ") + + def test_recent_and_previous_batches_return_separate_counts(self): + counting_date = counter_dashboard.get_counting_date() + self.seed_batch(counting_date) + + recent = self.client.get("/api/recent-batches").get_json() + previous = self.client.get("/api/previous-batch").get_json() + + self.assertEqual(recent[0]["sack_count"], 3) + self.assertEqual(recent[0]["box_count"], 2) + self.assertEqual(recent[0]["plate"], "B 1234 XYZ") + self.assertEqual(previous["sack_count"], 3) + self.assertEqual(previous["box_count"], 2) + self.assertEqual(previous["plate"], "B 1234 XYZ") + + def test_control_server_stop_returns_separate_counts(self): + class FakeStore: + def get_status(self): + return { + "active": True, + "batch_number": 7, + "object_label": "mixed", + "count": 5, + "sack_count": 3, + "box_count": 2, + } + + def end_batch(self, closed_by="manual"): + return True + + server = start_control_server(FakeStore(), port=0) + self.addCleanup(server.shutdown) + port = server.server_address[1] + + request = urllib.request.Request( + f"http://127.0.0.1:{port}/stop", data=b"", method="POST" + ) + with urllib.request.urlopen(request) as response: + data = json.loads(response.read().decode("utf-8")) + + self.assertEqual(data["count"], 5) + self.assertEqual(data["sack_count"], 3) + self.assertEqual(data["box_count"], 2) + + def test_control_server_start_aliases_create_one_mixed_batch(self): + class FakeStore: + def __init__(self): + self.calls = [] + + def get_status(self): + return {"active": False, "batch_number": None, "count": 0} + + def start_new_batch(self, counting_date=None, object_label=None): + self.calls.append((counting_date, object_label)) + return 7 + + store = FakeStore() + server = start_control_server(store, host="127.0.0.1", port=0) + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + port = server.server_address[1] + + for path in ("/start/sack", "/start/box"): + request = urllib.request.Request( + f"http://127.0.0.1:{port}{path}", + data=b"{}", + method="POST", + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=2) as response: + self.assertEqual(response.status, 200) + + self.assertEqual(store.calls, [(None, None), (None, None)]) + + def test_peer_sync_api_key_validation_and_body_forwarding(self): + with patch("counter_dashboard._get_peer_api_token", return_value="secret-token"): + bad = self.client.post( + "/api/batch/start", + headers={"X-API-Key": "wrong-token"}, + json={"plate": "B 1234 XYZ"}, + ) + self.assertEqual(bad.status_code, 401) + self.assertFalse(bad.get_json()["success"]) + + with patch( + "counter_dashboard._send_counter_command", + return_value=({"success": True, "batch_number": 1}, 200), + ) as send: + ok = self.client.post( + "/api/batch/start", + headers={"X-API-Key": "secret-token"}, + json={"plate": "B 1234 XYZ", "source": "fcp-semarang"}, + ) + self.assertEqual(ok.status_code, 200) + self.assertEqual(send.call_count, 1) + self.assertEqual(send.call_args[0][0], "start") + self.assertIn(b"B 1234 XYZ", send.call_args[1]["data"]) + + +def tearDownModule(): + shutil.rmtree(TEST_ROOT, ignore_errors=True) + + +if __name__ == "__main__": + unittest.main()