path:
/AGENTS.md
10.51 KB | plain
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
110
111
112
113
114
115
116
117
# AGENTS.md
Orientation for AI agents and new contributors working on this project.
Read this first, then `CONTEXT.md` (which documents the message-rendering
refactor in detail — this file does not repeat it).
## What this is
A single-page "Event Notifications" dashboard for saikrupagas.com. It polls a
backend feed of incoming SMS and device events, renders them as a live list
grouped by day, flags LPG leak alerts with sound and desktop notifications, and
lets the user click to copy OTP codes.
No framework, no bundler, no build step for the page itself. Plain HTML, CSS,
vanilla JS. Open `index.html` behind a server that exposes `/kidang.fcgi` and
the edge-proxied `/api/devices/<tag>` route. Before changing device lookup or
proxy deployment, read `deploy/README.md` for the secret and authentication contract.
## File map
| File | Role |
|---|---|
| `index.html` | Page shell: two panels ("Events", "Action Required"), filter bar, device-info popover. Loads `logs.js` **before** `.content` exists in the DOM (see "Load order" below). |
| `logs.js` | The entire frontend. Polling, parsing, rendering, filtering, alerts, device lookup. |
| `gt.js` | `parseGT()` — parser for "GT", a JSON-like format the backend may return: single-quoted strings, unquoted bare words, **no commas** between entries. |
| `deploy/superpulse-proxy.conf` | Project-owned include for the authenticated `lighttpd-proxy` edge vhost; device lookup routing and token injection. Secrets live outside the document root under `/etc/superpulse/`. |
| `.env.php` | Legacy untracked secret file; may remain locally or on the server until administrator migration. **Never commit, log, or echo it.** |
| `logs.css` | Styles specific to this page (message rows, dispatch card, date dividers, popover, panels). |
| `style.css` | Shared site-wide stylesheet copied from the main saikrupagas.com repo. ~2,500 lines; treat as read-only. Note `body { overflow-x: hidden }` here is why sticky dividers must be top-level `<li>`s (see CONTEXT.md §1). |
| `CONTEXT.md` | Design notes on `serverMassage`, message templates, date dividers, and the action panel. Authoritative for rendering code. |
| `CHANGELOG.txt` | Version history (stops at 1.0; page header says v1.1-beta). |
| `templates.html` | Duplicate of the `#custom-date` `<template>` already inline in `index.html`. Neither is cloned at runtime; kept as a visual reference only. |
| `Makefile` | **Does not belong to this project.** Copied from the main site repo; references m4 templates, `html/*.html.in`, `privacy.html`, `404.html`, `css/`, `js/` — none exist here. Do not run it. |
| `assets/` | Icons. Runtime paths in `logs.js` are `/assets/logs/...`, so this folder is deployed under that prefix on the live site. |
## Backend contract
- **Feed**: `GET /kidang.fcgi?table=otp&sentstamp=<epochSec>&fromTimestamp=<epochSec>&toTimestamp=<epochSec>`
- `sentstamp` is the lower-bound param kidang actually reads today; `fromTimestamp`/`toTimestamp` are sent as forward-compatible aliases.
- Response is JSON (array, or object with `rows`/`data` array) **or** GT text. `parseFeedResponse()` tries JSON first, falls back to `parseGT()`.
- Each row: `{ sndr, sentstamp, mid, cid, msg, extra }`
- `sndr` — sender string
- `sentstamp` — epoch; seconds, ms, or µs are all accepted by `getDateFromEpoch()`
- `mid` — device id (looked up via `/api/devices/<mid>`)
- `cid` — category id, mapped by the hardcoded table in `getCategoryNameFromId()`: 1 sms, 2 econnect, 3 paytm, 4 tampermonkey, 5 printer
- `msg` — raw message text, or a JSON string with a `type` field
- `extra` — optional JSON string, e.g. `{"sim": "..."}`
- **Action feed**: `table=action`. Currently **disabled** (`config.actionTable = null`) because the table doesn't exist on the backend and returned HTTP 500. `fetchActionUpdates()` also self-disables on the first 404/500.
- **Device lookup**: `GET /api/devices/<mid>` returns raw Snipe-IT asset JSON. `fetchDeviceDetails()` maps its display fields; the edge proxy owns the secret and access policy.
## Runtime flow (per poll, every 3 s)
`fetchUpdates()` in `logs.js`:
1. `getRangeParams()` reads the "From" input (defaults to now minus `config.defaultRangeHours`), builds query params.
2. `fetchTable()` → `parseFeedResponse()`.
3. Sort newest first. For each row:
- `updateDeviceDropdown()` / `updateCategoryDropdown()` add new options once.
- `isActionRequiredItem()` routes to `#action-list` if sender is `complaints`, or category is `econnect` and the text matches urgent/emergency/complain/leak. Otherwise `#data-list`.
- Skip if a `<li>` with the same DOM id (`msg-<sndr>-<sentstamp>`, sanitised) already exists.
- `serverMassage(msg, extra)` → typed object (`iob-debit`, `iob-credit`, `sms`, or pass-through JSON such as `dispatch`).
- If `leakage` is set and not in `sessionStorage` key `seen_lpg_leaks`: `playAlarmSound()` (Web Audio) + `triggerDesktopNotification()`.
- `createMessageListItem()` → `insertInOrder()` (descending by timestamp).
4. `removeDeadItems()` deletes rows not in the fresh response.
5. `applyFilters()` / `applyActionFilters()` toggle visibility by device, category, and text.
6. `syncDateDividers()` rebuilds sticky per-day `<li class="date-divider">` rows.
**Device names** resolve lazily: rows first show `Device <mid>`, then `fetchDeviceDetails()` hits `/api/devices/<mid>`, caches in `deviceMapCache` (promise or object), and `updateDeviceReferences()` rewrites every button and dropdown option for that id. Clicking a device button opens the `#device-info-popover`, positioned by `placeDevicePopoverNear()`.
## Load order gotcha
`<script src="logs.js">` sits **before** `.content` in `index.html`. Anything that touches `#data-list`, `#action-list`, or the filter inputs synchronously must run inside the `DOMContentLoaded` handler at the bottom of `logs.js`. `fetchUpdates()` is called inline at the bottom and survives only because its `await fetch()` yields until after the parser finishes. Don't add new inline DOM access at the top level.
## Glossary
Use these names consistently in code and docs:
| Term | Meaning |
|---|---|
| **TVA control** | The reusable Chart.js widget in `tva-control.js` / `tva-control.css`. |
| **Display mode** | The widget size/layout state: `pulseGraph`, `pulseBar`, or `pulseGraphMax`. |
| **Chart view** | The chart content inside the widget: a parameter graph or an area scan. This is separate from display mode. |
| **PulseGraph** | The normal TVA display mode for the parameter graph. |
| **PulseBar** | The flattened TVA display mode: one short header-like bar with parameter boxes connected by the same dominance-gradient segments as the parameter graph. Do not call this "minimized" or "compact" in new code. |
| **PulseGraphMax** | The enlarged TVA display mode. It is not browser fullscreen, so don't name it fullscreen. |
| **Parameter graph** | The connected line chart showing configured parameters left-to-right. It is not a timeline. |
| **Area scan** | A bar-chart view for one parameter's areas, configured with `areaScanView`. |
| **Parameter** | One configured TVA metric, e.g. pendency days, invoice actions, complaints open. |
| **Parameter box** | The small drawn value label for a parameter on the TVA canvas. |
| **Connector** | The line segment between adjacent parameter boxes. In PulseBar it is custom-drawn so labels do not cover it. |
| **Warning level** | A configured threshold band such as amber/red/double-red. It owns color, dominance, glow, blink, and border-alert behavior. |
| **Dominance gradient** | The exact gradient-stop behavior controlled by a warning level's `dominance`; parameter graph connectors and PulseBar connectors must reuse the same code path. |
| **Controls row** | The TVA UI controls/title row. In PulseBar mode it stays inside the TVA control above the parameter boxes. |
## Conventions
- **All message parsing lives in `serverMassage()`.** Templates never regex the raw text. If a template needs a fact, extract it there as a field. Only add fields a type actually uses; don't add `null` placeholders.
- **Body markup per type lives in `messageBodyTemplates[type]`.** The header is shared (`renderMessageHeader`); only `getHeaderLabel()` varies per type.
- **Build every list row with `createMessageListItem()`**, whatever list it goes into.
- **Escape user data** with `escapeHTML(s, forAttribute)`. `msg`, `sndr`, and all template fields are escaped. `copyableCodeChip()` injects the OTP unescaped into an `onclick`, which is safe only because `otp` is always `\d{6}` — keep it that way.
- Timestamps: `config.displayTimestampsAsLocalWallClock = true` shifts dates by the browser's timezone offset because the backend sends local wall-clock time as if it were UTC. Don't "fix" this without checking the backend.
- Global functions used from inline HTML handlers are assigned on `window` (`applyFilters`, `applyActionFilters`, `showMobileSegment`, `refreshRangeFeeds`, `copyToClipboard`). `deviceCardUpdate` is a plain top-level function, which also works because scripts are classic (non-module).
## Known issues and rough edges
- `Notification.requestPermission()` is never called. It lives inside a commented-out line near the bottom of `logs.js`, so desktop alerts only fire if the browser already granted permission.
- The iob-debit/credit regexes in `serverMassage()` hardcode the card suffix `CC-xxx2081`.
- Category id → name mapping is hardcoded; the TODO says it should come from kidang.
- The "To" range input is hidden (`#range-to`) and always set to "now"; only "From" is user-editable.
- The `dispatch` template renders an "Acknowledge Invoice" button with no handler.
- `fetchUpdates` runs on both the inline call and `DOMContentLoaded`, plus a 3 s interval, so the first two polls overlap on page load. Harmless because of the DOM-id dedupe.
## Deploying
Production deploys should go through the CI job defined in `.config/Jobfile` on the `integ` branch. The Jobfile intentionally lives only on `integ`; do not copy it to `main`. Push intended app changes to `main`; the integ CI trigger runs `lint`, `package`, and `deploy`, archives the pushed commit, and deploys to `maa-1:/srv/www/logs.saikrupagas.com` with `rsync --delete` while preserving production-only `.env.php` and `vendor/`.
The live site serves these files alongside `/kidang.fcgi` and expects `assets/` under `/assets/logs/`. The new device route requires administrator integration of `deploy/superpulse-proxy.conf` into the edge service before frontend deployment; see `deploy/README.md`. Existing CI does not provision secrets, reload the edge, or remove the legacy preserved `.env.php`/`vendor/` files.