commit bb2cf79ddbec9020c324edf205c26644cbeaa1da
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Wed, 7 Oct 2026 17:14:13 +0530
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Wed, 7 Oct 2026 17:14:13 +0530
Add TVA control and logs UI updates
26 files changed, 7716 insertions(+), 0 deletions(-)
A
|
130
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/AGENTS.md b/AGENTS.md @@ -0,0 +1,95 @@ +# 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, plus one small PHP proxy. Open `index.html` behind a server that +also exposes `/kidang.fcgi` and `logs.php`. + +## 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. | +| `logs.php` | Proxy: `GET logs.php?id=<tag>` → Snipe-IT asset API at `equipment.saikrupagas.com/api/v1/hardware/bytag/<tag>` → trimmed JSON `{name, serial, assigned_to, image, category_color, notes}`. | +| `.env.php` | Defines `$accessToken` (Snipe-IT bearer token). **Live secret. 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. | +| `vendor/`, `composer.*` | Guzzle 8 for `logs.php`. Vendored; don't edit. | + +## 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 `logs.php`) + - `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 logs.php?id=<mid>`. + +## 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 `logs.php`, 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. + +## 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. +- `logs.php` does no validation of `$_GET['id']` and no error handling. A missing device yields PHP warnings mixed into the JSON body. The id is concatenated into the upstream URL path. +- 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 + +There is no working deploy target in this repo (see Makefile note). The live site serves these files alongside `/kidang.fcgi` and expects `assets/` under `/assets/logs/`. `.env.php` must exist on the server but must not be web-readable in plain text; `logs.php` includes it with `require_once`.
diff --git a/CHANGELOG.txt b/CHANGELOG.txt @@ -0,0 +1,16 @@ +0.7 +--- +* Basic version + +0.8 +--- +* Added filter based query +* Update UI + +0.9 +--- +* Added support for click to copy + +1.0 +--- +Added support for mId and cId
diff --git a/CONTEXT.md b/CONTEXT.md @@ -0,0 +1,172 @@ +# CONTEXT.md + +Notes on the frontend changes made to this project in a recent session, covering +`index.html`, `logs.css`, and `logs.js`. This is not a full architecture doc — +just a record of what changed and why, so future work (human or AI) doesn't +have to re-derive it from the diff. + +## 1. Sticky date dividers + +The message list (`#data-list`, and now `#action-list` too) groups messages by +day using a **standalone `<li class="date-divider">`**, not a badge embedded +inside each message row. + +- `formatDateBadge(date)` — builds the day/month markup, styled after the + `#custom-date` `<template>` in `index.html` (kept there as a visual + reference, not actually cloned at runtime). +- `syncDateDividers(list)` — wipes and rebuilds all `.date-divider` elements + in a given `<ul>`: walks its `li.msg-list-item` children in DOM order, + and inserts one divider right before the first message of each new + calendar day (by `li.dataset.timestamp`). +- CSS: `.date-divider { position: sticky; top: 0; ... }` in `logs.css`. + +**Why it's a separate `<li>` and not an embedded badge:** an earlier version +embedded the badge inside each message's flex row and made it +`position: sticky` there. It silently failed to stick — `body` in `style.css` +has `overflow-x: hidden`, which (per the CSS overflow-propagation rule) makes +`body` a scroll-container candidate and put the sticky containing-block +resolution in a bad spot when nested inside a flex item. Promoting the +divider to a **top-level `<li>` sibling** of the message rows sidesteps the +whole problem and is also just the standard pattern for sticky section +headers in a list. Don't re-embed the badge inside message rows. + +**Also removed:** an earlier attempt gave `#data-list` its own +`max-height: 75vh; overflow-y: auto` scroll box. That's gone — the list now +scrolls with the page. (A boxed-height list whose content doesn't fill the +box never triggers its own scroll, so the badge just scrolls away with +everything else — that was the actual root cause of "badge doesn't stick" +before the standalone-`<li>` fix above.) + +`syncDateDividers(list)` takes the list element as a parameter specifically +so it can run against either `#data-list` or `#action-list`. + +## 2. Message rendering: templates + `serverMassage` + +The old code had message-type branching (`if (iobDebitMatch) {...} else if +(iobCreditMatch) {...} else {...}`) duplicated across leak-detection, +header-prefix text, and body HTML. That's gone, replaced with a small +template system in `logs.js`: + +``` +serverMassage(msg, extraRaw) -> normalizes a raw item into { type, ...fields } +renderMessageBody(data) -> messageBodyTemplates[data.type](data) +getHeaderLabel(data) -> reduces a type's own fields to one header string +renderMessageHeader({...}) -> the one common header structure, text injected +createMessageListItem(item) -> builds one <li> using all of the above +``` + +### `serverMassage(msg, extraRaw)` + +This is **the one function that understands today's raw text `msg` format**. +Everything downstream only ever sees its output — a plain JSON object shaped +differently per type: + +- `{ type: "iob-debit", amount, merchant, msg }` +- `{ type: "iob-credit", amount, merchant, msg }` +- `{ type: "sms", msg, sim, otp?, leakage? }` — `otp` / `leakage` keys are + **only present when actually detected**, not set to `null`/`false`. Don't + add always-present placeholder fields "for consistency" — the whole point + is each type only carries what it needs. +- `{ type: "dispatch", status, cargo, vehicleNo, time, invoiceNo, amount }` + (see §3) + +**Important design point:** `msg` is never mutated. All the old inline-text +mutation (wrapping OTP codes in clickable spans *inside* the sentence, +wrapping "LPG leakage" in a red span *inside* the sentence) is gone. Instead, +`serverMassage` extracts those as separate fields (`otp`, `leakage`), and the +`sms` body template renders `msg` as plain escaped text plus separate +elements: `leakageBanner(data.leakage)` above it, `copyableCodeChip(data.otp)` +after it. If a template needs to react to something in the message, extract +it into a field in `serverMassage` — don't regex the raw text again inside a +template. + +**Forward path to real JSON from the server:** `serverMassage` first checks +if `msg.trim().startsWith("{")` and, if it parses as JSON with a `type` +field, returns it **as-is**, no further processing: + +```js +if (msg.trim().startsWith("{")) { + try { + const parsed = JSON.parse(msg); + if (parsed && typeof parsed === "object" && parsed.type) return parsed; + } catch (e) { /* not valid JSON, fall through to plain-text parsing */ } +} +``` + +This means: **when the server starts sending real JSON in `msg` instead of +plain SMS text, no changes are needed here or anywhere else** — it already +takes that path. The `dispatch` type (§3) is already exercised through this +path today (see the sample injector). The iob/otp regex parsing is the +legacy fallback for actual plain-text SMS content and should stay only as +long as the server keeps sending that. + +### Templates + +`messageBodyTemplates` is a plain object keyed by `type`; each function owns +100% of that type's body markup — nothing outside the template decides how a +body renders. `renderMessageBody` just dispatches: +`messageBodyTemplates[data.type] || messageBodyTemplates.sms`. + +`renderMessageHeader({ imgType, sender, headerLabel, timeStr, mid, deviceName })` +is the **one common header** every message type shares (icon, sender, an +optional label, time, device button). Only `getHeaderLabel(data)` varies by +type — it's a tiny switch that says which field on that type's own object +(`merchant`, `sim`, ...) becomes the header's label. Adding a new type that +wants a header label means adding one `case` there, not touching the header +template. + +### `createMessageListItem(item)` + +Builds one `<li class="msg-list-item">` from a raw `{ sndr, sentstamp, mid, +cid, msg, extra }` item, using `serverMassage` + the header/body templates. +This is shared by: +- `fetchUpdates()` — the real, polling OTP feed into `#data-list`. +- `fetchActionUpdates()` — the real, polling action-required feed into `#action-list` (§3). + +Both lists render through the exact same code path. If you add a third +message list, build its items with this same function rather than writing +new markup. + +## 3. `#action-list` ("action required" panel) + the `dispatch` type + +The right-hand panel used to be a single hand-written `<li>` in `index.html` +with visibly broken inline CSS (`style="/*! display: flex !important; */ +align-items: ..."` — the `display: flex` was inside a comment, so it never +applied, which is why the card rendered mangled). That's gone. + +- `index.html` now just has `<ul id="action-list" class="sticky-list"></ul>`. +- `messageBodyTemplates.dispatch` renders the status badge, cargo grid, + details table, and "Acknowledge Invoice" button — same + body-owns-its-markup pattern as the other types. +- `fetchActionUpdates()` polls `config.endpoint` with `config.actionTable` + (default: `action`), parses JSON or GT responses, appends/removes rows in + `#action-list`, and calls `syncDateDividers(list)` so action items get the + same sticky date-divider treatment as the main list. +- Action polling is wired on `DOMContentLoaded` (not called inline at the + bottom of the script like `fetchUpdates()`), because `logs.js` is + `<script src="logs.js">`'d *before* `.content`/`#action-list` exist in the + DOM. `fetchUpdates()` gets away with running immediately only because its + own `await fetch(...)` yields control back until well after the parser has + moved on; action polling checks for `#action-list` synchronously before its + fetch, so it starts after the real DOM-ready signal. + +**Completed follow-up:** the search input above `#action-list` now has +`id="action-filter-search"` and calls `applyActionFilters()`, which filters +only `#action-list .msg-list-item`. `#action-list` is now populated by +`fetchActionUpdates()`, polling `config.endpoint` with `config.actionTable` +(default: `action`) and rendering through `createMessageListItem()`. The old +hardcoded `renderSampleActionItem()` sample path was removed. + +## Quick map of what lives where + +| Concern | Function(s) | File | +|---|---|---| +| Raw msg -> typed data | `serverMassage` | `logs.js` | +| Body markup per type | `messageBodyTemplates`, `renderMessageBody` | `logs.js` | +| Common header | `renderMessageHeader`, `getHeaderLabel` | `logs.js` | +| Build one `<li>` | `createMessageListItem` | `logs.js` | +| OTP feed polling | `fetchUpdates` | `logs.js` | +| Action-required polling | `fetchActionUpdates` | `logs.js` | +| Date grouping | `formatDateBadge`, `syncDateDividers` | `logs.js` | +| Divider sticky styling | `.date-divider` | `logs.css` | +| Leak/OTP chip styling | `.leakage-alert`, `.copyable-code` (inline) | `logs.css` / `logs.js` |
diff --git a/DEV.md b/DEV.md @@ -0,0 +1,36 @@ +# Local development + +Run a local static server for testing frontend changes: + +```sh +node dev-server.mjs +``` + +Then open: + +```text +http://127.0.0.1:8088/ +``` + +The server serves files from this checkout with `Cache-Control: no-store` so reloads pick up edits quickly. + +## Remote endpoints + +- `/logs.php` is executed on the deployed `maa-1:/srv/www/logs.saikrupagas.com/` checkout through SSH. This avoids needing local PHP, Composer dependencies, or `.env.php` secrets. +- `/kidang.fcgi` is proxied through `maa-1` directly to the deployed FastCGI socket, bypassing SSO so the browser receives the GT payload instead of the login HTML. + +Optional environment variables: + +```sh +PORT=9090 node dev-server.mjs +HOST=127.0.0.1 node dev-server.mjs +DEV_REMOTE_HOST=maa-1 node dev-server.mjs +DEV_REMOTE_VHOST=logs.saikrupagas.com node dev-server.mjs +DEV_REMOTE_ORIGIN=http://127.0.0.1:81 node dev-server.mjs +``` + +Quick endpoint check: + +```sh +curl 'http://127.0.0.1:8088/logs.php?id=1' +```
diff --git a/Makefile b/Makefile @@ -0,0 +1,67 @@ +.ONESHELL: +templates=head.html header.html footer.html + +pages=index.html privacy.html 404.html +deploy-path=lighttpd@saikrupagas.com:/srv/www/saikrupagas.com/ + +# Explicit allowlist of what actually belongs on the live site -- NOT +# `git ls-files`, which would ship every tracked file in the repo +# (internal tooling, dev configs, build scripts, anything else that +# happens to be checked in) straight to production. head.json and +# html/components/*.html are deliberately excluded -- they're only ever +# pulled in via m4 include() at build time, never fetched at runtime. +# This same list drives both `deploy-src` (scp to production) and `dist` +# (a local servable folder) -- one source of truth for "what's the site". +deploy-files=$(pages) css js robots.txt sitemap.xml favicon.ico \ + gl4xcy2rrdndf2uq9crpfq2oelee7w.html styles vendor +HOST_PORT=8000 +LIVESIDE_PORT=8001 +DIST=dist + +dev-all: M4FLAGS = -D LIVERELOAD=1 -D LIVESIDE_PORT=$(LIVESIDE_PORT) +dev-all: $(pages) + +# m4's include() resolves bare names (`header.html`, not `html/header.html` +# -- that's how every .html.in under html/ writes it) against m4's own +# current directory, not the including file's directory. So rather than +# rewrite every include() path, just run m4 with html/ as its cwd and +# send the output back up to the repo root, where it's served from. +html/head.html: html/head.html.in + cd html && m4 $(M4FLAGS) head.html.in > head.html + +%.html: html/%.html.in $(addprefix html/,$(templates)) + cd html && m4 $(M4FLAGS) $*.html.in > ../$*.html + +all: $(pages) + +autorefresh: + darkhttpd . --port $(HOST_PORT) & + liveside -d . -p $(LIVESIDE_PORT) -c "make dev-all" + +host: + darkhttpd . --port $(HOST_PORT) + +refresh: all + liveside -d . -p $(LIVESIDE_PORT) -c "make dev-all" + +deploy-src: clean all + scp -Cr $(deploy-files) $(deploy-path) + +deploy-assets: + scp -Cr assets $(deploy-path) + +deploy: deploy-src deploy-assets + +clean: + -rm html/head.html $(foreach page,$(pages),$(page)) + +# A single self-contained, servable folder -- everything deploy-src/ +# deploy-assets would ship to production, gathered in one place instead. +# Point any static server at it: `darkhttpd $(DIST) --port 8000`. +dist: clean all + rm -rf $(DIST) + mkdir -p $(DIST) + cp -R $(deploy-files) $(DIST)/ + cp -R assets $(DIST)/ + +.PHONY: all dev-all autorefresh host refresh deploy-src deploy-assets deploy clean dist
diff --git a/TVA-CONTROL.md b/TVA-CONTROL.md @@ -0,0 +1,85 @@ +# TVA Control + +Standalone Chart.js control for the TVA timeline/drilldowns. + +## Files + +Copy these together: + +- `tva-control.js` +- `tva-control.css` + +The host page must load Chart.js before `tva-control.js`. + +## Usage + +```html +<link rel="stylesheet" href="tva-control.css"> +<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> +<script src="tva-control.js"></script> + +<div id="tva" class="tva-control-container"><canvas></canvas></div> +<script> + const tva = createTvaControl({ + container: document.getElementById('tva'), + data: { + complaintsOpen: 0, + invoiceActions: 2, + deliveryPersonLeave: 0, + refillSpreadDays: 12, + pendencyDays: 2.7, + bpclDepositLakhs: 3, + updatedAt: { + // Example: force this parameter stale when its refresh window is 30 min. + bpclDepositLakhs: Date.now() - (31 * 60 * 1000) + }, + refillSpreadAreas: { 'KK NAGAR': 12, 'WEST MAMBALAM': 9 }, + pendencyAreas: { 'KK NAGAR': 3.4, 'WEST MAMBALAM': 2.9 } + } + }); + + tva.update({ bpclDepositLakhs: 4 }); +</script> +``` + +## API + +```js +const control = createTvaControl({ canvas?, container?, data }) +control.update(partialData) +control.setData(fullData) +control.getData() +control.refreshTheme() +control.destroy() +``` + +No default areas are built into the control. Pass all parameters and area rows as JSON from the host app. + +Freshness is controlled per parameter in init JSON with `refreshMinutes`. When a continuous update includes a parameter key, its internal refresh timer resets. To mark a value as old/stale explicitly, pass `updatedAt` timestamps in the data JSON. + +A warning level can leave an ambient glow behind its plot point. It is JSON-controlled and can be disabled for low-end devices: + +```js +ambientGlow: { enabled: true, alpha: 0.14, radius: 74, blur: 42 }, +warningLevels: [ + { key: 'amber', label: 'AMBER ALERT', priority: 1, glowAlpha: 0.12 }, + { key: 'red', label: 'CRITICAL', priority: 2, glowAlpha: 0.16 }, + { key: 'double-red', label: 'DOUBLE RED', priority: 3, glowRadius: 88, glowBlur: 54 } +] +``` + +Per-level `glowColor`, `glowAlpha`, `glowRadius`, `glowBlur`, or `ambientGlow: false`/`glow: false` override the global glow behavior. The glow color defaults to the configured warning level color. The effect is drawn as a large radial background wash, not a foreground marker overlay. + +A warning level can pulse the control border when it is the highest active level: + +```js +warningLevels: [ + { key: 'double-red', label: 'DOUBLE RED', priority: 3, borderBlink: true } +] +``` + +Aliases `blinkBorder` and `borderAlert` are also accepted. + +Visual theme values are owned by `tva-control.css`. To switch themes, set `data-tva-theme="dark"` or `data-tva-theme="light"` on the control container and call `control.refreshTheme()` so canvas-rendered colors are re-read from CSS. + +See `tva-control-demo.html` for a complete standalone example.
diff --git a/assets/cid-2-16x.png b/assets/cid-2-16x.png Binary files differ.
diff --git a/assets/message.png b/assets/message.png Binary files differ.
diff --git a/assets/printer.svg b/assets/printer.svg @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> + <!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools --> +<svg width="16px" height="16px" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"> +<g clip-path="url(#clip0_901_1437)"> +<path d="M6 14V2C6 1.447 6.447 1 7 1H25C25.553 1 26 1.447 26 2V14M11 8H16M11 12H21M31 30C31 30.552 30.553 31 30 31H2C1.447 31 1 30.552 1 30V21C1 18.771 2.667 17 5 17H27C29.333 17 31 18.75 31 21V30ZM27 22C27 22.553 26.553 23 26 23C25.447 23 25 22.553 25 22C25 21.447 25.447 21 26 21C26.553 21 27 21.447 27 22ZM22 22C22 22.553 21.553 23 21 23C20.447 23 20 22.553 20 22C20 21.447 20.447 21 21 21C21.553 21 22 21.447 22 22Z" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> +</g> +<defs> +<clipPath id="clip0_901_1437"> +<rect width="32" height="32" fill="white"/> +</clipPath> +</defs> +</svg>+ \ No newline at end of file
diff --git a/assets/tampermonkey.svg b/assets/tampermonkey.svg @@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<svg version="1.1" viewBox="0 0 250.67 250.67" width="16px" height="16px" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><title>tampermonkey_icon</title><metadata><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/><dc:title>tampermonkey_icon</dc:title><cc:license rdf:resource="https://www.gnu.org/licenses/gpl-3.0.html"/><dc:date>2016-05-26</dc:date><dc:creator><cc:Agent><dc:title>derjanb (https://github.com/derjanb)</dc:title></cc:Agent></dc:creator><dc:rights><cc:Agent><dc:title>https://www.gnu.org/licenses/gpl-3.0.html</dc:title></cc:Agent></dc:rights><dc:publisher><cc:Agent><dc:title>Marti Martz (https://github.com/Martii)</dc:title></cc:Agent></dc:publisher><dc:source>https://github.com/Tampermonkey/tampermonkey/blob/fb31096869523ecdec3b4ae06fbf21678eddb565/images/icon128.png</dc:source></cc:Work></rdf:RDF></metadata><path d="m62.115 0c-34.412 0-62.115 27.703-62.115 62.115v126.44c0 34.412 27.703 62.115 62.115 62.115h126.44c34.412 0 62.115-27.703 62.115-62.115v-126.44c0-34.412-27.703-62.115-62.115-62.115zm4.6758 132.58a51.124 51.124 0 0 1 5.1035 0.25586 51.124 51.124 0 0 1 5.0527 0.76367 51.124 51.124 0 0 1 4.9512 1.2637 51.124 51.124 0 0 1 4.8008 1.7539 51.124 51.124 0 0 1 4.6016 2.2226 51.124 51.124 0 0 1 4.3574 2.6699 51.124 51.124 0 0 1 4.0684 3.0938 51.124 51.124 0 0 1 3.7383 3.4824 51.124 51.124 0 0 1 3.373 3.8398 51.124 51.124 0 0 1 2.9727 4.1562 51.124 51.124 0 0 1 2.543 4.4336 51.124 51.124 0 0 1 2.0879 4.6641 51.124 51.124 0 0 1 1.6113 4.8496 51.124 51.124 0 0 1 1.1192 4.9863 51.124 51.124 0 0 1 0.61523 5.0723 51.124 51.124 0 0 1 0.12891 3.6172 51.124 51.124 0 0 1-0.25586 5.1035 51.124 51.124 0 0 1-0.76368 5.0527 51.124 51.124 0 0 1-1.2656 4.9512 51.124 51.124 0 0 1-1.752 4.8008 51.124 51.124 0 0 1-2.2227 4.6016 51.124 51.124 0 0 1-2.6699 4.3574 51.124 51.124 0 0 1-3.0938 4.0684 51.124 51.124 0 0 1-3.4824 3.7383 51.124 51.124 0 0 1-3.8398 3.373 51.124 51.124 0 0 1-4.1562 2.9727 51.124 51.124 0 0 1-4.4336 2.543 51.124 51.124 0 0 1-4.6641 2.0879 51.124 51.124 0 0 1-4.8496 1.6113 51.124 51.124 0 0 1-4.9863 1.1191 51.124 51.124 0 0 1-5.0723 0.61523 51.124 51.124 0 0 1-3.6172 0.12695 51.124 51.124 0 0 1-5.1035-0.2539 51.124 51.124 0 0 1-5.0527-0.76367 51.124 51.124 0 0 1-4.9512-1.2656 51.124 51.124 0 0 1-4.8008-1.752 51.124 51.124 0 0 1-4.6016-2.2227 51.124 51.124 0 0 1-4.3574-2.6719 51.124 51.124 0 0 1-4.0684-3.0918 51.124 51.124 0 0 1-3.7383-3.4824 51.124 51.124 0 0 1-3.373-3.8398 51.124 51.124 0 0 1-2.9727-4.1563 51.124 51.124 0 0 1-2.543-4.4336 51.124 51.124 0 0 1-2.0879-4.6641 51.124 51.124 0 0 1-1.6113-4.8496 51.124 51.124 0 0 1-1.1191-4.9863 51.124 51.124 0 0 1-0.61523-5.0742 51.124 51.124 0 0 1-0.12891-3.6152 51.124 51.124 0 0 1 0.25586-5.1035 51.124 51.124 0 0 1 0.76367-5.0527 51.124 51.124 0 0 1 1.2637-4.9531 51.124 51.124 0 0 1 1.7539-4.7988 51.124 51.124 0 0 1 2.2227-4.6016 51.124 51.124 0 0 1 2.6699-4.3574 51.124 51.124 0 0 1 3.0938-4.0684 51.124 51.124 0 0 1 3.4824-3.7383 51.124 51.124 0 0 1 3.8398-3.373 51.124 51.124 0 0 1 4.1562-2.9726 51.124 51.124 0 0 1 4.4336-2.543 51.124 51.124 0 0 1 4.6641-2.0879 51.124 51.124 0 0 1 4.8496-1.6113 51.124 51.124 0 0 1 4.9863-1.1191 51.124 51.124 0 0 1 5.0723-0.61524 51.124 51.124 0 0 1 3.6172-0.1289zm117.54 0a51.124 51.124 0 0 1 5.1035 0.25586 51.124 51.124 0 0 1 5.0527 0.76367 51.124 51.124 0 0 1 4.9531 1.2637 51.124 51.124 0 0 1 4.7988 1.7539 51.124 51.124 0 0 1 4.6016 2.2226 51.124 51.124 0 0 1 4.3574 2.6699 51.124 51.124 0 0 1 4.0684 3.0938 51.124 51.124 0 0 1 3.7383 3.4824 51.124 51.124 0 0 1 3.373 3.8398 51.124 51.124 0 0 1 2.9727 4.1562 51.124 51.124 0 0 1 2.543 4.4336 51.124 51.124 0 0 1 2.0879 4.6641 51.124 51.124 0 0 1 1.6113 4.8496 51.124 51.124 0 0 1 1.1191 4.9863 51.124 51.124 0 0 1 0.61523 5.0723 51.124 51.124 0 0 1 0.12891 3.6172 51.124 51.124 0 0 1-0.25586 5.1035 51.124 51.124 0 0 1-0.76367 5.0527 51.124 51.124 0 0 1-1.2637 4.9512 51.124 51.124 0 0 1-1.7539 4.8008 51.124 51.124 0 0 1-2.2227 4.6016 51.124 51.124 0 0 1-2.6699 4.3574 51.124 51.124 0 0 1-3.0938 4.0684 51.124 51.124 0 0 1-3.4824 3.7383 51.124 51.124 0 0 1-3.8398 3.373 51.124 51.124 0 0 1-4.1563 2.9727 51.124 51.124 0 0 1-4.4336 2.543 51.124 51.124 0 0 1-4.6641 2.0879 51.124 51.124 0 0 1-4.8496 1.6113 51.124 51.124 0 0 1-4.9863 1.1191 51.124 51.124 0 0 1-5.0723 0.61523 51.124 51.124 0 0 1-3.6172 0.12695 51.124 51.124 0 0 1-5.1035-0.2539 51.124 51.124 0 0 1-5.0527-0.76367 51.124 51.124 0 0 1-4.9512-1.2656 51.124 51.124 0 0 1-4.8008-1.752 51.124 51.124 0 0 1-4.6016-2.2227 51.124 51.124 0 0 1-4.3574-2.6719 51.124 51.124 0 0 1-4.0684-3.0918 51.124 51.124 0 0 1-3.7383-3.4824 51.124 51.124 0 0 1-3.373-3.8398 51.124 51.124 0 0 1-2.9726-4.1563 51.124 51.124 0 0 1-2.543-4.4336 51.124 51.124 0 0 1-2.0879-4.6641 51.124 51.124 0 0 1-1.6113-4.8496 51.124 51.124 0 0 1-1.1191-4.9863 51.124 51.124 0 0 1-0.61524-5.0742 51.124 51.124 0 0 1-0.12695-3.6152 51.124 51.124 0 0 1 0.25391-5.1035 51.124 51.124 0 0 1 0.76367-5.0527 51.124 51.124 0 0 1 1.2656-4.9531 51.124 51.124 0 0 1 1.752-4.7988 51.124 51.124 0 0 1 2.2226-4.6016 51.124 51.124 0 0 1 2.6719-4.3574 51.124 51.124 0 0 1 3.0918-4.0684 51.124 51.124 0 0 1 3.4824-3.7383 51.124 51.124 0 0 1 3.8398-3.373 51.124 51.124 0 0 1 4.1562-2.9726 51.124 51.124 0 0 1 4.4336-2.543 51.124 51.124 0 0 1 4.6641-2.0879 51.124 51.124 0 0 1 4.8496-1.6113 51.124 51.124 0 0 1 4.9863-1.1191 51.124 51.124 0 0 1 5.0742-0.61524 51.124 51.124 0 0 1 3.6152-0.1289z" fill="#222"/></svg>
diff --git a/composer.json b/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "guzzlehttp/guzzle": "^8.0" + } +}
diff --git a/composer.lock b/composer.lock @@ -0,0 +1,671 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "7a0eda22374a9e977ccd013b8485f1fc", + "packages": [ + { + "name": "guzzlehttp/guzzle", + "version": "8.0.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "d1cbca76970939a9c2ced55b1e25ea26f34fc773" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/d1cbca76970939a9c2ced55b1e25ea26f34fc773", + "reference": "d1cbca76970939a9c2ced55b1e25ea26f34fc773", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^3.0.1", + "guzzlehttp/psr7": "^3.0", + "php": "^7.4 || ^8.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "symfony/polyfill-php80": "^1.25", + "symfony/polyfill-php82": "^1.27" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "guzzle/client-integration-tests": "4.0.1", + "guzzlehttp/test-server": "^1.0", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^9.6.34", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/8.0.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2026-08-05T19:50:26+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "64f38b87fa7d371853804161bfc701c9bc2cc00a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/64f38b87fa7d371853804161bfc701c9bc2cc00a", + "reference": "64f38b87fa7d371853804161bfc701c9bc2cc00a", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^9.6.34" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2026-08-05T19:35:04+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "b094ded77ee97a6027ad6cf0e8c7b9f88381814c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/b094ded77ee97a6027ad6cf0e8c7b9f88381814c", + "reference": "b094ded77ee97a6027ad6cf0e8c7b9f88381814c", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0", + "psr/http-factory": "^1.1", + "psr/http-message": "^2.0", + "symfony/polyfill-php80": "^1.25", + "symfony/polyfill-php82": "^1.27" + }, + "provide": { + "psr/http-factory-implementation": "1.1", + "psr/http-message-implementation": "2.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "1.1.0", + "jshttp/mime-db": "1.54.0.1", + "php-http/psr7-integration-tests": "^1.5.1", + "phpunit/phpunit": "^9.6.34" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/3.0.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2026-07-20T13:48:31+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.37.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-04-10T16:19:22+00:00" + }, + { + "name": "symfony/polyfill-php82", + "version": "v1.38.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php82.git", + "reference": "002dc0cfe5fd4ed6033d48f27d4f19a486c4b04b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/002dc0cfe5fd4ed6033d48f27d4f19a486c4b04b", + "reference": "002dc0cfe5fd4ed6033d48f27d4f19a486c4b04b", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php82\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php82/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-26T12:45:58+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +}
diff --git a/dev-server.mjs b/dev-server.mjs @@ -0,0 +1,180 @@ +#!/usr/bin/env node +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { extname, join, normalize } from 'node:path'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); +const root = process.cwd(); +const port = Number(process.env.PORT || 8088); +const host = process.env.HOST || '127.0.0.1'; +const remoteHost = process.env.DEV_REMOTE_HOST || 'maa-1'; +const remoteVhost = process.env.DEV_REMOTE_VHOST || 'logs.saikrupagas.com'; +const remoteOrigin = process.env.DEV_REMOTE_ORIGIN || 'http://127.0.0.1:81'; + +const contentTypes = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon' +}; + +function send(res, status, body, headers = {}) { + res.writeHead(status, headers); + res.end(body); +} + +function safeStaticPath(pathname) { + const requested = pathname === '/' ? '/index.html' : pathname; + const clean = normalize(decodeURIComponent(requested)).replace(/^\.\.(\/|\\|$)/, ''); + return join(root, clean); +} + +function shellQuote(value) { + return `'${String(value).replace(/'/g, `'\\''`)}'`; +} + +async function proxyRemotePhp(req, res, query) { + try { + const phpCode = `parse_str(${JSON.stringify(query)}, $_GET); chdir('/srv/www/logs.saikrupagas.com'); include 'logs.php';`; + const remoteCommand = ['php', '-d', 'display_errors=0', '-r', shellQuote(phpCode)].join(' '); + const { stdout, stderr } = await execFileAsync('ssh', [remoteHost, remoteCommand], { maxBuffer: 10 * 1024 * 1024 }); + + if (stderr) console.warn(`[dev-server] remote php stderr: ${stderr.trim()}`); + send(res, 200, stdout, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store' + }); + } catch (error) { + console.error('[dev-server] remote PHP failed:', error.message); + send(res, 502, JSON.stringify({ error: 'Remote PHP failed', detail: error.message }), { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store' + }); + } +} + +const fastcgiProxyScript = String.raw` +import glob, socket, struct, sys +query = sys.argv[1] +sockets = sorted(glob.glob('/run/lighttpd/http.socket-*')) +if not sockets: + raise SystemExit('No kidang FastCGI socket found') + +def rec(record_type, request_id, content=b''): + padding = (-len(content)) % 8 + return struct.pack('!BBHHBB', 1, record_type, request_id, len(content), padding, 0) + content + (b'\0' * padding) + +def enc_len(length): + return bytes([length]) if length < 128 else struct.pack('!I', length | 0x80000000) + +def param(name, value): + name = name.encode() + value = value.encode() + return enc_len(len(name)) + enc_len(len(value)) + name + value + +request_id = 1 +params = { + 'GATEWAY_INTERFACE': 'CGI/1.1', + 'REQUEST_METHOD': 'GET', + 'SCRIPT_NAME': '/kidang.fcgi', + 'SCRIPT_FILENAME': '/home/bharat/kidang/kidang.fcgi', + 'QUERY_STRING': query, + 'SERVER_SOFTWARE': 'logs-dev-server', + 'SERVER_PROTOCOL': 'HTTP/1.1', + 'CONTENT_LENGTH': '0', + 'DOCUMENT_ROOT': '/srv/www/logs.saikrupagas.com', + 'REMOTE_ADDR': '127.0.0.1', + 'SERVER_NAME': 'logs.saikrupagas.com', + 'SERVER_PORT': '443', + 'HTTPS': 'on', +} + +sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +sock.connect(sockets[-1]) +sock.sendall(rec(1, request_id, struct.pack('!HB5s', 1, 0, b''))) +sock.sendall(rec(4, request_id, b''.join(param(k, v) for k, v in params.items()))) +sock.sendall(rec(4, request_id, b'')) +sock.sendall(rec(5, request_id, b'')) + +stdout = b'' +stderr = b'' +while True: + header = sock.recv(8) + if not header: + break + _version, record_type, _rid, content_length, padding_length, _reserved = struct.unpack('!BBHHBB', header) + content = b'' + while len(content) < content_length: + content += sock.recv(content_length - len(content)) + if padding_length: + sock.recv(padding_length) + if record_type == 6: + stdout += content + elif record_type == 7: + stderr += content + elif record_type == 3: + break + +if stderr: + print(stderr.decode('utf-8', 'replace'), file=sys.stderr) + +separator = b'\r\n\r\n' if b'\r\n\r\n' in stdout else b'\n\n' +body = stdout.split(separator, 1)[1] if separator in stdout else stdout +sys.stdout.buffer.write(body) +`; + +async function proxyRemoteKidang(res, query) { + try { + const remoteCommand = ['python3', '-c', shellQuote(fastcgiProxyScript), shellQuote(query)].join(' '); + const { stdout, stderr } = await execFileAsync('ssh', [remoteHost, remoteCommand], { maxBuffer: 20 * 1024 * 1024 }); + + if (stderr) console.warn(`[dev-server] remote kidang stderr: ${stderr.trim()}`); + send(res, 200, stdout, { + 'Content-Type': 'text/plain; charset=utf-8', + 'Cache-Control': 'no-store' + }); + } catch (error) { + console.error('[dev-server] remote kidang failed:', error.message); + send(res, 502, JSON.stringify({ error: 'Remote kidang failed', detail: error.message }), { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store' + }); + } +} + +createServer(async (req, res) => { + const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`); + + if (url.pathname === '/logs.php') { + await proxyRemotePhp(req, res, url.searchParams.toString()); + return; + } + + if (url.pathname === '/kidang.fcgi') { + await proxyRemoteKidang(res, url.searchParams.toString()); + return; + } + + try { + const filePath = safeStaticPath(url.pathname); + const body = await readFile(filePath); + send(res, 200, body, { + 'Content-Type': contentTypes[extname(filePath).toLowerCase()] || 'application/octet-stream', + 'Cache-Control': 'no-store' + }); + } catch (error) { + send(res, 404, 'Not found\n', { 'Content-Type': 'text/plain; charset=utf-8' }); + } +}).listen(port, host, () => { + console.log(`Local dev server: http://${host}:${port}`); + console.log(`Proxying /logs.php and /kidang.fcgi through ${remoteHost} (${remoteVhost})`); +});
diff --git a/gt.js b/gt.js @@ -0,0 +1,216 @@ +function parseGT(input) { + let index = 0; + const inputLength = input.length; + + // Helper function to skip whitespace + function skipWhitespace() { + while (index < inputLength && /\s/.test(input[index])) { + index++; + } + } + + // Helper function to throw error with context + function throwError(message) { + const contextStart = Math.max(0, index - 10); + const contextEnd = Math.min(inputLength, index + 10); + const context = input.slice(contextStart, contextEnd); + throw new Error(`${message} at position ${index}. Context: "...${context}..."`); + } + + // Parse a value (object, array, string, number, or unquoted string) + function parseValue() { + skipWhitespace(); + const char = input[index]; + + if (char === '{') { + return parseObject(); + } else if (char === '[') { + return parseArray(); + } else if (char === "'") { + return parseString(); + } else if (/[0-9-]/.test(char)) { + return parseNumberOrUnquotedString(); + } else { + return parseUnquotedString(); + } + } + + // Parse an object + function parseObject() { + if (input[index] !== '{') { + throwError("Expected '{'"); + } + index++; + + const obj = {}; + skipWhitespace(); + + while (index < inputLength && input[index] !== '}') { + const key = parseKey(); + skipWhitespace(); + + const value = parseValue(); + obj[key] = value; + + skipWhitespace(); + + // No special handling for commas - just skip any whitespace + if (input[index] === '}') { + break; + } + } + + if (input[index] !== '}') { + throwError("Expected '}' to close object"); + } + index++; + + return obj; + } + + // Parse an array + function parseArray() { + if (input[index] !== '[') { + throwError("Expected '['"); + } + index++; + + const arr = []; + skipWhitespace(); + + while (index < inputLength && input[index] !== ']') { + const value = parseValue(); + arr.push(value); + + skipWhitespace(); + + // No special handling for commas - just skip any whitespace + if (input[index] === ']') { + break; + } + } + + if (input[index] !== ']') { + throwError("Expected ']' to close array"); + } + index++; + + return arr; + } + + // Parse a string (single-quoted) + function parseString() { + if (input[index] !== "'") { + throwError("Expected single quote"); + } + index++; + + let str = ''; + while (index < inputLength && input[index] !== "'") { + if (input[index] === '\\') { + index++; + if (index >= inputLength) { + throwError("Unterminated escape sequence"); + } + // Handle escape sequences + switch (input[index]) { + case "'": str += "'"; break; + case "\\": str += "\\"; break; + case "/": str += "/"; break; + case "b": str += "\b"; break; + case "f": str += "\f"; break; + case "n": str += "\n"; break; + case "r": str += "\r"; break; + case "t": str += "\t"; break; + default: str += input[index]; break; + } + } else { + str += input[index]; + } + index++; + } + + if (input[index] !== "'") { + throwError("Unterminated string"); + } + index++; + + return str; + } + + // Parse a key (either quoted or unquoted string) + function parseKey() { + skipWhitespace(); + if (input[index] === "'") { + return parseString(); + } + return parseUnquotedString(); + } + + // Parse an unquoted string (now includes ':' and ',' as regular characters) + function parseUnquotedString() { + let str = ''; + while (index < inputLength && !/[\]}\s]/.test(input[index])) { + str += input[index]; + index++; + } + return str; + } + + // Parse a number or unquoted string (for values starting with digit or minus) + function parseNumberOrUnquotedString() { + const start = index; + + // Handle negative numbers + if (input[index] === '-') { + index++; + } + + // Parse integer part + while (index < inputLength && /[0-9]/.test(input[index])) { + index++; + } + + // Parse fractional part + if (input[index] === '.') { + index++; + while (index < inputLength && /[0-9]/.test(input[index])) { + index++; + } + } + + // Parse exponent part + if (/[eE]/.test(input[index])) { + index++; + if (/[+-]/.test(input[index])) { + index++; + } + while (index < inputLength && /[0-9]/.test(input[index])) { + index++; + } + } + + const potentialNumber = input.slice(start, index); + + // Check if we have a valid number + if (/^-?\d+\.?\d*([eE][+-]?\d+)?$/.test(potentialNumber)) { + return parseFloat(potentialNumber); + } + + // If not a valid number, treat as unquoted string + index = start; + return parseUnquotedString(); + } + + try { + skipWhitespace(); + const result = parseValue(); + skipWhitespace(); + if (index < inputLength) { + throwError("Unexpected characters at end of input"); + } + return result; + } catch (e) { + throw new Error(`Failed to parse input: ${e.message}`); + } +}
diff --git a/index.html b/index.html @@ -0,0 +1,112 @@ +<!DOCTYPE html> +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Event Notifications</title> + <link rel="stylesheet" href="style.css"> + <link rel="stylesheet" href="logs.css"> + <link rel="stylesheet" href="tva-control.css"> + <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> +<body> + <template id="custom-date"> + <style> + .date-p { + text-align: center; + width: fit-content; + line-height: 0.7em; + position: relative; + left: -6px; + } + </style> + <div class="date-p"> + <p style="font-weight: 700;color: black;">23</p> + <small>Aug</small> + <hr style="border: 1px solid black;"> + </div> +</template> + <script src="tva-control.js"></script> + <script src="logs.js"></script> + <div class="content"> + <script src="gt.js"></script> + <button type="button" class="settings-button settings-icon-button" onclick="openLogsSettings()" aria-haspopup="dialog" aria-label="Settings" title="Settings">⚙</button> + <header class="app-chart-header"> + <div class="action-chart-container app-header-chart"> + <canvas id="tvaReactiveChart" aria-label="Action required baseline monitor"></canvas> + </div> + </header> + <dialog id="logs-settings-dialog" class="settings-dialog"> + <form method="dialog" class="settings-card"> + <h2>Settings</h2> + <label>Theme + <select id="settings-theme" class="filter-select"> + <option value="auto">Auto</option> + <option value="light">Light</option> + <option value="dark">Dark</option> + </select> + </label> + <label class="settings-checkbox"> + <input type="checkbox" id="settings-ambient-glow"> + TVA ambient warning glow + </label> + <menu> + <button type="button" onclick="closeLogsSettings()">Cancel</button> + <button type="button" onclick="saveLogsSettings()">Save</button> + </menu> + </form> + </dialog> + <div popover="auto" id="device-info-popover"> + <div class="device-popover-container"> + <strong id="p-name"></strong> + <p>with <span style="border-radius: 4px; font-weight: 600;" id="p-assigned-to"></span></p> + <table style="border: 0px;"> + <tbody> + <tr><th>Serial</th><td td id="p-serial"></td></tr> + <tr><th>Notes</th><td td id="p-notes"></td></tr> + </tbody> + </table> + <img class="device-popover-image" id="p-image" src="" > + </div> + </div> + <!--<p>(Displaying OTP from the last 5 hours only)</p>--> + <!-- From/to range controls query kidang with fromTimestamp/toTimestamp. --> + <div class="mobile-panel-switch" aria-label="Choose log panel"> + <button type="button" class="active" data-target-segment="1" onclick="showMobileSegment(1)">Events</button> + <button type="button" data-target-segment="2" onclick="showMobileSegment(2)">Action Required</button> + </div> + <div class="segment-container"> + <div data-segment=1 class="segment active"> + <div class="log-filter-bar"> + <!-- Device Filter (Auto-populated by script) --> + <select id="filter-device" onchange="applyFilters()" class="filter-select"> + <option value="">All Devices (mId)</option> + </select> + + <!-- Category Filter --> + <select id="filter-category" onchange="applyFilters()" class="filter-select"> + <option value="">All Categories</option> + </select> + + <!-- Range Query Controls --> + <label class="range-filter-label">From + <input type="datetime-local" id="range-from" onchange="refreshRangeFeeds()" class="filter-select"> + </label> + <input type="hidden" id="range-to"> + + <!-- Query Text Input Bar --> + <input type="text" id="filter-search" placeholder="Type to search entries..." oninput="applyFilters()" class="filter-select" style="flex-grow: 1; min-width: 200px;"> + </div> + <ul id="data-list"></ul> + </div> + <div data-segment=2 class="segment"> + <div class="log-filter-bar"> + + <!-- Query Text Input Bar --> + <input type="text" id="action-filter-search" placeholder="Type to search action required..." oninput="applyActionFilters()" class="filter-select" style="flex-grow: 1; min-width: 200px;"> + </div> + <ul id="action-list" class="sticky-list"></ul> + </div> + </div> + </div> +</body> +</html> +
diff --git a/logs.css b/logs.css @@ -0,0 +1,944 @@ + +/* card – clean, elevated, with subtle border */ +.dispatch-card { + background: #ffffff; + border-radius: 28px; + padding: 1.8rem 2rem 2rem 2rem; +} + + +/* header: lorry + badge */ +.card-header { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 0.75rem 0.5rem; + border-bottom: 2px solid #f0f4f9; + padding-bottom: 1rem; + margin-bottom: 1.25rem; +} + +.lorry-id { + display: flex; + align-items: center; + gap: 0.65rem; + font-size: 1.5rem; + font-weight: 700; + letter-spacing: -0.02em; + color: #0b1a26; +} + +.lorry-id i { + color: #1e5f8e; + font-size: 1.6rem; + width: 2rem; + text-align: center; +} + +.lorry-plate { + background: #eef3f9; + padding: 0.25rem 1rem 0.25rem 0.9rem; + border-radius: 40px; + font-size: 1.3rem; + font-weight: 650; + color: #003057; + border: 1px solid #d0dce8; + box-shadow: inset 0 1px 3px rgba(0,0,0,0.02); + letter-spacing: 0.5px; +} + +.badge-status { + background: #d4e6f7; + color: #004b7c; + font-weight: 600; + font-size: 0.8rem; + padding: 0.3rem 1rem 0.3rem 0.9rem; + display: inline-flex; + align-items: center; + gap: 6px; + border: 1px solid #b8d1e9; + background: #e3effa; + letter-spacing: 0.3px; + white-space: nowrap; +} + +.badge-status i { + font-size: 0.75rem; + color: #0077be; +} + +/* main content rows */ +.route-line { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.3rem 0.75rem; + font-size: 1rem; + padding: 0.6rem 1rem; + margin-bottom: 1rem; +} + +.route-line .from, .route-line .to { + font-weight: 500; + color: #1f3a4b; +} + +.route-line .from i, .route-line .to i { + margin-right: 0.3rem; + color: #3c6e8f; + width: 1.1rem; +} + +.route-line .time { + font-weight: 600; + color: #003b66; + background: #e6edf5; + border-radius: 24px; + padding: 0.1rem 0.8rem; + font-size: 0.9rem; + letter-spacing: 0.2px; + white-space: nowrap; +} + +.route-line .cust-ref { + font-weight: 600; + color: #005b8c; + background: #e5eef7; + padding: 0.1rem 0.8rem; + border-radius: 30px; + font-size: 0.9rem; + white-space: nowrap; +} + +/* cargo grid – two columns */ +.cargo-grid { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 1.2rem; + border-radius: 24px; + border: 1px solid #e3ecf5; +} + +.cargo-item { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.95rem; +} + +.cargo-item i { + color: #2f6f96; + width: 1.4rem; + font-size: 1rem; + text-align: center; +} + +.cargo-item strong { + font-weight: 600; + color: #0e2b3d; +} + +.cargo-item .qty { + font-weight: 600; + color: #003057; + background: #ff980030; + border: 1px solid #ff9800; + border-radius: 8px; + padding: 1px 5px; + font-size: 0.85rem; + line-height: 1.6; +} + +.cargo-item .unit { + font-weight: 500; + color: #1f4a66; +} + +.cargo-item .kg-badge { + background: #d1e2f0; + padding: 0.1rem 0.5rem; + font-size: 0.75rem; + font-weight: 600; + color: #004070; +} + +/* invoice & value row */ +.invoice-row { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + padding: 0.8rem 1rem 0.8rem 1rem; + margin-top: 0.6rem; + gap: 0.5rem 1rem; +} + +.invoice-number { + display: flex; + align-items: center; + gap: 0.5rem; + font-weight: 500; + color: #1d3b4f; +} + +.invoice-number i { + color: #3a779b; + font-size: 1rem; + width: 1.4rem; +} + +.invoice-number span { + background: #ecf3fa; + padding: 0.1rem 0.9rem; + border-radius: 40px; + font-weight: 600; + color: #003d66; + letter-spacing: 0.3px; +} + +.value { + display: flex; + align-items: center; + gap: 0.4rem; + font-weight: 600; + color: #0b3d2b; + background: #e5f2ea; + padding: 0.25rem 1.2rem 0.25rem 1rem; + border-radius: 40px; + border: 1px solid #c4decb; +} + +.value i { + color: #2b7a4b; + font-size: 0.9rem; +} + +.value .amount { + font-size: 1.2rem; + font-weight: 700; + color: #004d2b; + letter-spacing: 0.2px; +} + +/* small meta / footer */ +.card-footer { + margin-top: 1.2rem; + font-size: 0.7rem; + color: #6b8396; + display: flex; + justify-content: flex-end; + border-top: 1px solid #eef4fa; + padding-top: 0.7rem; + letter-spacing: 0.2px; + gap: 0.5rem; +} + +.card-footer i { + color: #6f8da3; + margin-right: 0.2rem; +} + +/* responsive */ +@media (max-width: 550px) { + .cargo-grid { + grid-template-columns: 1fr; + gap: 0.4rem; + } + .route-line { + flex-direction: column; + align-items: flex-start; + gap: 0.3rem; + } + .route-line .time { + margin-left: 0; + align-self: flex-start; + } + .invoice-row { + flex-direction: column; + align-items: stretch; + gap: 0.5rem; + border-radius: 24px; + padding: 0.8rem 1rem; + } + .lorry-id { + font-size: 1.2rem; + flex-wrap: wrap; + } + .badge-status { + font-size: 0.7rem; + padding: 0.2rem 0.8rem; + } +} + +@media (max-width: 400px) { + .lorry-plate { + font-size: 1rem; + padding: 0.1rem 0.8rem; + } + .cargo-item { + font-size: 0.85rem; + } +} + +/* tweak for print / selection */ + + + +.copyable-code:hover { + background-color: #e2e2e2 !important; +} + + +.otp-item-row { + vertical-align: middle; +} + +.sim-badge { + background:#e1f5fe; + /* background: #fff01f8b; */ + clip-path: polygon(0% 0%, 70% 0%, 100% 25%, 100% 100%, 0% 100%); + border-radius: 2px; + color: #333; + padding: 1px 4px; + font-size: 11px; + margin: 1px 6px; +} + +/* logs start */ +.content { + padding: 24px; +} + +.logs-message { + font-size: 1em; + color: #333; + line-height: 1.4; + word-break: break-word; +} + +.leakage-alert { + color: #ff0000; + font-weight: bold; + margin-bottom: 4px; +} +/* logs end */ + +@supports(position-area: end) { + [popover] { + margin: 0; + position-area: end span-end; + position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline; + } +} + +:popover-open { + background-color: transparent; + border: transparent; +} + +.device-popover-image { + width: auto; + max-height: 78px; + max-width: 64px; + top: -14px; + right: 8px; + position: absolute; +} + +.device-popover-container { + background: white; + margin: 16px; + padding: 16px; + position: relative; + min-height: 64px; +} + +.log-filter-bar { + display: flex; + gap: 10px; + padding: 12px; + background: #fafafa; + border: 1px solid rgba(0, 0, 0, 0.04); + border-radius: 8px; + flex-wrap: wrap; + position: sticky; + top: 0; + z-index: 4; + box-shadow: none; +} + +.segment > ul { + padding-left: 2px; + margin-top: 8px; +} + +.segment > ul > li { + list-style-type: none; + margin-bottom: 6px; +} + +/* one standalone list item per date group, inserted before that group's first message. As a top-level + <li> (not nested inside a message row) it can stick to the top of the list on its own while the + day's messages scroll underneath it. */ +.date-divider { + position: sticky; + top: 64px; + z-index: 2; + background: #fff; + padding: 4px 12px; +} + +.date-divider .date-p { + left: 0; +} + +/* day/month badge, styled after the #custom-date template, nudged slightly to the left */ +.date-p { + text-align: center; + width: fit-content; + line-height: 0.7em; + position: relative; + left: -6px; +} + +.date-p p { + font-weight: 700; + color: black; + margin: 0; +} + +.date-p hr { + border: 1px solid black; + margin: 2px 0 0 0; +} + +.filter-select { + padding: 6px 12px; + border: 1px solid #ccc; + border-radius: 4px; + background: #fff; + font-size: 13px; +} + +.range-filter-label { + display: inline-flex; + align-items: center; + gap: 6px; + color: #555; + font-size: 13px; + white-space: nowrap; +} + +.range-filter-label .filter-select { + width: auto; +} + +.segment-container { + display: flex; + flex-direction: row; + gap: 1em; +} + +.segment { + min-width: 0; +} + +.segment[data-segment="1"] { + flex: 1.8 1 0; +} + +.segment[data-segment="2"] { + flex: 0.9 1 0; + max-width: 42rem; +} + +.mobile-panel-switch { + display: none; +} + +.mobile-panel-switch button { + flex: 1; + border: 1px solid #d8d8d8; + background: #fff; + padding: 10px 12px; + font-weight: 650; +} + +.mobile-panel-switch button.active { + background: #111; + border-color: #111; + color: #fff; +} + +.sticky-list { +} + +.notification-badge { + background: #eb2f06; + padding: 2px 4px; + border-radius: 2em; + position: absolute; + right: 12px; + color: white; +} + +.msg-item-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 4px; + line-height: 0.8rem; +} + +table { + border: 1px solid #ddd; + border-radius: 8px; +} + +table thead th { + border-bottom: 1px solid #ddd; + font-style: normal; + background: #f8f8f8; +} + +tr { + border-bottom: 1px solid #ddd; +} + +td { + padding: 0.62em; +} + +@media (max-width: 800px) { + .content { + padding: 12px; + } + + .mobile-panel-switch { + display: flex; + position: sticky; + top: 0; + z-index: 6; + gap: 0; + margin: 8px 0; + background: #fff; + border-radius: 10px; + box-shadow: none; + } + + .mobile-panel-switch button:first-child { + border-radius: 10px 0 0 10px; + } + + .mobile-panel-switch button:last-child { + border-radius: 0 10px 10px 0; + } + + .segment-container { + display: block; + } + + .segment { + display: none; + } + + .segment.active { + display: block; + } + + .log-filter-bar { + top: 46px; + } + + .date-divider { + top: 118px; + } + + .filter-select { + width: 100%; + min-width: 0 !important; + } + + .msg-item-header { + gap: 8px; + line-height: 1.1rem; + } +} + +@media (prefers-color-scheme: dark) { + :root { + color-scheme: dark; + } + + body { + background: #000 !important; + color: #d8e1e7 !important; + } + + .content { + background: #000; + color: #d8e1e7; + } + + h1, + .logs-message, + .dispatch-card, + .device-popover-container, + .range-filter-label, + .date-p p, + .date-p small { + color: #d8e1e7 !important; + } + + a, + .insignificant { + color: #8ec7ff !important; + } + + .log-filter-bar { + background: rgba(18, 25, 31, 0.94); + border-color: rgba(255, 255, 255, 0.06); + box-shadow: none; + } + + .filter-select, + .mobile-panel-switch button { + background: #151d23 !important; + border-color: #344653 !important; + color: #d8e1e7 !important; + } + + .filter-select::placeholder { + color: #748693; + } + + .msg-list-item { + background: transparent !important; + border-bottom-color: #24313a !important; + } + + .msg-list-item:hover { + background: transparent !important; + } + + .msg-item-header, + .msg-item-header small, + .device-name-button { + color: #93a7b4 !important; + } + + .msg-item-header span { + color: #e4edf2; + } + + .date-divider { + background: #000; + } + + .date-p hr { + border-color: #d8e1e7 !important; + } + + .copyable-code { + background: #1c2932 !important; + border-color: #3a4d5b !important; + color: #e8f2f7 !important; + } + + .copyable-code:hover { + background: #263847 !important; + } + + .sim-badge, + .route-line .time, + .route-line .cust-ref, + .invoice-number span, + .cargo-item .kg-badge { + background: #1c2a34 !important; + color: #b8d9ee !important; + border-color: #334b5b !important; + } + + .leakage-alert { + color: #ff7b86 !important; + } + + .msg-list-item[style*="fff5f5"] { + background: #2a1418 !important; + border-left-color: #ff5c6c !important; + } + + .dispatch-card, + .device-popover-container { + background: #121a21 !important; + border-color: #26333d !important; + } + + .card-header, + .card-footer, + .cargo-grid, + table thead th, + tr { + border-color: #26333d !important; + } + + table thead th { + background: #17212a !important; + } + + .lorry-id, + .route-line .from, + .route-line .to, + .cargo-item strong, + .invoice-number, + .value, + table, + th, + td { + color: #d8e1e7 !important; + } + + .lorry-id i, + .route-line i, + .cargo-item i, + .invoice-number i, + .card-footer i { + color: #8db7d0 !important; + } + + .lorry-plate, + .badge-status, + .value { + background: #172530 !important; + border-color: #335066 !important; + color: #c9e3f2 !important; + } + + .cargo-item .qty { + background: rgba(255, 152, 0, 0.14) !important; + border-color: rgba(255, 183, 77, 0.58) !important; + color: #ffd18a !important; + } + + .value .amount { + color: #7ee0a3 !important; + } + + .card-footer, + .range-filter-label { + color: #8fa2ae !important; + } + + .mobile-panel-switch { + background: #111920 !important; + box-shadow: none !important; + } + + .mobile-panel-switch button.active { + background: #e4edf2 !important; + border-color: #e4edf2 !important; + color: #111920 !important; + } +} + + +.settings-button { + margin-left: 10px; + padding: 6px 10px; + border: 1px solid #d8d8d8; + border-radius: 6px; + background: #fff; + color: #333; + cursor: pointer; + font-weight: 650; +} + +.settings-dialog { + border: 0; + border-radius: 14px; + padding: 0; + box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28); +} + +.settings-dialog::backdrop { + background: rgba(0, 0, 0, 0.42); +} + +.settings-card { + display: grid; + gap: 14px; + min-width: min(340px, 86vw); + padding: 20px; +} + +.settings-card h2 { + margin: 0; +} + +.settings-card label { + display: grid; + gap: 6px; + font-weight: 650; +} + +.settings-checkbox { + align-items: center; + display: flex !important; + gap: 8px !important; +} + +.settings-card menu { + display: flex; + gap: 8px; + justify-content: flex-end; + margin: 4px 0 0; + padding: 0; +} + +.settings-card menu button { + padding: 7px 12px; +} + +body.logs-dark { + background: #000 !important; + color: #d8e1e7 !important; +} + +body.logs-dark .content { + background: #000; + color: #d8e1e7; +} + +body.logs-dark h1, +body.logs-dark .logs-message, +body.logs-dark .range-filter-label, +body.logs-dark .date-p p, +body.logs-dark .date-p small { + color: #d8e1e7 !important; +} + +body.logs-dark .log-filter-bar, +body.logs-dark .settings-dialog { + background: rgba(18, 25, 31, 0.98); + border-color: rgba(255, 255, 255, 0.06); + color: #d8e1e7; +} + +body.logs-dark .filter-select, +body.logs-dark .settings-button, +body.logs-dark .settings-card menu button, +body.logs-dark .mobile-panel-switch button { + background: #151d23 !important; + border-color: #344653 !important; + color: #d8e1e7 !important; +} + +body.logs-dark .msg-list-item { + background: transparent !important; + border-bottom-color: #24313a !important; +} + +body.logs-dark .date-divider { + background: #000; +} + +body.logs-dark .copyable-code { + background: #1c2932 !important; + border-color: #3a4d5b !important; + color: #e8f2f7 !important; +} + +body.logs-light { + background: #fff !important; + color: #333 !important; +} + +body.logs-light .content, +body.logs-light .date-divider { + background: #fff !important; + color: #333 !important; +} + +body.logs-light h1, +body.logs-light .logs-message, +body.logs-light .range-filter-label, +body.logs-light .date-p p, +body.logs-light .date-p small { + color: #333 !important; +} + +body.logs-light .log-filter-bar { + background: #fafafa !important; + border-color: rgba(0, 0, 0, 0.04) !important; + box-shadow: none !important; +} + +body.logs-light .filter-select, +body.logs-light .settings-button, +body.logs-light .mobile-panel-switch button { + background: #fff !important; + border-color: #ccc !important; + color: #333 !important; +} + +body.logs-light .msg-list-item { + background: transparent !important; + border-bottom-color: #f2f2f2 !important; +} + +body.logs-light .msg-item-header span { + color: inherit !important; +} + +body.logs-light .msg-item-header small, +body.logs-light .device-name-button { + color: #727272 !important; +} + +.app-chart-header { + margin-bottom: 16px; +} + +.settings-icon-button { + aspect-ratio: 1; + display: inline-grid; + font-size: 18px; + min-width: 38px; + padding: 0; + place-items: center; + position: fixed; + right: 18px; + top: 18px; + z-index: 9990; +} + +.app-header-chart.action-chart-container { + height: 240px; + margin-bottom: 0; +} + +.app-header-chart.tva-chart-fullscreen-mode, +.tva-chart-fullscreen-mode { + bottom: 16px !important; + height: auto !important; + left: 16px !important; + max-height: none !important; + position: fixed !important; + right: 16px !important; + top: 16px !important; + width: auto !important; + z-index: 10001 !important; +} + +.app-header-chart.tva-chart-fullscreen-mode canvas, +.tva-chart-fullscreen-mode canvas { + max-height: none !important; +} + +@media (max-width: 800px) { + .app-header-chart.action-chart-container { + height: 220px; + } +}
diff --git a/logs.js b/logs.js @@ -0,0 +1,1801 @@ +// Fixed single-quote syntax break error +const ESC_MAP = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +let config = { + endpoint: "/kidang.fcgi", + otpTable: "otp", + // Disabled until the backend action-required table/schema exists. Keeping this + // enabled causes kidang.fcgi?table=action to return HTTP 500 on maa-1. + actionTable: null, + defaultRangeHours: 48,// 2 days + // Incoming timestamps represent local wall-clock time from the sender/receiver. + // Neutralise the browser timezone offset for display so dates don't appear ahead. + displayTimestampsAsLocalWallClock: false +}; + +const trackedDevices = new Set(); +const trackedCategories = new Set(); // Caches categories dynamically to prevent dropdown flickering + +const defaultLogsSettings = { theme: 'auto', ambientGlow: true }; +let logsSettings = loadLogsSettings(); + +function loadLogsSettings() { + try { + return { ...defaultLogsSettings, ...(JSON.parse(localStorage.getItem('logs_settings')) || {}) }; + } catch (e) { + return { ...defaultLogsSettings }; + } +} + +function persistLogsSettings() { + localStorage.setItem('logs_settings', JSON.stringify(logsSettings)); +} + +const tvaControlConfig = { + title: 'TVA REACTIVE CHANNEL', + blinkMs: 1100, + aliases: { + bookingAgeDays: 'refillSpreadDays', + bookingSpreadDays: 'refillSpreadDays', + bpclDeposit: 'bpclDepositLakhs' + }, + ambientGlow: { enabled: logsSettings.ambientGlow !== false, alpha: 0.14, radius: 74, blur: 42 }, + warningLevels: [ + { key: 'amber', label: 'AMBER ALERT', priority: 1, showAxis: true, dominance: 0.6, axisAlpha: 0.28, axisWidth: 1.45, axisDash: [3, 5], glowAlpha: 0.12 }, + { key: 'red', label: 'CRITICAL', priority: 2, showAxis: true, dominance: 0.7, axisAlpha: 0.42, axisWidth: 1.45, axisDash: [6, 6], glowAlpha: 0.16 }, + { key: 'double-red', label: 'DOUBLE RED', priority: 3, showAxis: false, dominance: 0.7, borderBlink: true, glowAlpha: 0.18, glowRadius: 88, glowBlur: 54 } + ], + colors: { + amber: '#ffcc00', + red: '#ff0055', + critical: '#ff0055', + 'double-red': '#ff1a1a', + doubleRed: '#ff1a1a', + disabled: '#777777' + }, + staleAlpha: 0.35, + parameters: [ + { key: 'complaintsOpen', label: 'Complaints Open', icon: 'warning', scale: 'count10', refreshMinutes: 15, thresholds: { amberUpper: 52.5, redUpper: 75, amberLower: -52.5, redLower: -75 } }, + { key: 'invoiceActions', label: 'Invoice Actions', icon: 'invoice', scale: 'count10', refreshMinutes: 15, thresholds: { amberUpper: 59.5, redUpper: 85, amberLower: -59.5, redLower: -85 } }, + { key: 'deliveryPersonLeave', label: 'Delivery Person Leave', icon: 'person', scale: 'count10', refreshMinutes: 720, thresholds: { amberUpper: 49, redUpper: 70, amberLower: -49, redLower: -70 } }, + { key: 'refillSpreadDays', label: 'Refill Spread', icon: 'calendar', scale: 'daysCritical', scaleBase: 10, scaleMax: 165, refreshMinutes: 1440, display: { suffix: 'd' }, thresholds: { amberUpper: 50, redUpper: 100, doubleRedUpper: 150, amberLower: -70, redLower: -100 }, detailMode: 'refill-spread', areaKey: 'refillSpreadAreas', detailTitle: 'REFILL SPREAD AREA SCAN', detailLevels: [{ level: 'amber', above: 5 }, { level: 'red', above: 10 }] }, + { key: 'pendencyDays', label: 'Pendency', icon: 'hourglass', scale: 'pendency', scaleIdeal: 1, scaleBase: 3, scaleMax: 115, refreshMinutes: 720, display: { suffix: 'd', decimals: 1 }, thresholds: { amberUpper: 33.33, redUpper: 100, amberLower: -70, redLower: -100 }, detailMode: 'pendency', areaKey: 'pendencyAreas', detailTitle: 'PENDENCY AREA SCAN', detailLevels: [{ level: 'amber', above: 1 }, { level: 'red', above: 3 }] }, + { key: 'bpclDepositLakhs', label: 'BPCL Deposit', icon: 'deposit', scale: 'raw', refreshMinutes: 30, display: { prefix: '₹', suffix: 'L', decimals: 1 }, thresholds: { amberUpper: 4, redUpper: 6, amberLower: -1, redLower: -3 } } + ], + extraAxes: [ + { label: 'BPCL Deposit Good', parameterKey: 'bpclDepositLakhs', value: 6, color: 'rgba(0,255,120,.5)', width: 1.8, dash: [4, 4] }, + { label: 'BPCL Deposit Soft', parameterKey: 'bpclDepositLakhs', value: 4, color: 'rgba(120,255,160,.34)', width: 1.4, dash: [2, 5] } + ] +}; + +const tvaMetrics = { + complaintsOpen: 0, + invoiceActions: 2, + deliveryPersonLeave: 0, + refillSpreadDays: getDaysSinceISTMonthDay(-1, 25), + amberRefillSpreadDays: 5, + criticalRefillSpreadDays: 10, + doubleRedRefillSpreadDays: 15, + bpclDepositLakhs: 3, + pendencyDays: 2.7, + idealPendencyMaxDays: 1, + criticalPendencyDays: 3, + refillSpreadAreas: [ + { name: 'KK NAGAR', days: 12 }, + { name: 'WEST MAMBALAM', days: 9 }, + { name: 'ASHOK NAGAR', days: 7 }, + { name: 'T NAGAR', days: 11 }, + { name: 'VADAPALANI', days: 6 }, + { name: 'KODAMBAKKAM', days: 8 }, + { name: 'SALIGRAMAM', days: 5 }, + { name: 'VIRUGAMBAKKAM', days: 10 }, + { name: 'NESAPAKKAM', days: 13 }, + { name: 'JAFFERKHANPET', days: 6 }, + { name: 'EKKATTUTHANGAL', days: 4 }, + { name: 'MGR NAGAR', days: 9 }, + { name: 'SAIDAPET', days: 7 } + ], + pendencyAreas: [ + { name: 'KK NAGAR', days: 3.4 }, + { name: 'WEST MAMBALAM', days: 2.9 }, + { name: 'ASHOK NAGAR', days: 2.6 }, + { name: 'T NAGAR', days: 3.1 }, + { name: 'VADAPALANI', days: 2.2 }, + { name: 'KODAMBAKKAM', days: 2.8 }, + { name: 'SALIGRAMAM', days: 1.9 }, + { name: 'VIRUGAMBAKKAM', days: 2.4 }, + { name: 'NESAPAKKAM', days: 3.0 }, + { name: 'JAFFERKHANPET', days: 2.1 }, + { name: 'EKKATTUTHANGAL', days: 1.7 }, + { name: 'MGR NAGAR', days: 2.5 }, + { name: 'SAIDAPET', days: 2.0 } + ] +}; +const tvaChartCheckpoints = ['Complaints Open', 'Invoice Actions', 'Delivery Person Leave', 'Refill Spread', 'Pendency', 'BPCL Deposit']; +const tvaCheckpointIcons = ['warning', 'invoice', 'person', 'calendar', 'hourglass', 'deposit']; +const tvaUsePlotIcons = true; +const tvaShowAlertBadge = true; +const tvaUpperThreshold = [75, 85, 70, 100, 100, 6]; +const tvaLowerThreshold = [-75, -85, -70, -100, -100, -3]; +const tvaAmberUpperThreshold = [52.5, 59.5, 49, 50, 33.33, 4]; +const tvaAmberLowerThreshold = [-52.5, -59.5, -49, -70, -70, -1]; +const tvaDoubleRedUpperThreshold = [Infinity, Infinity, Infinity, 150, Infinity, Infinity]; +const tvaShowDoubleRedAxis = false; +const tvaMetricDatasetIndex = 6; +let tvaReactiveChart = null; +let tvaControl = null; +let pendingTvaControlPatch = null; +let tvaMetricData = [0, 0, 0, 0, 0, 6.5]; +let tvaChartMode = 'timeline'; +let tvaShowPointLabels = false; +let tvaBlinkOn = true; +let tvaBlinkIntervalId = null; +let rangeFieldsInitialized = false; + +const reactiveThresholdBlastPlugin = { + id: 'reactiveThresholdBlast', + beforeDatasetsDraw(chart) { + const { ctx, chartArea } = chart; + const metricData = chart.data.datasets[tvaMetricDatasetIndex] && chart.data.datasets[tvaMetricDatasetIndex].data; + const metricMeta = chart.getDatasetMeta(tvaMetricDatasetIndex); + if (!chartArea || !metricData || !metricMeta || metricMeta.hidden) return; + + ctx.save(); + + metricData.forEach((value, index) => { + const breached = value > tvaUpperThreshold[index] || value < tvaLowerThreshold[index]; + const point = metricMeta.data[index]; + if (!breached || !point) return; + + const { x, y } = point.getProps(['x', 'y'], true); + const radius = 70; + const gradient = ctx.createRadialGradient(x, y, 4, x, y, radius); + gradient.addColorStop(0, 'rgba(255, 0, 85, 0.42)'); + gradient.addColorStop(0.38, 'rgba(255, 0, 85, 0.18)'); + gradient.addColorStop(1, 'rgba(255, 0, 85, 0)'); + + ctx.globalCompositeOperation = 'screen'; + ctx.fillStyle = gradient; + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2); + ctx.fill(); + + // Deterministic dither grain: gives the breach a static blast texture + // without introducing animation or frame-to-frame shimmer. + ctx.globalCompositeOperation = 'lighter'; + for (let i = 0; i < 90; i += 1) { + const seed = (index + 1) * 997 + i * 37; + const angle = (Math.sin(seed) * 10000 % 1) * Math.PI * 2; + const distance = Math.sqrt(Math.abs(Math.sin(seed * 1.7))) * radius; + const dotX = x + Math.cos(angle) * distance; + const dotY = y + Math.sin(angle) * distance; + const alpha = Math.max(0, 1 - distance / radius) * 0.22; + const size = 0.6 + Math.abs(Math.sin(seed * 2.3)) * 1.8; + + ctx.fillStyle = `rgba(255, ${Math.floor(20 + 45 * Math.abs(Math.sin(seed)))}, ${Math.floor(60 + 40 * Math.abs(Math.cos(seed)))}, ${alpha})`; + ctx.beginPath(); + ctx.arc(dotX, dotY, size, 0, Math.PI * 2); + ctx.fill(); + } + }); + + ctx.restore(); + } +}; + +function drawTvaCheckpointIcon(ctx, type, x, y, color) { + ctx.save(); + ctx.strokeStyle = color; + ctx.fillStyle = color; + ctx.lineWidth = 1.25; + ctx.lineCap = 'round'; + ctx.lineJoin = 'round'; + + if (type === 'warning') { + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x - 5.5, y + 10.5); + ctx.lineTo(x + 5.5, y + 10.5); + ctx.closePath(); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(x, y + 3.5); + ctx.lineTo(x, y + 7.2); + ctx.stroke(); + ctx.beginPath(); + ctx.arc(x, y + 9.2, 0.6, 0, Math.PI * 2); + ctx.fill(); + } else if (type === 'invoice') { + ctx.strokeRect(x - 5, y + 1, 10, 11.5); + [4, 7, 10].forEach(offset => { + ctx.beginPath(); + ctx.moveTo(x - 3, y + offset); + ctx.lineTo(x + 3, y + offset); + ctx.stroke(); + }); + } else if (type === 'person') { + ctx.beginPath(); + ctx.arc(x, y + 3.8, 2.8, 0, Math.PI * 2); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(x - 5, y + 12); + ctx.quadraticCurveTo(x, y + 7.6, x + 5, y + 12); + ctx.stroke(); + } else if (type === 'calendar') { + ctx.strokeRect(x - 5, y + 3, 10, 10); + ctx.beginPath(); + ctx.moveTo(x - 5, y + 6); + ctx.lineTo(x + 5, y + 6); + ctx.moveTo(x - 2.8, y + 1); + ctx.lineTo(x - 2.8, y + 4); + ctx.moveTo(x + 2.8, y + 1); + ctx.lineTo(x + 2.8, y + 4); + ctx.stroke(); + ctx.fillRect(x - 2.8, y + 8, 1.3, 1.3); + ctx.fillRect(x + 1.5, y + 8, 1.3, 1.3); + } else if (type === 'deposit') { + ctx.strokeRect(x - 5, y + 4, 10, 8); + ctx.beginPath(); + ctx.moveTo(x - 6, y + 4); + ctx.lineTo(x, y + 0.5); + ctx.lineTo(x + 6, y + 4); + ctx.moveTo(x - 3, y + 7); + ctx.lineTo(x + 3, y + 7); + ctx.moveTo(x - 3, y + 10); + ctx.lineTo(x + 3, y + 10); + ctx.stroke(); + } else if (type === 'hourglass') { + ctx.beginPath(); + ctx.moveTo(x - 5, y + 1); + ctx.lineTo(x + 5, y + 1); + ctx.lineTo(x - 5, y + 12.5); + ctx.lineTo(x + 5, y + 12.5); + ctx.closePath(); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(x - 2.8, y + 4); + ctx.lineTo(x + 2.8, y + 4); + ctx.moveTo(x - 2.2, y + 10); + ctx.lineTo(x + 2.2, y + 10); + ctx.stroke(); + } + + ctx.restore(); +} + +function getTvaTrend(index) { + if (index <= 0) return 'flat'; + const delta = tvaMetricData[index] - tvaMetricData[index - 1]; + if (delta >= 15) return 'up'; + if (delta <= -15) return 'down'; + return 'flat'; +} + +function getTvaPointLabel(index) { + const label = tvaChartCheckpoints[index]; + if (!label) return ''; + if (label === 'Pendency') return `${tvaMetrics.pendencyDays}d`; + if (label === 'Invoice Actions') return `${tvaMetrics.invoiceActions}`; + if (label === 'Complaints Open') return `${tvaMetrics.complaintsOpen}`; + if (label === 'Delivery Person Leave') return `${tvaMetrics.deliveryPersonLeave}`; + return `${tvaMetricData[index]}%`; +} + +function drawTvaPlotValueGroup(ctx, index, x, y, chartArea, blinkOn) { + const valueText = getTvaPointLabel(index); + const placeBelow = y - chartArea.top < 52; + const groupY = placeBelow ? y + 18 : y - 43; + const doubleRed = tvaMetricData[index] > tvaDoubleRedUpperThreshold[index]; + const breached = doubleRed || tvaMetricData[index] > tvaUpperThreshold[index] || tvaMetricData[index] < tvaLowerThreshold[index]; + const amber = breached || tvaMetricData[index] > tvaAmberUpperThreshold[index] || tvaMetricData[index] < tvaAmberLowerThreshold[index]; + + ctx.save(); + ctx.font = 'bold 9px monospace'; + const groupWidth = Math.max(28, ctx.measureText(valueText).width + 10); + const groupHeight = 31; + const groupX = Math.min( + Math.max(x - groupWidth / 2, chartArea.left + 2), + chartArea.right - groupWidth - 2 + ); + + ctx.globalAlpha = breached ? (blinkOn ? 1 : 0.38) : 1; + ctx.fillStyle = doubleRed ? 'rgba(62, 0, 18, 0.94)' : breached ? 'rgba(42, 0, 16, 0.82)' : amber ? 'rgba(42, 28, 0, 0.78)' : 'rgba(10, 10, 10, 0.58)'; + ctx.strokeStyle = doubleRed ? 'rgba(255, 20, 20, 1)' : breached ? 'rgba(255, 0, 85, 0.8)' : amber ? 'rgba(255, 204, 0, 0.72)' : 'rgba(255, 255, 255, 0.16)'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.rect(groupX, groupY, groupWidth, groupHeight); + ctx.fill(); + ctx.stroke(); + + const iconX = groupX + groupWidth / 2; + const iconY = groupY + 3; + drawTvaCheckpointIcon(ctx, tvaCheckpointIcons[index], iconX, iconY, '#ffffff'); + + ctx.fillStyle = '#ffffff'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(valueText, groupX + groupWidth / 2, groupY + 24); + ctx.restore(); +} + +const reactiveZeroAxisPlugin = { + id: 'reactiveZeroAxis', + afterDraw(chart) { + if (tvaChartMode !== 'timeline') return; + const { ctx, scales: { y } } = chart; + if (!y) return; + const yZeroPixel = y.getPixelForValue(0); + + ctx.save(); + ctx.strokeStyle = '#00ffcc'; + ctx.lineWidth = 2.5; + ctx.shadowColor = 'rgba(0, 255, 204, 0.38)'; + ctx.shadowBlur = 7; + ctx.beginPath(); + ctx.moveTo(0, yZeroPixel); + ctx.lineTo(chart.width, yZeroPixel); + ctx.stroke(); + ctx.restore(); + } +}; + +const reactivePointLabelsPlugin = { + id: 'reactivePointLabels', + afterDatasetsDraw(chart) { + if (tvaChartMode !== 'timeline') return; + const { ctx, chartArea } = chart; + const metricMeta = chart.getDatasetMeta(tvaMetricDatasetIndex); + if (!metricMeta || metricMeta.hidden) return; + + metricMeta.data.forEach((point, index) => { + if (!tvaUsePlotIcons) return; + const { x, y } = point.getProps(['x', 'y'], true); + drawTvaPlotValueGroup(ctx, index, x, y, chartArea, tvaBlinkOn); + }); + + const activeIndexes = new Set((chart.tooltip && chart.tooltip.dataPoints || []) + .filter(point => point.datasetIndex === tvaMetricDatasetIndex) + .map(point => point.dataIndex)); + if (tvaUsePlotIcons || (!tvaShowPointLabels && !activeIndexes.size)) return; + + metricMeta.data.forEach((point, index) => { + if (!tvaShowPointLabels && !activeIndexes.has(index)) return; + const { x, y } = point.getProps(['x', 'y'], true); + const text = getTvaPointLabel(index); + const breached = tvaMetricData[index] > tvaUpperThreshold[index] || tvaMetricData[index] < tvaLowerThreshold[index]; + + ctx.save(); + ctx.font = 'bold 10px monospace'; + const width = ctx.measureText(text).width + 14; + const height = 20; + const boxX = x - width / 2; + const boxY = y - 34; + + ctx.fillStyle = breached ? 'rgba(32, 0, 14, 0.86)' : 'rgba(8, 18, 17, 0.86)'; + ctx.strokeStyle = breached ? 'rgba(255, 0, 85, 0.74)' : 'rgba(0, 255, 204, 0.55)'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.roundRect(boxX, boxY, width, height, 8); + ctx.fill(); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(x - 4, boxY + height); + ctx.lineTo(x, boxY + height + 5); + ctx.lineTo(x + 4, boxY + height); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); + + ctx.fillStyle = '#ffffff'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(text, x, boxY + height / 2 + 1); + ctx.restore(); + }); + } +}; + +function getISTDateParts(date = new Date()) { + const parts = new Intl.DateTimeFormat('en-CA', { + timeZone: 'Asia/Kolkata', + year: 'numeric', + month: '2-digit', + day: '2-digit' + }).formatToParts(date); + const getPart = type => Number(parts.find(part => part.type === type).value); + return { year: getPart('year'), month: getPart('month'), day: getPart('day') }; +} + +function getISTDateEpochMs(year, month, day) { + return Date.UTC(year, month - 1, day, -5, -30, 0, 0); +} + +function getDaysSinceISTMonthDay(monthOffset, day) { + const nowParts = getISTDateParts(); + const targetMonthDate = new Date(Date.UTC(nowParts.year, nowParts.month - 1 + monthOffset, 1)); + const targetYear = targetMonthDate.getUTCFullYear(); + const targetMonth = targetMonthDate.getUTCMonth() + 1; + const targetEpoch = getISTDateEpochMs(targetYear, targetMonth, day); + const nowEpoch = Date.now(); + return Math.max(0, Math.floor((nowEpoch - targetEpoch) / (24 * 60 * 60 * 1000))); +} + +function actionMetricPercent(count, direction = 1) { + return Math.max(-100, Math.min(100, count * 10 * direction)); +} + +function pendencyMetricPercent(currentDays, idealMaxDays, criticalDays) { + if (!criticalDays) return 0; + if (currentDays <= idealMaxDays) return 0; + return Math.max(0, Math.min(115, (currentDays / criticalDays) * 100)); +} + +function refillSpreadMetricPercent(currentDays, criticalDays, doubleRedDays) { + if (!criticalDays) return 0; + const maxDays = doubleRedDays || criticalDays; + return Math.max(0, Math.min(165, (currentDays / criticalDays) * 100, (currentDays / maxDays) * 150)); +} + +function syncTvaMetricThresholds() { + const refillSpreadIndex = tvaChartCheckpoints.indexOf('Refill Spread'); + if (refillSpreadIndex !== -1 && tvaMetrics.criticalRefillSpreadDays) { + tvaAmberUpperThreshold[refillSpreadIndex] = (tvaMetrics.amberRefillSpreadDays / tvaMetrics.criticalRefillSpreadDays) * 100; + tvaUpperThreshold[refillSpreadIndex] = 100; + tvaDoubleRedUpperThreshold[refillSpreadIndex] = (tvaMetrics.doubleRedRefillSpreadDays / tvaMetrics.criticalRefillSpreadDays) * 100; + } + + const depositIndex = tvaChartCheckpoints.indexOf('BPCL Deposit'); + if (depositIndex !== -1) { + tvaAmberUpperThreshold[depositIndex] = 4; + tvaUpperThreshold[depositIndex] = 6; + tvaAmberLowerThreshold[depositIndex] = -1; + tvaLowerThreshold[depositIndex] = -3; + } + + const pendencyIndex = tvaChartCheckpoints.indexOf('Pendency'); + if (pendencyIndex !== -1 && tvaMetrics.criticalPendencyDays) { + tvaAmberUpperThreshold[pendencyIndex] = (tvaMetrics.idealPendencyMaxDays / tvaMetrics.criticalPendencyDays) * 100; + tvaUpperThreshold[pendencyIndex] = 100; + } +} + +function finiteNumber(value) { + const number = Number(value); + return Number.isFinite(number) ? number : null; +} + +function setTvaMetricFromPayload(payloadKey, metricKey, payload) { + if (!Object.prototype.hasOwnProperty.call(payload, payloadKey)) return; + const value = finiteNumber(payload[payloadKey]); + if (value !== null) tvaMetrics[metricKey] = value; +} + +function normalizeNamedDayAreas(value) { + const rows = Array.isArray(value) + ? value + : value && typeof value === 'object' + ? Object.entries(value).map(([name, days]) => ({ name, days })) + : []; + + return rows.map((row, index) => { + const name = String(row.name || row.area || row.areaName || `Area ${index + 1}`).trim(); + const days = finiteNumber(row.days ?? row.pendencyDays ?? row.currentDays); + return name && days !== null ? { name, days } : null; + }).filter(Boolean); +} + +function setTvaPendencyAreasFromPayload(payload) { + if (!Object.prototype.hasOwnProperty.call(payload, 'pendencyAreas')) return; + const areas = normalizeNamedDayAreas(payload.pendencyAreas); + if (areas.length) tvaMetrics.pendencyAreas = areas; +} + +function setTvaRefillSpreadAreasFromPayload(payload) { + if (!Object.prototype.hasOwnProperty.call(payload, 'refillSpreadAreas')) return; + const areas = normalizeNamedDayAreas(payload.refillSpreadAreas); + if (areas.length) tvaMetrics.refillSpreadAreas = areas; +} + +function applyTvaMetricUpdate(payload) { + if (!payload || String(payload.type || '').toLowerCase() !== 'tva-metrics') return false; + + pendingTvaControlPatch = { ...(pendingTvaControlPatch || {}), ...payload }; + delete pendingTvaControlPatch.type; + + // Partial updates are intentional: only keys present in the payload change. + setTvaMetricFromPayload('complaintsOpen', 'complaintsOpen', payload); + setTvaMetricFromPayload('invoiceActions', 'invoiceActions', payload); + setTvaMetricFromPayload('deliveryPersonLeave', 'deliveryPersonLeave', payload); + setTvaMetricFromPayload('refillSpreadDays', 'refillSpreadDays', payload); + setTvaMetricFromPayload('bookingAgeDays', 'refillSpreadDays', payload); + setTvaMetricFromPayload('bookingSpreadDays', 'refillSpreadDays', payload); + setTvaMetricFromPayload('amberRefillSpreadDays', 'amberRefillSpreadDays', payload); + setTvaMetricFromPayload('criticalRefillSpreadDays', 'criticalRefillSpreadDays', payload); + setTvaMetricFromPayload('doubleRedRefillSpreadDays', 'doubleRedRefillSpreadDays', payload); + setTvaMetricFromPayload('bpclDepositLakhs', 'bpclDepositLakhs', payload); + setTvaMetricFromPayload('bpclDeposit', 'bpclDepositLakhs', payload); + setTvaMetricFromPayload('pendencyDays', 'pendencyDays', payload); + setTvaMetricFromPayload('idealPendencyMaxDays', 'idealPendencyMaxDays', payload); + setTvaMetricFromPayload('criticalPendencyDays', 'criticalPendencyDays', payload); + setTvaPendencyAreasFromPayload(payload); + setTvaRefillSpreadAreasFromPayload(payload); + syncTvaMetricThresholds(); + return true; +} + +function applyTvaMetricUpdatesFromRows(items) { + [...items] + .sort((a, b) => a.sentstamp - b.sentstamp) + .forEach(item => applyTvaMetricUpdate(serverMassage(item.msg, item.extra))); +} + +function isTvaMetricsItem(item) { + return String(serverMassage(item.msg, item.extra).type || '').toLowerCase() === 'tva-metrics'; +} + +function formatTvaMetricValue(index, value) { + if (tvaChartCheckpoints[index] === 'Pendency') return `${tvaMetrics.pendencyDays}d · crit >${tvaMetrics.criticalPendencyDays}d`; + if (tvaChartCheckpoints[index] === 'Invoice Actions') return `${tvaMetrics.invoiceActions} invoices`; + if (tvaChartCheckpoints[index] === 'Complaints Open') return `${tvaMetrics.complaintsOpen} complaints`; + if (tvaChartCheckpoints[index] === 'Delivery Person Leave') return `${tvaMetrics.deliveryPersonLeave} leave`; + if (tvaChartCheckpoints[index] === 'Refill Spread') return `${tvaMetrics.refillSpreadDays}d · red >${tvaMetrics.criticalRefillSpreadDays}d`; + if (tvaChartCheckpoints[index] === 'BPCL Deposit') return `₹${tvaMetrics.bpclDepositLakhs}L`; + return `${value}%`; +} + +function getActionChartMetrics() { + return [ + actionMetricPercent(tvaMetrics.complaintsOpen), + actionMetricPercent(tvaMetrics.invoiceActions), + actionMetricPercent(tvaMetrics.deliveryPersonLeave), + refillSpreadMetricPercent(tvaMetrics.refillSpreadDays, tvaMetrics.criticalRefillSpreadDays, tvaMetrics.doubleRedRefillSpreadDays), + pendencyMetricPercent(tvaMetrics.pendencyDays, tvaMetrics.idealPendencyMaxDays, tvaMetrics.criticalPendencyDays), + tvaMetrics.bpclDepositLakhs + ]; +} + +function getTvaValueZoomBounds(values) { + const finiteValues = values.filter(value => Number.isFinite(value)); + if (!finiteValues.length) return { min: -10, max: 10 }; + + let min = Math.min(0, ...finiteValues); + let max = Math.max(0, ...finiteValues); + if (min === max) { + min -= 10; + max += 10; + } + + const span = max - min; + const padding = Math.max(8, span * 0.24); + return { + min: Math.floor(min - padding), + max: Math.ceil(max + padding) + }; +} + +function getPendencyAreaLabels() { + return tvaMetrics.pendencyAreas.map(area => area.name); +} + +function getPendencyAreaDays() { + return tvaMetrics.pendencyAreas.map(area => area.days); +} + +function getRefillSpreadAreaLabels() { + return tvaMetrics.refillSpreadAreas.map(area => area.name); +} + +function getRefillSpreadAreaDays() { + return tvaMetrics.refillSpreadAreas.map(area => area.days); +} + +window.setTvaControlData = function(data) { + if (typeof data === 'string') data = JSON.parse(data); + applyTvaMetricUpdate({ type: 'tva-metrics', ...(data || {}) }); + updateActionRequiredChart(); +}; + +window.getTvaControlData = function() { + return tvaControl ? tvaControl.getData() : JSON.parse(JSON.stringify(tvaMetrics)); +}; + +function ensureTvaChartControls(canvas) { + const container = canvas.closest('.action-chart-container'); + if (!container || container.querySelector('.tva-chart-controls')) return; + + const controls = document.createElement('div'); + controls.className = 'tva-chart-controls'; + const alertBadge = document.createElement('div'); + alertBadge.className = 'tva-alert-badge'; + alertBadge.hidden = true; + container.prepend(alertBadge); + + controls.innerHTML = ` + <button type="button" class="tva-chart-back" hidden>←</button> + <div class="tva-chart-heading">TVA REACTIVE CHANNEL</div> + <button type="button" class="tva-chart-fullscreen" title="Fullscreen chart" aria-label="Fullscreen chart"> + <span class="tva-fullscreen-icon" aria-hidden="true"></span> + </button> + `; + container.prepend(controls); + + controls.querySelector('.tva-chart-back').addEventListener('click', () => switchTvaChartMode('timeline')); + controls.querySelector('.tva-chart-fullscreen').addEventListener('click', () => toggleTvaChartFullscreen()); +} + +function syncTvaChartControls() { + const canvas = document.getElementById('tvaReactiveChart'); + const container = canvas && canvas.closest('.action-chart-container'); + if (!container) return; + + const backButton = container.querySelector('.tva-chart-back'); + const fullscreenButton = container.querySelector('.tva-chart-fullscreen'); + const alertBadge = container.querySelector('.tva-alert-badge'); + const heading = container.querySelector('.tva-chart-heading'); + if (backButton) backButton.hidden = tvaChartMode === 'timeline'; + if (heading) heading.textContent = tvaChartMode === 'pendency' ? 'PENDENCY AREA SCAN' : tvaChartMode === 'refill-spread' ? 'REFILL SPREAD AREA SCAN' : 'TVA REACTIVE CHANNEL'; + if (fullscreenButton) { + const fullscreen = container.classList.contains('tva-chart-fullscreen-mode'); + fullscreenButton.classList.toggle('is-restore', fullscreen); + fullscreenButton.title = fullscreen ? 'Restore chart' : 'Fullscreen chart'; + fullscreenButton.setAttribute('aria-label', fullscreen ? 'Restore chart' : 'Fullscreen chart'); + } + if (alertBadge) { + const hasDoubleRed = tvaMetricData.some((value, index) => value > tvaDoubleRedUpperThreshold[index]); + const hasCritical = hasDoubleRed || tvaMetricData.some((value, index) => value > tvaUpperThreshold[index] || value < tvaLowerThreshold[index]); + const hasAmber = hasCritical || tvaMetricData.some((value, index) => value > tvaAmberUpperThreshold[index] || value < tvaAmberLowerThreshold[index]); + alertBadge.hidden = !tvaShowAlertBadge || tvaChartMode !== 'timeline' || !hasAmber; + alertBadge.innerHTML = `<span class="tva-alert-icon" aria-hidden="true"></span>${hasDoubleRed ? 'DOUBLE RED' : hasCritical ? 'CRITICAL' : 'AMBER ALERT'}`; + alertBadge.classList.toggle('is-critical', hasCritical && !hasDoubleRed); + alertBadge.classList.toggle('is-double-red', hasDoubleRed); + alertBadge.classList.toggle('is-amber', !hasCritical); + } +} + +function isTvaChartFullscreen() { + const canvas = document.getElementById('tvaReactiveChart'); + const container = canvas && canvas.closest('.action-chart-container'); + return !!(container && container.classList.contains('tva-chart-fullscreen-mode')); +} + +function ensureTvaBlinkInterval() { + if (tvaBlinkIntervalId) return; + tvaBlinkIntervalId = setInterval(() => { + tvaBlinkOn = !tvaBlinkOn; + if (tvaReactiveChart && tvaChartMode === 'timeline') tvaReactiveChart.update('none'); + }, 1100); +} + +function toggleTvaChartFullscreen() { + const canvas = document.getElementById('tvaReactiveChart'); + const container = canvas && canvas.closest('.action-chart-container'); + if (!container) return; + container.classList.toggle('tva-chart-fullscreen-mode'); + syncTvaChartControls(); + if (tvaReactiveChart) { + tvaReactiveChart.resize(); + tvaReactiveChart.update('none'); + } +} + +function switchTvaChartMode(mode) { + if (tvaChartMode === mode) return; + tvaChartMode = mode; + if (tvaReactiveChart) { + tvaReactiveChart.destroy(); + tvaReactiveChart = null; + } + initActionRequiredChart(); + updateActionRequiredChart(); +} + +function getTimelineChartConfig() { + return { + type: 'line', + data: { + labels: tvaChartCheckpoints, + datasets: [ + { + label: 'Red Upper Threshold', + data: tvaUpperThreshold, + borderColor: 'rgba(255, 0, 85, 0.42)', + borderWidth: 2.2, + borderDash: [6, 6], + fill: false, + tension: 0.4, + pointRadius: 0, + hoverRadius: 0 + }, + { + label: 'Red Lower Threshold', + data: tvaLowerThreshold, + borderColor: 'rgba(255, 0, 85, 0.42)', + borderWidth: 2.2, + borderDash: [6, 6], + fill: false, + tension: 0.4, + pointRadius: 0, + hoverRadius: 0 + }, + { + label: 'Amber Upper Threshold', + data: tvaAmberUpperThreshold, + borderColor: 'rgba(255, 204, 0, 0.28)', + borderWidth: 1.45, + borderDash: [3, 5], + fill: false, + tension: 0.4, + pointRadius: 0, + hoverRadius: 0 + }, + { + label: 'Amber Lower Threshold', + data: tvaAmberLowerThreshold, + borderColor: 'rgba(255, 204, 0, 0.28)', + borderWidth: 1.45, + borderDash: [3, 5], + fill: false, + tension: 0.4, + pointRadius: 0, + hoverRadius: 0 + }, + { + label: 'Green Upper Threshold', + data: tvaUpperThreshold.map((value, index) => index === tvaChartCheckpoints.indexOf('BPCL Deposit') ? value : null), + borderColor: 'rgba(0, 255, 120, 0.5)', + borderWidth: 1.8, + borderDash: [4, 4], + spanGaps: false, + fill: false, + tension: 0.4, + pointRadius: 0, + hoverRadius: 0 + }, + { + label: 'Green Soft Threshold', + data: tvaAmberUpperThreshold.map((value, index) => index === tvaChartCheckpoints.indexOf('BPCL Deposit') ? value : null), + borderColor: 'rgba(120, 255, 160, 0.34)', + borderWidth: 1.4, + borderDash: [2, 5], + spanGaps: false, + fill: false, + tension: 0.4, + pointRadius: 0, + hoverRadius: 0 + }, + { + label: 'Timeline Metric', + data: tvaMetricData, + borderWidth: 3.5, + tension: 0.4, + fill: false, + borderColor: '#ff6200', + segment: { + borderColor: context => { + const index = context.p1DataIndex; + const value = tvaMetricData[index]; + return value > tvaDoubleRedUpperThreshold[index] ? '#ff1a1a' : value > tvaUpperThreshold[index] || value < tvaLowerThreshold[index] ? '#ff0055' : '#ff6200'; + } + }, + pointBackgroundColor: context => { + const index = context.dataIndex; + const value = tvaMetricData[index]; + return value > tvaDoubleRedUpperThreshold[index] ? '#ff1a1a' : value > tvaUpperThreshold[index] || value < tvaLowerThreshold[index] ? '#ff0055' : '#ffcc00'; + }, + pointStyle: context => getTvaTrend(context.dataIndex) === 'flat' ? 'circle' : 'triangle', + rotation: context => getTvaTrend(context.dataIndex) === 'down' ? 180 : 0, + pointRadius: context => getTvaTrend(context.dataIndex) === 'flat' ? 4 : 5.5, + pointHoverRadius: 8 + } + ] + }, + options: { + responsive: true, + maintainAspectRatio: false, + layout: { padding: { left: 2, right: 6, top: 8, bottom: 4 } }, + onClick: (event, elements) => { + const activeElement = elements[0]; + if (!activeElement || activeElement.datasetIndex !== tvaMetricDatasetIndex) return; + + const idx = activeElement.index; + const label = tvaChartCheckpoints[idx]; + if (label === 'Pendency') { + switchTvaChartMode('pendency'); + return; + } + if (label === 'Refill Spread') { + switchTvaChartMode('refill-spread'); + return; + } + + const val = tvaMetricData[idx]; + const maxBound = tvaUpperThreshold[idx]; + const minBound = tvaLowerThreshold[idx]; + let status = 'STABLE WITHIN AXIS BOUNDS'; + if (val > maxBound) status = 'CRITICAL OVER-BREACH'; + if (val < minBound) status = 'CRITICAL UNDER-BREACH'; + + alert(`Checkpoint: ${label}\nValue: ${formatTvaMetricValue(idx, val)}\nTolerance Band: ${minBound}% to ${maxBound}%\nStatus: ${status}`); + }, + plugins: { + title: { display: false }, + legend: { display: false }, + tooltip: { + callbacks: { + title: items => items.length ? tvaChartCheckpoints[items[0].dataIndex] : '', + label: context => context.datasetIndex === tvaMetricDatasetIndex ? formatTvaMetricValue(context.dataIndex, context.parsed.y) : null + } + } + }, + scales: { + x: { + offset: false, + border: { display: false }, + grid: { color: '#222' }, + ticks: { + color: '#ffffff', + font: { weight: 'bold', size: 10 }, + callback: (_value, index) => tvaUsePlotIcons && !isTvaChartFullscreen() ? '' : tvaChartCheckpoints[index] + } + }, + y: { + ...getTvaValueZoomBounds(tvaMetricData), + border: { display: false }, + grid: { + color: context => context.tick.value === 0 ? 'rgba(0, 255, 204, 0)' : '#222', + lineWidth: 1 + }, + ticks: { display: false } + } + } + }, + plugins: [reactiveZeroAxisPlugin, reactiveThresholdBlastPlugin, reactivePointLabelsPlugin] + }; +} + +function getAreaBarChartConfig({ labels, days, title, subtitle, tooltipSuffix, amberDays, criticalDays }) { + const maxDays = Math.max((criticalDays || amberDays || 1) + 1, ...days) + 0.5; + + return { + type: 'bar', + data: { + labels, + datasets: [ + { + label: 'Pendency Days', + data: days, + borderWidth: 1.2, + borderRadius: 8, + borderSkipped: false, + backgroundColor: context => { + const value = context.raw || 0; + return value > criticalDays ? 'rgba(255, 0, 85, 0.46)' : value > amberDays ? 'rgba(255, 204, 0, 0.38)' : 'rgba(0, 255, 204, 0.3)'; + }, + borderColor: context => { + const value = context.raw || 0; + return value > criticalDays ? '#ff0055' : value > amberDays ? '#ffcc00' : '#00ffcc'; + } + } + ] + }, + options: { + responsive: true, + maintainAspectRatio: false, + layout: { padding: { left: 12, right: 12, top: 24, bottom: 4 } }, + plugins: { + title: { display: false }, + subtitle: { + display: true, + text: subtitle, + color: '#ffcc00', + font: { size: 10, weight: 'bold' }, + padding: { bottom: 10 } + }, + legend: { display: false }, + tooltip: { + callbacks: { + label: context => `${context.label}: ${context.parsed.y} ${tooltipSuffix}` + } + } + }, + scales: { + x: { + grid: { color: '#242424' }, + ticks: { color: '#ffffff', font: { weight: 'bold', size: 10 } } + }, + y: { + min: 0, + max: maxDays, + grid: { + color: context => context.tick.value === amberDays ? 'rgba(255, 204, 0, 0.55)' : context.tick.value === criticalDays ? 'rgba(255, 0, 85, 0.55)' : '#242424', + lineWidth: context => context.tick.value === amberDays || context.tick.value === criticalDays ? 2 : 1 + }, + ticks: { color: '#aaaaaa', callback: value => `${value}d` } + } + } + } + }; +} + +function getPendencyChartConfig() { + return getAreaBarChartConfig({ + labels: getPendencyAreaLabels(), + days: getPendencyAreaDays(), + title: 'PENDENCY AREA SCAN', + subtitle: `${tvaMetrics.pendencyDays} days overall · amber > ${tvaMetrics.idealPendencyMaxDays}d · critical > ${tvaMetrics.criticalPendencyDays}d`, + tooltipSuffix: 'days pending', + amberDays: tvaMetrics.idealPendencyMaxDays, + criticalDays: tvaMetrics.criticalPendencyDays + }); +} + +function getRefillSpreadChartConfig() { + return getAreaBarChartConfig({ + labels: getRefillSpreadAreaLabels(), + days: getRefillSpreadAreaDays(), + title: 'REFILL SPREAD AREA SCAN', + subtitle: `${tvaMetrics.refillSpreadDays} days overall · amber > ${tvaMetrics.amberRefillSpreadDays}d · critical > ${tvaMetrics.criticalRefillSpreadDays}d`, + tooltipSuffix: 'days open', + amberDays: tvaMetrics.amberRefillSpreadDays, + criticalDays: tvaMetrics.criticalRefillSpreadDays + }); +} + +function applyLogsSettingsToDom() { + document.body.classList.toggle('logs-dark', logsSettings.theme === 'dark'); + document.body.classList.toggle('logs-light', logsSettings.theme === 'light'); + document.querySelectorAll('.action-chart-container, .tva-control-container').forEach(container => { + if (logsSettings.theme === 'auto') container.removeAttribute('data-tva-theme'); + else container.dataset.tvaTheme = logsSettings.theme; + }); + tvaControlConfig.ambientGlow.enabled = logsSettings.ambientGlow !== false; + if (tvaControl && typeof tvaControl.refreshTheme === 'function') tvaControl.refreshTheme(); +} + +function initLogsSettingsDialog() { + const theme = document.getElementById('settings-theme'); + const glow = document.getElementById('settings-ambient-glow'); + if (!theme || !glow) return; + theme.value = logsSettings.theme; + glow.checked = logsSettings.ambientGlow !== false; +} + +window.openLogsSettings = function() { + initLogsSettingsDialog(); + const dialog = document.getElementById('logs-settings-dialog'); + if (dialog) dialog.showModal(); +}; + +window.closeLogsSettings = function() { + const dialog = document.getElementById('logs-settings-dialog'); + if (dialog) dialog.close(); +}; + +window.saveLogsSettings = function() { + const theme = document.getElementById('settings-theme'); + const glow = document.getElementById('settings-ambient-glow'); + logsSettings = { + theme: theme ? theme.value : 'auto', + ambientGlow: glow ? glow.checked : true + }; + persistLogsSettings(); + applyLogsSettingsToDom(); + closeLogsSettings(); +}; + +function initActionRequiredChart() { + const canvas = document.getElementById('tvaReactiveChart'); + if (!canvas || tvaControl || typeof Chart === 'undefined' || typeof createTvaControl !== 'function') return; + + applyLogsSettingsToDom(); + tvaControl = createTvaControl({ canvas, config: tvaControlConfig, data: tvaMetrics }); + tvaReactiveChart = tvaControl; +} + +function updateActionRequiredChart() { + tvaMetricData = getActionChartMetrics(); + if (!tvaControl) initActionRequiredChart(); + if (!tvaControl) return; + if (pendingTvaControlPatch) { + tvaControl.update(pendingTvaControlPatch); + pendingTvaControlPatch = null; + } +} + +// Reads session memory to track alerts across page refreshes +function getSeenLeaksLog() { + try { + const data = sessionStorage.getItem('seen_lpg_leaks'); + return data ? JSON.parse(data) : []; + } catch (e) { + return []; + } +} + +// Commits a triggered alert ID to session memory +function markLeakAsSeen(itemDomId) { + try { + const seenList = getSeenLeaksLog(); + if (!seenList.includes(itemDomId)) { + seenList.push(itemDomId); + sessionStorage.setItem('seen_lpg_leaks', JSON.stringify(seenList)); + } + } catch (e) { + console.error(e); + } +} + +// Web Audio synthesizer tone generator +function playAlarmSound() { + try { + const AudioContext = window.AudioContext || window.webkitAudioContext; + if (!AudioContext) return; + const ctx = new AudioContext(); + [0, 0.25].forEach(delay => { + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.type = 'sine'; + osc.frequency.setValueAtTime(880, ctx.currentTime + delay); + gain.gain.setValueAtTime(0.3, ctx.currentTime + delay); + gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + delay + 0.2); + osc.connect(gain); + gain.connect(ctx.destination); + osc.start(ctx.currentTime + delay); + osc.stop(ctx.currentTime + delay + 0.2); + }); + } catch (e) { + console.warn("Audio Context blocked. Click anywhere on the webpage once to enable sound alerts."); + } +} + +// Bypasses sandbox blockers to show a system banner alert +function triggerDesktopNotification(sender, message, deviceId) { + if (!("Notification" in window)) return; + if (Notification.permission === "granted") { + new Notification("CRITICAL ALERT: LPG Leakage", { + body: `From: ${sender} (${deviceId})\n${message}` + }); + } +} + +function escapeHTML(s, forAttribute) { + if (s === null || s === undefined) return ""; + if (typeof(s) !== "string") return s; + if (!s) return ""; + return s.replace(forAttribute ? /[&<>'"]/g : /[&<>]/g, c => ESC_MAP[c]); +} + +function getDateFromEpoch(ts) { + if (!ts) return undefined; + let date; + if (ts < 10_000_000_000) date = new Date(ts * 1000); + else if (ts < 10_000_000_000_000) date = new Date(ts); + else if (ts < 10_000_000_000_000_000) date = new Date(Math.floor(ts / 1000)); + else return undefined; + + if (config.displayTimestampsAsLocalWallClock) { + return new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000); + } + return date; +} + +// Time-only formatting for message headers now that the day/month lives in the per-date-group badge +function formatTimeOnly(date) { + if (!(date instanceof Date) || isNaN(date)) return ""; + const time = new Intl.DateTimeFormat('en-IN', { + timeZone: 'Asia/Kolkata', + hour: '2-digit', + minute: '2-digit', + hour12: false + }).format(date); + return `<strong>${time}</strong>`; +} + +function getISTDateKey(date) { + if (!(date instanceof Date) || isNaN(date)) return ""; + const parts = new Intl.DateTimeFormat('en-CA', { + timeZone: 'Asia/Kolkata', + year: 'numeric', + month: '2-digit', + day: '2-digit' + }).formatToParts(date); + const getPart = type => parts.find(part => part.type === type).value; + return `${getPart('year')}-${getPart('month')}-${getPart('day')}`; +} + +// Calendar-style day/month markup, matching the #custom-date template +function formatDateBadge(date) { + if (!(date instanceof Date) || isNaN(date)) return ""; + const parts = new Intl.DateTimeFormat('en-US', { + timeZone: 'Asia/Kolkata', + day: 'numeric', + month: 'short' + }).formatToParts(date); + const day = parts.find(part => part.type === 'day').value; + const month = parts.find(part => part.type === 'month').value; + return `<div class="date-p"><p>${day}</p><small>${month}</small><hr></div>`; +} + +// Rebuilds the standalone date-divider <li> elements: one per date group, inserted right before that +// group's first message. As a top-level list item (not nested inside a message row), each divider can +// stick to the top of the list on its own while its date's messages scroll underneath it. Works on any +// message <ul> — both the OTP feed and the action-required feed use it. +function syncDateDividers(list) { + if (!list) return; + list.querySelectorAll("li.date-divider").forEach(el => el.remove()); + + let lastDateKey = null; + list.querySelectorAll("li.msg-list-item").forEach(item => { + const sentDate = getDateFromEpoch(parseInt(item.dataset.timestamp, 10)); + if (!sentDate) return; + const dateKey = getISTDateKey(sentDate); + if (dateKey === lastDateKey) return; + lastDateKey = dateKey; + + const divider = document.createElement("li"); + divider.className = "date-divider"; + divider.innerHTML = formatDateBadge(sentDate); + list.insertBefore(divider, item); + }); +} + +// Native clipboard click handling operation +window.copyToClipboard = function(text, element) { + navigator.clipboard.writeText(text).then(() => { + const originalText = element.innerText; + element.innerText = "Copied!"; + element.style.background = "#d4edda"; + element.style.borderColor = "#c3e6cb"; + setTimeout(() => { + element.innerText = originalText; + element.style.background = "#f0f0f0"; + element.style.borderColor = "#ddd"; + }, 1200); + }).catch(err => console.error(err)); +}; + +function copyableCodeChip(code) { + return `<span class="copyable-code" onclick="copyToClipboard('${code}', this)" style="cursor:pointer; background:#f0f0f0; padding:2px 6px; border-radius:4px; font-weight:bold; display:inline-block; margin-top:4px; border:1px solid #ddd; transition: all 0.2s;">${code}</span>`; +} + +function leakageBanner(keyword) { + return `<div class="leakage-alert">${escapeHTML(keyword, true)} detected</div>`; +} + +// ============================================================================ +// Message templates +// +// serverMassage() is the only place that understands today's raw "gt" msg +// string. It normalizes a message into a JSON object shaped for its specific +// type — an iob-debit only carries amount/merchant, an sms only carries +// otp/leakage when those actually apply — rather than one generic shape with +// fields that don't mean anything for that type. `msg` itself is always kept +// completely raw: every other field is extracted OUT of it, never mutated +// into it, so templates render msg as-is and use the extracted fields for +// any special presentation (chips, banners, etc). Once the server starts +// sending this same JSON directly instead of a plain-text msg, serverMassage() +// is the single spot that needs to change (parse/pass-through instead of +// regex-sniffing); the header and body templates stay untouched. +// ============================================================================ + +function serverMassage(msg, extraRaw) { + if (msg && typeof msg === "object" && msg.type) return msg; + msg = msg || ""; + + // Structured payloads: once the server sends JSON straight in `msg`, each type just carries whatever + // fields it needs (e.g. "dispatch" below) — no regex-sniffing required. + if (typeof msg === "string" && msg.trim().startsWith("{")) { + try { + const parsed = JSON.parse(msg); + if (parsed && typeof parsed === "object" && parsed.type) return parsed; + } catch (e) { /* not valid JSON, fall through to plain-text parsing */ } + } + + const iobDebitMatch = msg.match(/^rs\.([0-9.]*) debited to CC-xxx2081 .* \[(.*)\]/i); + if (iobDebitMatch) { + return { type: "iob-debit", amount: iobDebitMatch[1], merchant: iobDebitMatch[2] || "", msg }; + } + + const iobCreditMatch = msg.match(/^rs\.([0-9.]*) credited to CC-xxx2081 .* \[(.*)\]/i); + if (iobCreditMatch) { + return { type: "iob-credit", amount: iobCreditMatch[1], merchant: iobCreditMatch[2] || "", msg }; + } + + let sim = ""; + try { + const extraJson = extraRaw ? JSON.parse(extraRaw) : null; + if (extraJson && extraJson.sim) sim = extraJson.sim; + } catch (e) { /* extra wasn't valid JSON, ignore */ } + + const data = { type: "sms", msg, sim }; + + const otpMatch = msg.match(/\b\d{6}\b/); + if (otpMatch) data.otp = otpMatch[0]; + + const leakageMatch = msg.match(/(lpg leakage|gas leak|leakage detected)/i); + if (leakageMatch) data.leakage = leakageMatch[0]; + + return data; +} + +// Body markup is fully owned by each message type — nothing outside these templates decides how a body renders. +const messageBodyTemplates = { + "iob-debit": data => `<div> + <details style="display: inline-block; width: 100%;"><summary style="margin-left: 6rem; display: block; color: red;">- Rs. ${escapeHTML(data.amount, true)}</summary>${escapeHTML(data.msg)}</details> + </div>`, + "iob-credit": data => `<div> + <details style="display: inline-block; width: 100%;"><summary style="display: block; color: green;">+ Rs. ${escapeHTML(data.amount, true)}</summary>${escapeHTML(data.msg)}</details> + </div>`, + "sms": data => `${data.leakage ? leakageBanner(data.leakage) : ""}${escapeHTML(data.msg)}${data.otp ? copyableCodeChip(data.otp) : ""}`, + "dispatch": data => `<span class="badge-status">${escapeHTML(data.status, true)}</span> + <div class="cargo-grid"> + ${(data.cargo || []).map(c => `<div class="cargo-item"><span class="kg-badge">${escapeHTML(c.kg, true)}</span> + <span class="qty">${escapeHTML(String(c.qty), true)}</span></div>`).join("")} + </div> + <table> + <tbody> + <tr> + <th>vehicle no</th> + <td>${escapeHTML(data.vehicleNo, true)}</td> + </tr> + <tr> + <th>time</th> + <td>${escapeHTML(data.time, true)}</td> + </tr> + <tr> + <th>invoice no.</th> + <td>${escapeHTML(data.invoiceNo, true)}</td> + </tr> + <tr> + <th>amount</th> + <td>${escapeHTML(data.amount, true)}</td> + </tr> + </tbody> + </table> + <button class="value">Acknowledge Invoice</button>` +}; + +function renderMessageBody(data) { + const template = messageBodyTemplates[data.type] || messageBodyTemplates.sms; + return template(data); +} + +// Only the header needs to reduce each type's custom fields down to one label string. +function getHeaderLabel(data) { + switch (data.type) { + case "iob-debit": + case "iob-credit": + return data.merchant || ""; + case "sms": + return data.sim || ""; + case "dispatch": + return data.vehicleNo || data.invoiceNo || ""; + default: + return ""; + } +} + +// Header structure is the same for every message type — only the injected text (sender, label, time, device) varies. +function renderMessageHeader({ imgType, sender, headerLabel, timeStr, mid, deviceName }) { + const headerPrefixText = headerLabel ? `${headerLabel} | ` : ""; + return `<div class="msg-item-header"> + ${imgType} + <div style="display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px;"> + <span>${sender}</span> + <small style="font-weight: lighter; color: #727272;">${headerPrefixText}${timeStr}</small> + </div> + <button class="device-name-button" popovertarget="device-info-popover" data-mid="${escapeHTML(String(mid), true)}" onfocus="deviceCardUpdate(event)" onclick="deviceCardUpdate(event)" style="flex: 1; text-align: end; font-size: 11px; color:#aaa; font-weight:normal; font-family:monospace;">${deviceName}</button> + </div>`; +} + +function setMessageVisibility(element, visible) { + element.style.setProperty("display", visible ? "flex" : "none", "important"); +} + +// Master visual filter calculation logic for the live event feed. +window.applyFilters = function() { + const selectedDevice = document.getElementById("filter-device").value; + const selectedCategory = document.getElementById("filter-category").value; + const searchQuery = document.getElementById("filter-search").value.toLowerCase(); + + document.querySelectorAll("#data-list .msg-list-item").forEach(element => { + const matchesDevice = !selectedDevice || element.dataset.device === selectedDevice; + const matchesCategory = !selectedCategory || element.dataset.category === selectedCategory; + const matchesSearch = !searchQuery || element.innerText.toLowerCase().includes(searchQuery); + setMessageVisibility(element, matchesDevice && matchesCategory && matchesSearch); + }); +}; + +// Search-only filter for the action-required panel. +window.applyActionFilters = function() { + const searchInput = document.getElementById("action-filter-search"); + const searchQuery = searchInput ? searchInput.value.toLowerCase() : ""; + + document.querySelectorAll("#action-list .msg-list-item").forEach(element => { + const matchesSearch = !searchQuery || element.innerText.toLowerCase().includes(searchQuery); + setMessageVisibility(element, matchesSearch); + }); +}; + +window.showMobileSegment = function(segmentNumber) { + document.querySelectorAll(".segment").forEach(segment => { + segment.classList.toggle("active", segment.dataset.segment === String(segmentNumber)); + }); + + document.querySelectorAll(".mobile-panel-switch button").forEach(button => { + const isActive = button.dataset.targetSegment === String(segmentNumber); + button.classList.toggle("active", isActive); + button.setAttribute("aria-pressed", isActive ? "true" : "false"); + }); +}; + +function epochSecondsFromLocalInput(value) { + if (!value) return null; + const match = String(value).match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/); + if (!match) return null; + const [, year, month, day, hour, minute] = match.map(Number); + // datetime-local has no timezone. Treat the control value as IST. + return Math.floor(Date.UTC(year, month - 1, day, hour - 5, minute - 30, 0, 0) / 1000); +} + + +// 1. Updated helper function that explicitly forces Asia/Kolkata timezone +function formatDateTimeLocalIST(date) { + const options = { + timeZone: 'Asia/Kolkata', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + hour12: false // Ensures 24-hour format + }; + + // This formats the date into an array of parts based on IST rules + const formatter = new Intl.DateTimeFormat('en-US', options); + const parts = formatter.formatToParts(date); + + // Extract the parts to construct the exact YYYY-MM-DDTHH:mm string + const getPart = type => parts.find(p => p.type === type).value; + + return `${getPart('year')}-${getPart('month')}-${getPart('day')}T${getPart('hour')}:${getPart('minute')}`; +} + +function initRangeFields(force = false) { + const fromInput = document.getElementById("range-from"); + const toInput = document.getElementById("range-to"); + if (!fromInput || !toInput) return; + + const now = new Date(); + + if (force || !rangeFieldsInitialized || !fromInput.value) { + const fromDate = new Date(now.getTime() - (config.defaultRangeHours * 60 * 60 * 1000)); + fromInput.value = formatDateTimeLocalIST(fromDate); + rangeFieldsInitialized = true; + } + toInput.value = formatDateTimeLocalIST(now); +} + + + +function getRangeParams() { + initRangeFields(); + const fromInput = document.getElementById("range-from"); + const toInput = document.getElementById("range-to"); + const params = {}; + const fromTimestamp = epochSecondsFromLocalInput(fromInput && fromInput.value); + const toTimestamp = epochSecondsFromLocalInput(toInput && toInput.value); + + if (fromTimestamp) { + // kidang currently names the lower-bound query parameter `sentstamp`. + // Use the same Unix epoch seconds that the sender/receiver exchange; any + // PostgreSQL internal epoch offset stays hidden inside the database layer. + params.sentstamp = fromTimestamp; + // Keep explicit range aliases too, so the UI remains forward-compatible if + // the backend grows true from/to query names later. + params.fromTimestamp = fromTimestamp; + } + if (toTimestamp) params.toTimestamp = toTimestamp; + return params; +} + +window.refreshRangeFeeds = function() { + initRangeFields(); + fetchUpdates(); + fetchActionUpdates(); +}; + +function updateDeviceDropdown(mId) { + if (!mId || trackedDevices.has(String(mId))) return; + trackedDevices.add(String(mId)); + const dropdown = document.getElementById("filter-device"); + if (!dropdown) return; + const option = document.createElement("option"); + option.value = String(mId); + option.textContent = getDeviceNameFromId(mId) || fallbackDeviceName(mId); + dropdown.appendChild(option); +} + +// Automatically populates dropdown choices based on data stream records +function updateCategoryDropdown(category) { + if (!category || trackedCategories.has(category)) return; + trackedCategories.add(category); + const dropdown = document.getElementById("filter-category"); + if (!dropdown) return; + + const option = document.createElement("option"); + option.value = category; + + if (category === 'otp' || category === 'sms') { + option.textContent = `${category.toUpperCase()} Only`; + } else { + option.textContent = category.charAt(0).toUpperCase() + category.slice(1); + } + dropdown.appendChild(option); +} + +function fallbackDeviceName(mid) { + return mid ? `Device ${mid}` : "unknown"; +} + +function getDeviceNameFromId(mid) { + const cached = deviceMapCache[mid]; + if (cached && typeof cached === "object" && cached.name) return cached.name; + fetchDeviceDetails(mid).then(device => updateDeviceReferences(mid, device)); + return fallbackDeviceName(mid); +} + +function cssEscape(value) { + if (window.CSS && CSS.escape) return CSS.escape(value); + return value.replace(/[^a-zA-Z0-9_-]/g, "\\$&"); +} + +function updateDeviceReferences(mid, device) { + if (!mid || !device || !device.name) return; + document.querySelectorAll(`.device-name-button[data-mid="${cssEscape(String(mid))}"]`).forEach(button => { + button.textContent = device.name; + const item = button.closest(".msg-list-item"); + if (item) item.dataset.device = String(mid); + }); + const option = document.querySelector(`#filter-device option[value="${cssEscape(String(mid))}"]`); + if (option) option.textContent = device.name; +} + +function getCategoryNameFromId(cid) { + // TODO Get from kidang and cache + let deviceIdMap = { + "1": "sms", + "2": "econnect", + "3": "paytm", + "4": "tampermonkey", + "5": "printer" + }; + return deviceIdMap[cid + ""]; +} + +function getDeterministicColor(str) { + let hash = 0; + for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash); + return `hsl(${Math.abs(hash) % 360}, 65%, 42%)`; +} + +function insertInOrder(parent, newChild, newTimestamp) { + const children = parent.querySelectorAll("li.msg-list-item"); + for (let i = 0; i < children.length; i++) { + const currentTimestamp = parseInt(children[i].dataset.timestamp, 10); + if (newTimestamp > currentTimestamp) { + parent.insertBefore(newChild, children[i]); + return; + } + } + parent.appendChild(newChild); +} + +function isActionRequiredItem(item) { + const sender = String(item.sndr || "").toLowerCase(); + const msg = String(item.msg || "").toLowerCase(); + const category = getCategoryNameFromId(item.cid) || ""; + return sender === "complaints" || category === "econnect" && /\b(urgent|emergency|complain|complaint|leak)/i.test(msg); +} + +function removeDeadItems(parent, freshData) { + const freshIds = freshData.map(item => `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, '_')); + parent.querySelectorAll('li[id^="msg-"]').forEach(item => { + if (!freshIds.includes(item.id)) item.remove(); + }); +} + +// Builds one <li class="msg-list-item"> from a raw item ({ sndr, sentstamp, mid, cid, msg, extra }), +// using serverMassage() + the header/body templates above. Shared by the live OTP feed and any other +// message list (e.g. the sample action-required item below) so both render through the same templates. +function createMessageListItem(item) { + const sentDate = getDateFromEpoch(item.sentstamp); + if (!sentDate) return null; + + const dName = getDeviceNameFromId(item.mid) || fallbackDeviceName(item.mid); + const cId = getCategoryNameFromId(item.cid) || "unknown"; + const messageData = serverMassage(item.msg, item.extra); + + const listItem = document.createElement("li"); + listItem.id = `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, '_'); + listItem.className = "msg-list-item"; + listItem.dataset.device = String(item.mid || "unknown"); + listItem.dataset.category = cId; + listItem.dataset.timestamp = item.sentstamp; + + listItem.style.display = "flex"; + listItem.style.alignItems = "flex-start"; + listItem.style.padding = "10px 12px"; + listItem.style.borderBottom = "1px solid #f2f2f2"; + + if (messageData.leakage) { + listItem.style.background = "#fff5f5"; + listItem.style.borderLeft = "4px solid #dc3545"; + } + + const iconColor = getDeterministicColor(item.sndr || 'Unknown'); + + let imgType = ""; + if (cId === "sms") { + imgType=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${iconColor}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"> + <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path> + </svg>`; + } else if (cId === "tampermonkey") { + imgType = '<img src="/assets/tampermonkey.svg">'; + } else if (cId === "printer") { + imgType = '<img src="/assets/printer.svg">'; + } else { + imgType = '<img style="height: 16px; width: 16px;" src="/assets/logs/cid-2-16x.png">'; + } + + listItem.innerHTML = ` + <div style="flex-grow: 1; min-width: 0; display: flex; flex-direction: column;"> + ${renderMessageHeader({ + imgType, + sender: escapeHTML(item.sndr, true), + headerLabel: escapeHTML(getHeaderLabel(messageData), true), + timeStr: formatTimeOnly(sentDate), + mid: item.mid, + deviceName: escapeHTML(dName, true) + })} + + <!-- Body markup is fully owned by the message type template --> + <div class="logs-message"> + ${renderMessageBody(messageData)} + </div> + </div> + `; + return listItem; +} + +function parseFeedResponse(textData) { + const trimmed = textData.trim(); + if (!trimmed) return []; + if (trimmed.startsWith("[") || trimmed.startsWith("{")) { + try { + const parsed = JSON.parse(trimmed); + if (Array.isArray(parsed)) return parsed; + if (Array.isArray(parsed.rows)) return parsed.rows; + if (Array.isArray(parsed.data)) return parsed.data; + return [parsed]; + } catch (e) { + // kidang's GT format can also start with "{"/"[" but is not JSON. + // Fall through to the legacy GT parser instead of breaking the live feed. + } + } + const parsed = parseGT(textData); + return Array.isArray(parsed) ? parsed : [parsed]; +} + +async function fetchTable(tableName, queryParams = {}) { + const params = new URLSearchParams({ table: tableName }); + Object.entries(queryParams).forEach(([key, value]) => { + if (value !== null && value !== undefined && value !== "") params.set(key, value); + }); + + const response = await fetch(`${config.endpoint}?${params.toString()}`); + if (!response.ok) throw new Error(`${tableName} fetch failed: ${response.status}`); + return parseFeedResponse(await response.text()); +} + +async function fetchUpdates() { + try { + const rangeParams = getRangeParams(); + const data = await fetchTable(config.otpTable, rangeParams); + const list = document.getElementById("data-list"); + const toTimestampMs = rangeParams.toTimestamp ? rangeParams.toTimestamp * 1000 : null; + const rangedData = toTimestampMs ? data.filter(item => item.sentstamp <= toTimestampMs) : data; + + rangedData.sort((a, b) => b.sentstamp - a.sentstamp); + applyTvaMetricUpdatesFromRows(rangedData); + + const historySeenAlerts = getSeenLeaksLog(); + const eventData = []; + const actionData = []; + + rangedData.forEach(item => { + if (isTvaMetricsItem(item)) return; + + const cId = getCategoryNameFromId(item.cid) || "unknown"; + + updateDeviceDropdown(item.mid); + updateCategoryDropdown(cId); + + const isActionRequired = isActionRequiredItem(item); + const targetList = isActionRequired ? document.getElementById("action-list") : list; + if (isActionRequired) actionData.push(item); + else eventData.push(item); + + const itemDomId = `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, '_'); + if (targetList && targetList.querySelector(`#${cssEscape(itemDomId)}`)) return; + + const messageData = serverMassage(item.msg, item.extra); + + // Fires sound and alert banners only if it hasn't popped during this browser session + if (messageData.leakage && !historySeenAlerts.includes(itemDomId)) { + markLeakAsSeen(itemDomId); + historySeenAlerts.push(itemDomId); + // FIXME Enable later + playAlarmSound(); + triggerDesktopNotification(item.sndr, item.msg, item.mid); + } + + const listItem = createMessageListItem(item); + if (targetList && listItem) insertInOrder(targetList, listItem, item.sentstamp); + }); + removeDeadItems(list, eventData); + const actionList = document.getElementById("action-list"); + if (actionList) { + removeDeadItems(actionList, actionData); + updateActionRequiredChart(actionData); + applyActionFilters(); + syncDateDividers(actionList); + } + applyFilters(); + syncDateDividers(list); + } catch (error) { + console.error("Error fetching updates:", error); + } +} + +async function fetchActionUpdates() { + const list = document.getElementById("action-list"); + if (!list || !config.actionTable) return; + + try { + const rangeParams = getRangeParams(); + const data = await fetchTable(config.actionTable, rangeParams); + const toTimestampMs = rangeParams.toTimestamp ? rangeParams.toTimestamp * 1000 : null; + const rangedData = toTimestampMs ? data.filter(item => item.sentstamp <= toTimestampMs) : data; + + rangedData.sort((a, b) => b.sentstamp - a.sentstamp); + applyTvaMetricUpdatesFromRows(rangedData); + + rangedData.forEach(item => { + if (isTvaMetricsItem(item)) return; + const itemDomId = `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, '_'); + if (document.getElementById(itemDomId)) return; + + const listItem = createMessageListItem(item); + if (listItem) insertInOrder(list, listItem, item.sentstamp); + }); + + removeDeadItems(list, rangedData); + updateActionRequiredChart(rangedData); + applyActionFilters(); + syncDateDividers(list); + } catch (error) { + // Some deployments do not have the action-required table yet. Stop polling + // after the first server-side failure so the normal OTP feed stays quiet. + if (String(error.message || "").match(/\b(404|500)\b/)) { + console.warn("Action-required feed unavailable; stopping action polling.", error); + config.actionTable = null; + if (actionFetchIntervalId) clearInterval(actionFetchIntervalId); + return; + } + console.error("Error fetching action-required updates:", error); + } +} + +function $(id) { return document.getElementById(id); } + +let deviceMapCache = {}; + +function fetchDeviceDetails(id) { + if (!id) return Promise.resolve(null); + const key = String(id); + const cached = deviceMapCache[key]; + if (cached && typeof cached.then === "function") return cached; + if (cached && typeof cached === "object") return Promise.resolve(cached); + + const promise = fetch('/logs.php?id=' + encodeURIComponent(key)) + .then(async r => { + let device = null; + try { + device = await r.json(); + } catch (error) { + throw new Error(`Device lookup returned invalid JSON: ${r.status}`); + } + if (!r.ok) throw new Error(device && device.error ? device.error : `Device lookup failed: ${r.status}`); + if (!device || !device.name) throw new Error('Device lookup response missing name'); + return device; + }) + .then(device => { + deviceMapCache[key] = device; + updateDeviceReferences(key, device); + return device; + }) + .catch(error => { + console.warn("Device lookup failed", key, error); + delete deviceMapCache[key]; + return null; + }); + deviceMapCache[key] = promise; + return promise; +} + +function updateDeviceCard(device) { + device = device || {}; + $('p-name').parentNode.style.borderColor = device.category_color || "gray"; + $('p-name').parentNode.style.borderWidth = '1px'; + $('p-name').parentNode.style.borderStyle = 'solid'; + $('p-name').textContent = device.name || "Loading device…"; + $('p-assigned-to').textContent = device.assigned_to || ""; + $('p-image').src = device.image || ''; + $('p-notes').textContent = device.notes || ""; + $('p-serial').textContent = device.serial || ""; +} + +function placeDevicePopoverNear(el) { + const popover = document.getElementById("device-info-popover"); + if (!popover || !el) return; + const rect = el.getBoundingClientRect(); + popover.style.position = "fixed"; + popover.style.left = `${Math.min(rect.left, window.innerWidth - 320)}px`; + popover.style.top = `${Math.min(rect.bottom + 6, window.innerHeight - 180)}px`; + popover.style.inset = "auto"; +} + +function deviceCardUpdate(ev) { + const el = ev.target; + const id = el.dataset.mid; + placeDevicePopoverNear(el); + updateDeviceCard({ name: fallbackDeviceName(id) }); + if (!id) return; + fetchDeviceDetails(id).then(device => { + if (device) updateDeviceCard(device); + placeDevicePopoverNear(el); + }); +} + +// parent.querySelectorAll('li[id^="msg-"]').forEach(item => {if (!freshIds.includes(item.id)) item.remove();});}if ("Notification" in window && Notification.permission !== "granted" && Notification.permission !== "denied") {Notification.requestPermission();}var fetchIntervalId = setInterval(fetchUpdates, 2000); + +fetchIntervalId = setInterval(fetchUpdates, 3000); +let actionFetchIntervalId = null; +//document.addEventListener("visibilitychange", () => { +// clearInterval(fetchIntervalId); +// if (!document.hidden) { +// fetchUpdates(); +// } +//}); + +fetchUpdates(); + +// logs.js runs before <ul id="action-list"> exists in the DOM (script tag comes before .content), +// so action-required polling starts after the parser has created that panel. +document.addEventListener("DOMContentLoaded", () => { + initLogsSettingsDialog(); + applyLogsSettingsToDom(); + initRangeFields(); + initActionRequiredChart(); + fetchUpdates(); + fetchActionUpdates(); + actionFetchIntervalId = setInterval(fetchActionUpdates, 3000); +});
diff --git a/logs.php b/logs.php @@ -0,0 +1,70 @@ +<?php +require_once(__DIR__ . '/.env.php'); +require_once(__DIR__ . '/vendor/autoload.php'); + +header('Content-Type: application/json; charset=utf-8'); + +function respond_json($payload, $status = 200) { + http_response_code($status); + echo json_encode($payload); + exit; +} + +function value_or_null($value, $path) { + foreach ($path as $key) { + if (is_object($value) && isset($value->{$key})) { + $value = $value->{$key}; + } else { + return null; + } + } + return $value; +} + +$id = isset($_GET['id']) ? trim((string) $_GET['id']) : ''; +if ($id === '' || !preg_match('/^[A-Za-z0-9_.-]+$/', $id)) { + respond_json(['error' => 'Invalid device id'], 400); +} + +$client = new \GuzzleHttp\Client([ + 'timeout' => 5, + 'connect_timeout' => 3, + 'headers' => [ + 'Authorization' => 'Bearer '.$accessToken, + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + 'User-Agent' => 'Integration Script' + ] +]); + +try { + $url = 'https://equipment.saikrupagas.com/api/v1/hardware/bytag/'.rawurlencode($id); + $response = $client->request('GET', $url); + $obj = json_decode((string) $response->getBody()); + + if (!$obj || !is_object($obj)) { + respond_json(['error' => 'Invalid device lookup response'], 502); + } + + $device = new stdClass(); + // Prefer the asset's own display name, then the model name, then leave null + // so the frontend keeps its "Device <id>" fallback. + $device->name = value_or_null($obj, ['name']) ?: value_or_null($obj, ['model', 'name']); + $device->serial = value_or_null($obj, ['serial']); + $device->assigned_to = value_or_null($obj, ['assigned_to', 'name']); + $device->image = value_or_null($obj, ['image']); + $device->category_color = value_or_null($obj, ['category', 'tag_color']); + $device->notes = value_or_null($obj, ['notes']); + + if (!$device->name) { + respond_json(['error' => 'Device name not found'], 404); + } + + echo json_encode($device); +} catch (\GuzzleHttp\Exception\ClientException $e) { + respond_json(['error' => 'Device not found'], $e->getResponse() ? $e->getResponse()->getStatusCode() : 404); +} catch (Throwable $e) { + error_log('Device lookup failed for asset tag '.$id.': '.$e->getMessage()); + respond_json(['error' => 'Device lookup failed'], 502); +} +?>
diff --git a/message.png b/message.png Binary files differ.
diff --git a/style.css b/style.css @@ -0,0 +1,2499 @@ +/* Fonts now loaded via Google Fonts CDN */ + +:root { + --primary-font: "Instrument Sans", -apple-system, BlinkMacSystemFont, + "Segoe UI", Roboto, sans-serif; + --radius: 16px; +} + +html { + scroll-behavior: smooth; + font-display: swap; + font-family: var(--primary-font); +} + +/* Base styles - same font everywhere; icon fonts override below */ +*, +*::before, +*::after { + font-family: var(--primary-font); +} + +body { + font-family: var(--primary-font); + font-size: 0.96em; + overflow-x: hidden; +} + +/* Prevent all images from skewing/distorting */ +img { + max-width: 100%; + height: auto; +} + +/* Logo specific styling to prevent distortion */ +.logo { + object-fit: contain; +} + +/* Material Icons (legacy) */ +.material-icons { + font-family: "Material Icons" !important; +} + +/* Material Symbols Outlined */ +.material-symbols-outlined { + font-family: "Material Symbols Outlined"; + font-weight: normal; + font-style: normal; + font-size: 24px; + line-height: 1; + letter-spacing: normal; + text-transform: none; + display: inline-block; + white-space: nowrap; + word-wrap: normal; + direction: ltr; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-rendering: optimizeLegibility; + font-variation-settings: "FILL" 0, "wght" 400, "GRAD" 0, "opsz" 24; +} + +.contact-body { + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-content: space-between; + align-items: center; + justify-content: center; +} + +.location-grid { + text-align: center; + margin: 0 auto; + columns: 3; +} + +.location-grid > * { + text-align: center; + border-radius: var(--radius); + padding: 8px; + background-color: #f4f4f4; +} + +hr { + height: 1px; +} + +.header { + position: fixed; + top: 0; + left: 0; + right: 0; + height: 80px; + background-color: transparent; + z-index: 1000; + padding: 16px 8em; + transition: background-color 200ms ease, transform 300ms cubic-bezier(0.23, 1, 0.32, 1); + animation: navBlurFadeIn 600ms cubic-bezier(0.23, 1, 0.32, 1) forwards; +} + +@keyframes navBlurFadeIn { + 0% { + opacity: 0; + filter: blur(4px); + } + 100% { + opacity: 1; + filter: blur(0); + } +} + +.header-container { + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; +} + +.left-section { + display: flex; + align-items: flex-start; +} + +.logo-nav-group { + display: flex; + align-items: center; + gap: 48px; + animation: navBlurFadeIn 600ms cubic-bezier(0.23, 1, 0.32, 1) forwards; +} + +.logo { + height: 48px; + width: auto; +} + +.nav-section { + display: flex; + align-items: center; + animation: navBlurFadeIn 600ms cubic-bezier(0.23, 1, 0.32, 1) 100ms forwards; +} + +.nav-pills { + display: flex; + gap: 16px; + align-items: center; + background: rgba(255, 255, 255, 0.8); + backdrop-filter: blur(8px); + padding: 0 4px; + height: 40px; + border-radius: 100px; + border: 1px solid rgba(0, 0, 0, 0.08); +} + +.nav-pill { + font-size: 16px; + font-weight: 500; + color: #000; + text-decoration: none; + padding: 0 16px; + height: 32px; + display: flex; + align-items: center; + border-radius: 100px; + transition: background-color 150ms ease, color 150ms ease; +} + +@media (hover: hover) and (pointer: fine) { + .nav-pill:hover { + background: rgba(255, 255, 255, 0.95); + color: #000; + } +} + +/* Add support for Safari */ +@supports (-webkit-backdrop-filter: none) { + .nav-pills { + -webkit-backdrop-filter: blur(8px); + } +} + +.book-now-btn { + background: #1d80c3; + color: white; + border: none; + padding: 0 16px; + height: 40px; + display: flex; + align-items: center; + border-radius: 100px; + cursor: pointer; + transition: background-color 150ms ease, transform 200ms ease-out, box-shadow 200ms ease-out; + font-weight: 600; +} + +@media (hover: hover) and (pointer: fine) { + .book-now-btn:hover { + background: #1557b0; + transform: translateY(-1px); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + color: white; + } +} + +.book-now.loading { + background: #ccc; + cursor: not-allowed; + opacity: 0.7; +} + +:focus { + outline: 2px solid #1d80c3; + outline-offset: 2px; +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation: none; + transition: none; + scroll-behavior: auto; + } + + .awards-ticker { + animation: none; + } + + .hero-text, + .hero-text > *, + .hero-image-animate, + .header, + .logo-nav-group, + .nav-section { + animation: none; + opacity: 1; + } + + .skeleton { + animation: none; + } +} + +.hamburger { + display: none; + cursor: pointer; + font-size: 24px; +} + +.defaultMargin { + padding: 64px 32px; + margin-bottom: 0; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; +} + +/* Section container styles */ +.section-container { + width: 100%; + max-width: 1200px; + margin: 0 auto; +} + +h1 { + font-size: 36px !important; + font-weight: 700 !important; + color: #0c334e !important; +} + +h2 { + font-size: 28px !important; + font-weight: 600 !important; + color: #0c334e !important; +} + +h3 { + font-size: 22px !important; + font-weight: 500 !important; + color: rgba(0, 0, 0, 0.8) !important; +} + +h4 { + font-size: 20px; + font-weight: 500; + color: rgba(0, 0, 0, 0.8); +} + +h5 { + font-size: 17px; + font-weight: 500; + color: rgba(0, 0, 0, 0.8); +} + +code, +pre { + line-height: 1; + font: 1em monospace; + font-weight: 500; +} + +a { + color: rgba(0, 0, 0, 0.6); + text-decoration: none; + font-weight: 600; + transition: color 150ms ease; +} + +@media (hover: hover) and (pointer: fine) { + a:hover { + color: #1d80c3; + text-decoration: none; + } +} + +a:active { + color: #000000; +} + +.book-now-btn:active, +.CTA:active, +.submit-btn:active, +.emergency-button:active { + transform: scale(0.97); +} + +.btnCard:active { + transform: scale(0.98); +} + +table { + border: 1px solid #ddd; + border-radius: 8px; +} + +table thead th { + border-bottom: 1px solid #ddd; + font-style: normal; + background: #f8f8f8; +} + +tr { + border-bottom: 1px solid #ddd; +} + +td { + padding: 0.62em; +} + +.hero-section { + min-height: 100vh; + background-image: url(/assets/herobackground.png); + background-size: cover; + background-repeat: no-repeat; + background-position: center; + display: flex; + align-items: center; + padding: 120px 2rem; +} + +.hero-content { + max-width: 1400px; + margin: 0 auto; + width: 100%; + display: flex; + align-items: center; +} + +.hero-text { + flex: 1; + padding-right: 4rem; + animation: blurFadeIn 0.7s ease-in-out forwards; +} + +.hero-title { + margin: 1.5rem 0; +} + +.hero-title h1 { + font-size: 48px; + line-height: 1.2; + margin-bottom: 0.5rem; + font-weight: 500; + font-family: var(--primary-font); + letter-spacing: -0.02em; +} + +.hero-description { + font-size: 18px; + line-height: 1.6; + margin-bottom: 2rem; + max-width: 600px; + font-weight: 400; + color: rgba(0, 0, 0, 0.8); + letter-spacing: -0.01em; +} + +.app-buttons { + display: flex; + gap: 24px; +} + +.app-buttons img { + width: 120px !important; + height: auto; + object-fit: contain; +} + +.hero-image { + flex: 1; + display: flex; + justify-content: center; + align-items: center; + padding-left: 2rem; +} + +.hero-image-grid { + display: grid; + grid-template-columns: 1fr 1fr; + grid-template-rows: 1fr 1fr; + gap: 1rem; + width: 100%; + max-width: 500px; + position: relative; + perspective: 1000px; +} + +.hero-img-1 { + grid-column: 1 / 2; + grid-row: 1 / 3; + height: 100%; + object-fit: cover; + border-radius: 24px; +} + +.hero-img-2 { + grid-column: 2 / 3; + grid-row: 1 / 2; + width: 100%; + object-fit: cover; + border-radius: 24px; +} + +.hero-img-3 { + grid-column: 2 / 3; + grid-row: 2 / 3; + width: 100%; + object-fit: cover; + border-radius: 24px; +} + +.hero-image-grid img { + max-width: 100%; + height: auto; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1), box-shadow 200ms cubic-bezier(0.23, 1, 0.32, 1); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), + 0 2px 4px -1px rgba(0, 0, 0, 0.06); + transform: translateZ(0); + will-change: transform; +} + +@media (hover: hover) and (pointer: fine) { + .hero-image-grid img.hover { + transform: scale(1.02); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), + 0 4px 6px -2px rgba(0, 0, 0, 0.05); + } +} + +.customLink { + scroll-behavior: smooth; +} + +.CTA { + border-radius: 100px; + color: #1d80c3; + font-weight: 600; + border: none; + background: rgba(29, 128, 195, 0.14); + display: inline-flex; + padding: 8px 24px; + justify-content: center; + align-items: center; + gap: 10px; + transition: background-color 150ms ease, color 150ms ease; +} + +@media (hover: hover) and (pointer: fine) { + .CTA:hover { + background-color: #1d80c3; + color: rgba(255, 255, 255, 1); + } +} + +.caption { + font-size: 15px; + color: rgba(0, 0, 0, 0.6); +} + +.contact-section { + display: flex; + justify-content: center; + align-items: center; +} + +.contact-info { + flex: 1; + margin-right: 20px; +} + +.contact-card { + padding: 24px; + border-radius: 10px; + margin-bottom: 10px; +} + +.contact-card p, +.contact-card h3 { + margin: 0; + font-weight: 600; +} + +.contact-map { + flex: 1; + border: none; + border-radius: 12px; +} + +.collapsible-header { + cursor: pointer; + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid #e0e0e0; + padding: 20px 0; +} + +.collapsible-content { + padding: 20px 0; +} + +.footer { + background-color: #f8f8f8; + padding: 2em 2em 6em 2em; + display: flex; + justify-content: space-between; + align-items: center; + border-top: 1px solid #e0e0e0; +} + +.footer h3 { + text-align: center; +} + +.carousel-container { + display: flex; + overflow-x: scroll; + scroll-snap-type: x mandatory; + -webkit-overflow-scrolling: touch; +} + +.carousel-item { + flex: 0 0 auto; + scroll-snap-align: start; + margin-right: 10px; + border-radius: 10px; + overflow: visible; +} + +.carousel-item img { + display: block; + width: 100%; + height: auto; +} + +.emergency-cta { + position: fixed; + bottom: 32px; + right: 32px; + z-index: 100; +} + +.emergency-button { + display: flex; + align-items: center; + gap: 12px; + background: white; + border: 1px solid rgba(220, 38, 38, 0.2); + padding: 12px 24px; + border-radius: 24px; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), + 0 2px 4px -1px rgba(0, 0, 0, 0.06); + transition: transform 200ms ease-out, box-shadow 200ms ease-out; +} + +@media (hover: hover) and (pointer: fine) { + .emergency-button:hover { + background: white; + transform: translateY(-1px); + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05); + } +} + +.emergency-icon { + font-size: 24px !important; + color: #dc2626; +} + +.emergency-text { + display: flex; + flex-direction: column; + gap: 2px; +} + +.emergency-text p { + font-size: 12px; + color: #4b5563; + margin: 0; +} + +.emergency-text h3 { + font-size: 16px !important; + color: #dc2626 !important; + margin: 0; +} + +.emergency-label { + font-size: 15px; + font-weight: 400; + color: rgba(0, 0, 0, 0.6); +} + +.emergency-number { + font-size: 22px; + font-weight: 500; + color: rgba(0, 0, 0, 0.8); +} + +.card, +.btnCard { + border: none; + display: flex; + padding: 24px 36px; + flex-direction: column; + align-items: flex-start; + gap: 24px; + width: 100%; + max-width: 500px; + height: 100%; + justify-content: center; + background: #fafafa; + border-radius: 8px; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1), box-shadow 200ms cubic-bezier(0.23, 1, 0.32, 1), background-color 200ms ease; +} + +.bigP { + font-size: 15px; + font-weight: 400; + color: rgba(0, 0, 0, 0.6); +} + +.direction { + display: flex; + flex-direction: row; + gap: 32px; + width: 100%; + justify-content: center; +} + +@media (hover: hover) and (pointer: fine) { + .btnCard:hover { + background: #1d80c3 !important; + color: #fff !important; + } +} + +.brand1 { + background-color: #1d80c3; +} + +.brand2 { + background-color: rgba(248, 226, 18, 0.14); +} + +/* Tablet breakpoint - prevent navbar text wrapping */ +@media (max-width: 1024px) and (min-width: 769px) { + .header { + padding: 16px 4em; + } + + .nav-pill { + padding: 0 12px; + white-space: nowrap; + } + + .book-now-btn { + padding: 0 12px; + white-space: nowrap; + } + + .logo-nav-group { + gap: 32px; + } +} + +/* Mobile styles */ +@media (max-width: 768px) { + .defaultMargin { + padding: 48px 24px; + } + + .direction { + flex-direction: column; + gap: 24px; + } + + .reverse { + flex-direction: column-reverse; + } + + .hero-section { + height: auto; + min-height: 100vh; + padding: 100px 1rem 60px; + } + + .desktop-menu { + display: none; + } + + .mobile-menu { + display: none; + } + + .mobile-menu.active { + display: block; + } + + .hamburger { + display: block; + color: #000; + } + + .nav-actions .book-now { + display: none; + } + + .cards-container { + gap: 24px; + } + + .btnCard, + .card { + width: 100%; + height: 100%; + max-width: 100%; + margin: 0 auto; + min-width: unset; + } + + #services .btnCard { + width: 100%; + } + + .hero-text { + padding-right: 0; + width: 100%; + } + + .hero-image { + padding-left: 0; + width: 100%; + } + + .hero-image-grid { + max-width: 400px; + gap: 0.5rem; + margin: 0 auto; + } + + .hero-title h1 { + font-size: 36px; + } + + .app-buttons { + justify-content: center; + } + + .app-buttons img { + width: 120px !important; + height: auto; + } + + .flex-col { + flex-direction: column; + text-align: center; + padding: 1rem 0; + gap: 3rem; + } + + .nav-links { + display: none; + } + + .header { + padding: 16px 2em; + } + + .nav-pills { + background: rgba(245, 245, 245, 0.9); + } + + section { + margin-bottom: 64px; + } + + /* Contact section mobile styles */ + .contact-card { + width: 100%; + } + + .contact-card-content { + width: 100%; + } + + .contact-link { + width: 100%; + justify-content: space-between; + } + + #Contact .section-container { + width: 100%; + } + + #Contact .direction { + width: 100%; + } +} + +/* Modal styles */ +.modal { + display: none; + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.5); + z-index: 1001; +} + +.modal-content { + background: white; + width: 90%; + max-width: 500px; + margin: 2rem auto; + padding: 2rem; + border-radius: 12px; + position: relative; +} + +.close-btn { + position: absolute; + right: 1.5rem; + top: 1rem; + font-size: 1.5rem; + cursor: pointer; +} + +.form-group { + margin-bottom: 1.5rem; +} + +.form-group label { + display: block; + margin-bottom: 0.5rem; +} + +.form-group input, +.form-group textarea { + padding: 12px 16px; + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 8px; + font-size: 16px; + transition: border-color 150ms ease, box-shadow 150ms ease; + background: white; +} + +.form-group input:focus, +.form-group textarea:focus { + outline: none; + border-color: #1d80c3; + box-shadow: 0 0 0 3px rgba(29, 128, 195, 0.1); +} + +.form-group .error-message { + display: none; + color: #dc2626; + font-size: 13px; + margin-top: 4px; +} + +.form-group.error input { + border-color: #dc2626; +} + +.form-group.error .error-message { + display: block; +} + +.submit-btn { + background: #1d80c3; + color: white; + border: none; + padding: 0.8rem; + border-radius: 100px; + width: 100%; + cursor: pointer; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(10px); + filter: drop-shadow(0 0 20px rgba(29, 128, 195, 0.15)); + } + + to { + opacity: 1; + transform: translateY(0); + filter: none; + } +} + +.hero-text > * { + animation: fadeIn 450ms ease-in-out forwards; + opacity: 0; +} + +.hero-text > *:nth-child(1) { + animation-delay: 0.1s; +} + +.hero-text > *:nth-child(2) { + animation-delay: 0.2s; +} + +.hero-text > *:nth-child(3) { + animation-delay: 0.3s; +} + +.hero-text > *:nth-child(4) { + animation-delay: 0.4s; +} + +/* Video Container Styles */ +.video-container { + width: 100%; + max-width: 900px; + margin: 0 auto; +} + +.video-wrapper { + position: relative; + padding-bottom: 56.25%; + height: 0; + background: #000; + border-radius: 16px; + overflow: hidden; + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), + 0 2px 4px -1px rgba(0, 0, 0, 0.06); + cursor: pointer; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1); +} + +@media (hover: hover) and (pointer: fine) { + .video-wrapper:hover { + transform: scale(1.02); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), + 0 4px 6px -2px rgba(0, 0, 0, 0.05); + } +} + +.video-thumbnail { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + object-fit: cover; + transition: opacity 200ms ease-out; +} + +.play-button { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 68px; + height: 48px; + background-color: rgba(33, 33, 33, 0.8); + border: none; + border-radius: 8px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: background-color 150ms ease; +} + +@media (hover: hover) and (pointer: fine) { + .play-button:hover { + background-color: #ff0000; + } +} + +.video-wrapper.playing .video-thumbnail, +.video-wrapper.playing .play-button { + opacity: 0; + pointer-events: none; +} + +.video-wrapper iframe { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + border: 0; +} + +@media (max-width: 768px) { + .video-container { + margin: 0 -1rem; + } + + .video-wrapper { + border-radius: 0; + } +} + +/* Hero background transition */ +.hero-bg { + will-change: opacity; +} + +/* Collapsible section title */ +.collapsible-title { + font-size: 28px; + font-weight: 700; + color: black; +} + +/* Mobile menu */ +#mobileMenu { + transform: translateY(-1rem); +} + +#mobileMenu.show { + opacity: 1; + pointer-events: auto; + transform: translateY(0); +} + +/* Cards container */ +.cards-container { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); + gap: 32px; + width: 100%; + max-width: 1400px; + margin: 0 auto; +} + +/* Card base styles */ +.btnCard { + /* Remove border and set background to match collapsible section */ + border: none !important; + background: #f8fafc !important; + display: flex; + flex-direction: column; + align-items: center; + gap: 24px; + padding: 24px; + border-radius: 8px; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1), box-shadow 200ms cubic-bezier(0.23, 1, 0.32, 1), background-color 200ms ease; + height: 100%; + min-height: 120px; + justify-content: center; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); +} + +@media (hover: hover) and (pointer: fine) { + .btnCard:hover { + transform: translateY(-2px); + box-shadow: 0 10px 20px rgba(29, 128, 195, 0.1), + 0 6px 6px rgba(29, 128, 195, 0.05); + } +} + +@media (hover: hover) and (pointer: fine) { + #services .btnCard:hover { + transform: none; + box-shadow: none; + } +} + +/* Standard button card images - maintain aspect ratio */ +.btnCard img { + width: 36px; + height: 36px; + object-fit: contain; +} + +.btnCard h3 { + font-size: 15px; +} + +/* Responsive adjustments */ +@media (max-width: 1200px) { + .cards-container { + grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); + padding: 0 24px; + } +} + +@media (max-width: 768px) { + .cards-container { + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 24px; + padding: 0 16px; + } + + .btnCard { + padding: 20px; + min-height: 100px; + } +} + +@media (max-width: 480px) { + .cards-container { + grid-template-columns: 1fr; + padding: 0 12px; + } + + .btnCard { + padding: 20px; + } +} + +/* Contact section */ +#Contact .card { + height: 250px; + display: flex; + flex-direction: column; + justify-content: flex-start; + padding: 32px; +} + +#Contact .card > div { + height: 100%; + display: flex; + flex-direction: column; + justify-content: space-between; +} + +.contact-link { + display: flex; + align-items: center; + gap: 8px; + margin-top: 16px; + width: 100%; + border-radius: 8px; + transition: color 150ms ease; +} + +@media (hover: hover) and (pointer: fine) { + .contact-link:hover { + color: #1d80c3; + } + + .contact-link:hover .material-icons { + transform: translateX(2px); + } +} + +.contact-link .material-icons { + font-size: 20px; + transition: transform 200ms ease-out; +} + +@supports (-webkit-backdrop-filter: none) { + .emergency-button { + -webkit-backdrop-filter: blur(8px); + } +} + +/* Desktop/Mobile visibility */ +.desktop-nav { + display: flex; +} + +.mobile-menu-btn, +.mobile-nav { + display: none; +} + +/* Mobile menu button */ +.mobile-menu-btn { + border: none; + background: none; + padding: 8px; + cursor: pointer; + color: #000; + display: none; +} + +.mobile-menu-btn .material-icons { + font-size: 24px; +} + +/* Mobile navigation */ +.mobile-nav { + position: fixed; + top: 80px; + left: 0; + right: 0; + background: white; + padding: 1rem; + box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); + z-index: 50; + transform-origin: top; + transform: translateY(-8px); + opacity: 0; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1), opacity 200ms cubic-bezier(0.23, 1, 0.32, 1); + will-change: transform, opacity; +} + +.mobile-nav.active { + transform: translateY(0); + opacity: 1; +} + +.mobile-nav-content { + display: flex; + flex-direction: column; + gap: 1rem; + transform: translateY(-10px); + opacity: 0; + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1) 50ms, opacity 200ms cubic-bezier(0.23, 1, 0.32, 1) 50ms; +} + +.mobile-nav.active .mobile-nav-content { + transform: translateY(0); + opacity: 1; +} + +/* Add stagger animation for menu items */ +.mobile-nav-link { + opacity: 0; + transform: translateX(-10px); + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1), opacity 200ms cubic-bezier(0.23, 1, 0.32, 1); +} + +.mobile-nav.active .mobile-nav-link { + opacity: 1; + transform: translateX(0); +} + +.mobile-nav.active .mobile-nav-link:nth-child(1) { + transition-delay: 0.1s; +} +.mobile-nav.active .mobile-nav-link:nth-child(2) { + transition-delay: 0.15s; +} +.mobile-nav.active .mobile-nav-link:nth-child(3) { + transition-delay: 0.2s; +} +.mobile-nav.active .mobile-nav-link:nth-child(4) { + transition-delay: 0.3s; +} + +.mobile-nav-link { + padding: 0.75rem; + color: #374151; + text-decoration: none; + transition: background-color 150ms ease; +} + +@media (hover: hover) and (pointer: fine) { + .mobile-nav-link:hover { + background-color: #f3f4f6; + } +} + +.mobile-nav-link.highlight { + background-color: #1d80c3; + color: white; + border-radius: 0.375rem; + text-align: center; +} + +@media (min-width: 768px) { + .mobile-nav { + display: none !important; + } +} + +@media (hover: hover) and (pointer: fine) { + .mobile-nav-link.highlight:hover { + background: #1557b0; + color: white; + } +} + +@media (max-width: 768px) { + .desktop-nav, + .desktop-only { + display: none; + } + + .mobile-menu-btn { + display: block; + } + + .header { + padding: 16px 2em; + background: rgba(255, 255, 255, 0.98); + backdrop-filter: blur(8px); + box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1); + } +} + +/* Font now loaded via Google Fonts CDN */ + +/* About Bharatgas Section */ +.about-bharatgas { + width: 100%; +} + +.about-bharatgas h1 { + font-size: 48px; + font-weight: 600; + margin-bottom: 8px; + padding: 0 8em; +} + +.about-bharatgas .subtitle { + font-size: 20px; + color: #666; + margin-bottom: 48px; + padding: 0 8em; +} + +.about-content { + display: grid; + gap: 32px; + width: 100%; +} + +.main-text { + font-size: 18px; + line-height: 1.6; + color: #333; + text-align: right; + width: 100%; + margin-left: auto; +} + +.features { + margin-top: 16px; + width: 100%; +} + +.features h3 { + font-size: 20px; + font-weight: 500; + margin-bottom: 24px; +} + +.features ul { + list-style: none; + padding: 0; + display: grid; + gap: 16px; + width: 100%; +} + +.features li { + font-size: 16px; + line-height: 1.5; + color: #333; +} + +.features li strong { + color: #000; +} + +.closing-text { + font-size: 18px; + line-height: 1.6; + color: #333; + text-align: right; + width: 100%; + margin-left: auto; +} + +@media (max-width: 768px) { + .about-bharatgas h1, + .about-bharatgas .subtitle { + padding: 0 2em; + } + + .about-bharatgas h1 { + font-size: 36px; + } + + .about-bharatgas .subtitle { + font-size: 18px; + margin-bottom: 32px; + } + + .main-text, + .closing-text { + text-align: left; + margin-left: 0; + } + + .about-bharatgas { + padding: 0 2em; + } +} + +.text-gray-600 { + font-family: var(--primary-font); +} + +/* About card styles */ +.about-card { + background: #fafafa; + border-radius: 8px; + padding: 80px; + margin-bottom: 64px; +} + +.about-card-content { + display: flex; + flex-direction: row; + align-items: flex-start; + gap: 48px; + max-width: 1200px; + margin: 0 auto; +} + +.about-card-left { + flex: 1; + display: flex; + flex-direction: column; + gap: 24px; + padding-top: 48px; +} + +.about-card-right { + flex: 1; + border-radius: 8px; + aspect-ratio: 16/9; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; +} + +.about-card h2 { + font-size: 36px; + font-weight: 600; + color: #000; + max-width: 450px; + text-align: left; + line-height: 1.2; +} + +.about-text { + display: flex; + flex-direction: column; + gap: 24px; + max-width: 450px; +} + +.about-text p { + font-size: 16px; + line-height: 1.6; + color: #4b5563; + text-align: left; +} + +@media (max-width: 768px) { + .about-card { + padding: 32px; + margin: 0 24px; + border-radius: 8px; + } + + .about-card-content { + flex-direction: column; + } + + .about-card-left { + padding-top: 0; + } + + .about-card h2 { + font-size: 28px; + max-width: 100%; + } + + .about-text { + max-width: 100%; + } +} + +.video-container { + width: 100%; + height: 100%; +} + +.video-wrapper { + position: relative; + width: 100%; + height: 100%; + border-radius: 8px; + overflow: hidden; +} + +.video-wrapper iframe { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + border: 0; +} + +p { + font-size: 15px; + font-weight: 400; + color: rgba(0, 0, 0, 0.6); +} + +/* Add specific styles for Useful Links section */ +#services .btnCard { + flex-direction: row; + align-items: center; + justify-content: flex-start; + gap: 24px; + border: 2px solid rgba(1, 103, 172, 0.3); + background: #ffffff; + border-radius: 24px; + transition: background-color 200ms cubic-bezier(0.23, 1, 0.32, 1), border-color 200ms cubic-bezier(0.23, 1, 0.32, 1); +} + +#services .btnCard img { + flex-shrink: 0; + object-fit: contain; + transition: filter 200ms cubic-bezier(0.23, 1, 0.32, 1); +} + +#services .btnCard h3 { + text-align: left; + margin: 0; + color: inherit; + transition: color 200ms cubic-bezier(0.23, 1, 0.32, 1); +} + +@media (hover: hover) and (pointer: fine) { + #services .btnCard:hover { + background: #0167ac; + border-color: #0167ac; + } + + #services .btnCard:hover img { + filter: brightness(0) invert(1); + } + + #services .btnCard:hover h3 { + color: #ffffff !important; + } +} + +/* Keep Book Refill section centered */ +section:not(#services) .btnCard { + align-items: center; + text-align: center; +} + +/* Responsive adjustments */ +@media (max-width: 768px) { + #services .btnCard { + padding: 20px; + gap: 16px; + } +} + +@media (max-width: 480px) { + #services .btnCard { + padding: 16px; + gap: 12px; + } +} + +/* Add specific margin for sections */ +section { + margin-bottom: 80px; +} + +@media (max-width: 480px) { + .defaultMargin { + margin-bottom: 48px; + } + + section { + margin-bottom: 48px; + } +} + +/* Location section styles */ +.direction.reverse { + align-items: center; + flex-wrap: wrap; + gap: 64px; +} + +.direction.reverse img { + box-shadow: none; +} + +/* Add these styles for mobile view */ +@media (max-width: 768px) { + .direction.reverse { + text-align: center; + } + + .direction.reverse > div { + flex: 1 1 100%; /* Take full width */ + } + + /* Center align the text container */ + .direction.reverse > div:last-child { + align-items: center; + text-align: center; + } + + /* Center align the text content */ + .direction.reverse > div:last-child > div { + text-align: center; + align-items: center; + display: flex; + flex-direction: column; + gap: 16px; + } + + /* Center align paragraph text */ + .direction.reverse > div:last-child > div p { + text-align: center; + max-width: 400px; + margin: 0 auto; + } + + /* Center align the button */ + .direction.reverse > div:last-child > a { + align-self: center; + } + + /* Center the image */ + .direction.reverse > div:first-child { + justify-content: center; + } + + /* Adjust image size */ + .direction.reverse img { + max-width: 100%; + width: 100%; + } +} + +/* About section responsive styles */ +@media (max-width: 768px) { + .about-section-container { + flex-direction: column; + gap: 32px; + } + + .about-section-container > div:first-child { + order: 1; /* Move text to top */ + text-align: center; + } + + .about-section-container > div:first-child h2 br { + display: none; /* Remove line break in heading on mobile */ + } + + .about-section-container > div:last-child { + order: 2; /* Move video to bottom */ + width: 100%; + } +} + +@media (max-width: 480px) { + .about-section-container { + gap: 24px; + } +} + +/* Lottie animation container styles */ +.lottie-container { + display: flex; + justify-content: center; + width: 64px; +} + +@media (max-width: 768px) { + .lottie-container { + } + + /* Update the container for mobile */ + .about-section-container > div:first-child > div { + gap: 16px; + } +} + +.footer-content { + display: flex; + justify-content: space-around; + align-items: flex-start; + gap: 48px; + width: 100%; + max-width: 1200px; + margin: 0 auto; +} + +.footer-section { + text-align: center; + min-width: 200px; +} + +.footer-section h3 { + margin-bottom: 16px; + color: #0c334e; +} + +@media (max-width: 768px) { + .footer-content { + flex-direction: column; + align-items: center; + gap: 32px; + } + + .footer-section { + min-width: unset; + width: 100%; + text-align: center; + } +} + +/* Awards ticker styles */ +.awards-ticker-container { + width: 100vw; + position: relative; + left: 50%; + right: 50%; + margin-left: -50vw; + margin-right: -50vw; + overflow: hidden; + /* background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); */ + padding: 40px 0; +} + +.awards-ticker { + display: flex; + gap: 24px; + animation: scroll-ticker 40s linear infinite; + width: fit-content; +} + +@keyframes scroll-ticker { + 0% { + transform: translateX(0); + } + 100% { + transform: translateX(-50%); + } +} + +.awards-ticker:hover { + animation-play-state: paused; +} + +.ticker-arrow { + position: absolute; + top: 50%; + transform: translateY(-50%); + z-index: 10; + width: 44px; + height: 44px; + border-radius: 50%; + border: none; + background: #fff; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + opacity: 0.35; + transition: opacity 200ms ease, transform 200ms cubic-bezier(0.23, 1, 0.32, 1), box-shadow 200ms ease; + color: #1d80c3; + pointer-events: auto; +} + +.awards-ticker-container:hover .ticker-arrow { + opacity: 1; +} + +.ticker-arrow--prev { + left: 32px; +} + +.ticker-arrow--next { + right: 32px; +} + +.ticker-arrow .material-symbols-outlined { + font-size: 22px; +} + +@media (hover: hover) and (pointer: fine) { + .ticker-arrow:hover { + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.18); + transform: translateY(-50%) scale(1.08); + } +} + +.ticker-arrow:active { + transform: translateY(-50%) scale(0.95); +} + +@media (max-width: 768px) { + .ticker-arrow { + opacity: 1; + width: 40px; + height: 40px; + } + .ticker-arrow--prev { left: 8px; } + .ticker-arrow--next { right: 8px; } +} + +.award-card { + min-width: 280px; + background: #f8fafc !important; + border-radius: 16px; + padding: 24px; + box-shadow: none !important; + display: flex; + flex-direction: column; + justify-content: space-between; + border: none !important; + position: relative; + transform-origin: center center; + margin-right: 0; + height: 204px; +} + +.award-title { + color: #1d80c3; + font-size: 20px; + font-weight: 600; +} + +.award-info { + display: flex; + flex-direction: column; +} + +.award-winner { + font-size: 17px; + font-weight: 700; + color: #000000; +} + +.award-year { + font-size: 14px; + color: rgba(0, 0, 0, 0.6); +} + +@keyframes blurFadeIn { + 0% { + opacity: 0; + filter: blur(8px); + transform: translateY(20px); + box-shadow: 0 0 60px rgba(29, 128, 195, 0.25); + } + 100% { + opacity: 1; + filter: blur(0); + transform: translateY(0); + box-shadow: none; + } +} + +.hero-text { + animation: blurFadeIn 700ms ease-in-out forwards; + will-change: transform, opacity; +} + +@keyframes heroImageBlurIn { + 0% { + opacity: 0; + filter: blur(12px); + transform: translateY(20px); + box-shadow: 0 0 80px rgba(29, 128, 195, 0.2); + } + 100% { + opacity: 1; + filter: blur(0); + transform: translateY(0); + box-shadow: none; + } +} + +.hero-image-animate { + animation: heroImageBlurIn 700ms ease-in-out 100ms forwards; + opacity: 0; + will-change: transform, opacity; +} + +/* Hero section styles */ +@media (max-width: 768px) { + header#home { + min-height: 100vh; + display: flex; + flex-direction: column; + } + + header#home .relative.z-10 { + flex: 1; + display: flex; + flex-direction: column; + justify-content: center; + } + + header#home .w-full:last-child { + margin-top: auto; + } + + header#home .w-full:last-child img { + display: block; + width: 100%; + object-fit: contain; + } +} + +/* Skeleton loading styles */ +@keyframes shimmer { + 0% { + background-position: -1000px 0; + } + 100% { + background-position: 1000px 0; + } +} + +.skeleton { + background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); + background-size: 1000px 100%; + animation: shimmer 2s infinite linear; +} + +.skeleton-text { + height: 20px; + border-radius: 4px; + margin-bottom: 12px; + width: 100%; +} + +.skeleton-title { + height: 32px; + width: 60%; + border-radius: 4px; + margin-bottom: 24px; +} + +.skeleton-card { + min-width: 280px; + height: 204px; + background: #ffffff; + border-radius: 16px; + padding: 24px; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + display: flex; + flex-direction: column; + justify-content: space-between; + border: 1px solid rgba(0, 0, 0, 0.1); +} + +/* Contact section specific card styles */ +.contact-card { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 16px; + padding: 24px; + background: #fafafa; + border-radius: 12px; +} + +.contact-card-content { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; + align-self: stretch; +} + +.contact-card-header { + display: flex; + flex-direction: column; + gap: 4px; +} + +.contact-icon { + width: 48px; + height: 48px; +} + +/* Book refill section specific styles */ +.book-refill .btnCard { + border-radius: 16px !important; + gap: 0; + min-height: auto; + padding: 16px; + background: #fafafa; +} + +@media (hover: hover) and (pointer: fine) { + .book-refill .btnCard:hover { + background: inherit !important; + color: inherit !important; + } +} + +.book-refill .btnCard img { + width: 80px; + height: 80px; + object-fit: contain; +} + +@media (max-width: 768px) { + .book-refill .btnCard img { + width: 64px; + height: 64px; + object-fit: contain; + } +} + +@media (max-width: 480px) { + .book-refill .btnCard img { + width: 56px; + height: 56px; + object-fit: contain; + } +} + +/* Contact section layout */ +.contact-grid { + display: flex; + flex-wrap: wrap; + gap: 16px; +} + +.contact-info { + display: flex; + flex-direction: column; + gap: 16px; + min-width: 300px; +} + +/* Contact form styles */ +.contact-form-container { + background: #fafafa; + border-radius: 16px; + padding: 24px; + position: relative; +} + +.form-header { + margin-bottom: 20px; +} + +.form-header h3 { + font-size: 24px; + font-weight: 600; + margin-bottom: 8px; +} + +.form-header p { + color: rgba(0, 0, 0, 0.6); + font-size: 15px; +} + +.contact-form { + display: flex; + flex-direction: column; +} + +.form-group { + display: flex; + flex-direction: column; +} + +.form-group label { + font-size: 15px; + font-weight: 500; + color: rgba(0, 0, 0, 0.8); +} + +.form-group input, +.form-group textarea { + padding: 8px 12px; + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 8px; + font-size: 16px; + transition: border-color 150ms ease, box-shadow 150ms ease; + background: white; +} + +.form-group input:focus, +.form-group textarea:focus { + outline: none; + border-color: #1d80c3; + box-shadow: 0 0 0 3px rgba(29, 128, 195, 0.1); +} + +.form-group .error-message { + display: none; + color: #dc2626; + font-size: 13px; + margin-top: 4px; +} + +.form-group.error input { + border-color: #dc2626; +} + +.form-group.error .error-message { + display: block; +} + +.submit-btn { + background: #1d80c3; + color: white; + border: none; + padding: 8px 16px; + border-radius: 8px; + font-weight: 600; + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; + transition: background-color 150ms ease, transform 200ms ease-out; +} + +@media (hover: hover) and (pointer: fine) { + .submit-btn:hover { + background: #1557b0; + transform: translateY(-1px); + } +} + +/* Mobile responsive */ +@media (max-width: 768px) { + .contact-grid { + grid-template-columns: 1fr; + gap: 32px; + } + .contact-info { + min-width: 100%; + } + .contact-form-container { + width: 100%; + min-width: 100%; + flex: 1 1 100%; + box-sizing: border-box; + } +} + +.form-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} + +@media (max-width: 768px) { + .form-row { + grid-template-columns: 1fr; + gap: 16px; + } +} + +.message-icon { + position: absolute; + top: -20px; + right: 24px; + width: 40px; + height: 40px; + z-index: 1; +} + +/* Agency Finder Mobile Styles */ +@media (max-width: 768px) { + .agency-finder-container { + flex-direction: column-reverse !important; + gap: 32px !important; + } + + .agency-finder-content { + order: 2; + } + + .agency-finder-image { + order: 1; + width: 100% !important; + } + + .agency-finder-form { + max-width: 100% !important; + } + + .agency-finder-text h2 { + text-align: center; + margin-bottom: 16px; + } + + .agency-finder-text p { + text-align: center; + margin-bottom: 24px; + } + + .button-group { + flex-direction: row !important; + gap: 12px !important; + } + + .button-group .CTA { + flex: 1 !important; + } + + #clear-button { + flex: none !important; + min-width: 90px !important; + } + + #agency-card { + margin-top: 24px; + padding: 20px !important; + max-height: 350px !important; + } +} + +@media (max-width: 480px) { + .agency-finder-container { + gap: 24px !important; + } + + .agency-finder-form { + gap: 12px !important; + } + + .agency-finder-text h2 { + font-size: 24px; + } + + .agency-finder-text p { + font-size: 14px; + } + + #clear-button { + padding: 8px 16px !important; + font-size: 13px !important; + min-width: 80px !important; + } + + .button-group .CTA { + font-size: 14px !important; + } + + #agency-card { + max-height: 300px !important; + } +} + +/* Prevent app store badge images from scaling up on mobile */ +.flex.gap-6.justify-center img[src*="App-Store"], +.flex.gap-6.justify-center img[src*="Google-Store"], +.flex.gap-6.justify-center img.w-\[120px\] { + width: 120px !important; + max-width: 120px !important; + height: auto !important; + object-fit: contain !important; +} + +@media (max-width: 768px) { + .flex.gap-6.justify-center img[src*="App-Store"], + .flex.gap-6.justify-center img[src*="Google-Store"], + .flex.gap-6.justify-center img.w-\[120px\] { + width: 120px !important; + max-width: 120px !important; + height: auto !important; + object-fit: contain !important; + } +} + +/* Material Design inspired collapsible sections */ +.material-collapsible { + background: #f8f9fa; + border-radius: 16px; + margin-bottom: 8px; + border: none !important; + transition: background-color 200ms ease; + overflow: hidden; +} + +@media (hover: hover) and (pointer: fine) { + .material-collapsible:hover { + background: #f1f3f4; + border-color: #dee2e6; + } +} + +.material-collapsible.expanded { + background: #e3f2fd; + border-color: #2196f3; +} + +.material-collapsible-header { + position: relative; + padding: 24px; + cursor: pointer; + user-select: none; + transition: background-color 150ms ease; + border: none; + background: transparent; + width: 100%; + text-align: left; + display: flex; + justify-content: space-between; + align-items: center; +} + +@media (hover: hover) and (pointer: fine) { + .material-collapsible-header:hover { + background-color: rgba(0, 0, 0, 0.04); + } +} + +.material-collapsible-header:focus { + outline: none; + background-color: rgba(29, 128, 195, 0.08); +} + +.material-collapsible-header::before { + content: ""; + position: absolute; + top: 50%; + left: 50%; + width: 300px; + height: 300px; + background: rgba(29, 128, 195, 0.3); + border-radius: 50%; + transform: translate(-50%, -50%) scale(0); + transition: transform 400ms cubic-bezier(0.23, 1, 0.32, 1), opacity 400ms cubic-bezier(0.23, 1, 0.32, 1); + opacity: 0; +} + +.material-collapsible-header:active::before { + transform: translate(-50%, -50%) scale(1); + opacity: 1; +} + +.material-collapsible-content-wrapper { + background: #fafafa; + overflow: hidden; + transition: max-height 300ms cubic-bezier(0.23, 1, 0.32, 1); + max-height: 0; + padding: 0 24px; + border: none !important; +} + +.material-collapsible-content-wrapper.expanded { + padding: 24px; + max-height: 1000px; +} + +.material-collapsible-content { + opacity: 0; + transform: translateY(-8px); + transition: opacity 200ms cubic-bezier(0.23, 1, 0.32, 1) 50ms, transform 200ms cubic-bezier(0.23, 1, 0.32, 1) 50ms; +} + +.material-collapsible-content-wrapper.expanded .material-collapsible-content { + opacity: 1; + transform: translateY(0); +} + +.material-collapsible-icon { + transition: transform 200ms cubic-bezier(0.23, 1, 0.32, 1); + color: #666; + font-size: 24px; + will-change: transform; +} + +.material-collapsible.expanded .material-collapsible-icon { + transform: rotate(45deg); + color: #1d80c3; +} + +.material-collapsible-title { + margin: 0; + font-size: 18px; + font-weight: 600; + color: #1f2937; + line-height: 1.3; +} + +.material-collapsible-subtitle { + margin: 4px 0 0 0; + font-size: 14px; + color: #6b7280; + font-weight: 400; +} + +.material-collapsible-text { + color: #374151; + line-height: 1.6; + margin: 0; +} + +.material-collapsible-text:not(:last-child) { + margin-bottom: 16px; +} + +.material-collapsible-list { + list-style: none; + padding: 0; + margin: 16px 0; +} + +.material-collapsible-list li { + padding: 8px 0; + padding-left: 20px; + position: relative; + color: #374151; + line-height: 1.6; +} + +.material-collapsible-list li::before { + content: "•"; + color: #1d80c3; + position: absolute; + left: 0; + font-weight: bold; + font-size: 18px; +} + +/* Mobile responsive */ +@media (max-width: 768px) { + .material-collapsible-header { + padding: 20px 16px; + } + + .material-collapsible-content-wrapper { + padding: 0 16px; + } + + .material-collapsible-content-wrapper.expanded { + padding: 20px 16px; + } + + .material-collapsible-title { + font-size: 16px; + } + + .material-collapsible-subtitle { + font-size: 13px; + } +} + +button { + background: transparent; + border: transparent; +}
diff --git a/templates.html b/templates.html @@ -0,0 +1,16 @@ +<template id="custom-date"> + <style> + .date-p { + text-align: center; + width: fit-content; + line-height: 0.7em; + position: relative; + left: -6px; + } + </style> + <div class="date-p"> + <p style="font-weight: 700;color: black;">23</p> + <small>Aug</small> + <hr style="border: 1px solid black;"> + </div> +</template>
diff --git a/tests/tva-control.test.js b/tests/tva-control.test.js @@ -0,0 +1,28 @@ +const assert = require('assert'); +const fs = require('fs'); +const vm = require('vm'); + +const code = fs.readFileSync('tva-control.js', 'utf8'); +const context = { window: {}, console, setInterval() { return 1; }, clearInterval() {} }; +vm.createContext(context); +vm.runInContext(code, context); + +const { getTrend, isStale, mergeData } = context.window.TvaControlInternals; + +assert.equal(getTrend(10, 10), 'flat'); +assert.equal(getTrend(10, 24), 'flat'); +assert.equal(getTrend(10, 25), 'up'); +assert.equal(getTrend(25, 10), 'down'); +assert.equal(getTrend(undefined, 10), 'flat'); +assert.equal(getTrend(10, 24, 10), 'up'); +assert.equal(getTrend(24, 10, 10), 'down'); + +assert.equal(isStale(Date.now() - 1_000, 5_000, Date.now()), false); +assert.equal(isStale(Date.now() - 6_000, 5_000, Date.now()), true); +assert.equal(isStale(null, 5_000, Date.now()), true); +assert.equal(isStale(null, 0, Date.now()), false); + +assert.equal(mergeData({ refillSpreadDays: 0 }, { bookingAgeDays: 7 }, { bookingAgeDays: 'refillSpreadDays' }).refillSpreadDays, 7); +assert.equal(mergeData({ bpclDepositLakhs: 0 }, { bpclDeposit: 3 }, { bpclDeposit: 'bpclDepositLakhs' }).bpclDepositLakhs, 3); + +console.log('tva-control tests passed');
diff --git a/tva-control-demo.html b/tva-control-demo.html @@ -0,0 +1,130 @@ +<!doctype html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>TVA Control Demo</title> + <link rel="stylesheet" href="tva-control.css"> + <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> + <script src="tva-control.js"></script> + <style> + body { background: #0e0e0e; color: #eee; font-family: system-ui, sans-serif; margin: 24px; transition: background 180ms ease, color 180ms ease; } + body.demo-light { background: #fff; color: #333; } + .demo-toolbar { align-items: center; display: flex; gap: 8px; margin: 0 0 14px; } + .demo-toolbar button { background: #222; border: 1px solid #555; color: #eee; cursor: pointer; font: 700 12px/1 system-ui, sans-serif; padding: 8px 10px; } + body.demo-light .demo-toolbar button { background: #fff; border-color: #b9c7c4; color: #173f3a; } + .demo-toolbar button.is-active { border-color: #00b49f; box-shadow: 0 0 0 2px rgba(0, 180, 159, .18); } + .tva-control-container { max-width: 920px; } + </style> +</head> +<body> + <h1>TVA Control Demo</h1> + <div class="demo-toolbar" aria-label="Theme switcher"> + <button type="button" data-theme="dark" class="is-active">Dark</button> + <button type="button" data-theme="light">Light</button> + <button type="button" data-theme="auto">Auto</button> + </div> + <div id="demo-chart" class="tva-control-container" data-tva-theme="dark"><canvas></canvas></div> + <script> + const config = { + title: 'TVA REACTIVE CHANNEL', + blinkMs: 1100, + aliases: { + bookingAgeDays: 'refillSpreadDays', + bookingSpreadDays: 'refillSpreadDays', + bpclDeposit: 'bpclDepositLakhs' + }, + ambientGlow: { enabled: true, alpha: 0.14, radius: 74, blur: 42 }, + warningLevels: [ + { key: 'amber', label: 'AMBER ALERT', priority: 1, showAxis: true, dominance: 0.6, axisAlpha: 0.28, axisWidth: 1.45, axisDash: [3, 5], glowAlpha: 0.12 }, + { key: 'red', label: 'CRITICAL', priority: 2, showAxis: true, dominance: 0.7, axisAlpha: 0.42, axisWidth: 1.45, axisDash: [6, 6], glowAlpha: 0.16 }, + { key: 'double-red', label: 'DOUBLE RED', priority: 3, showAxis: false, dominance: 0.7, borderBlink: true, glowAlpha: 0.18, glowRadius: 88, glowBlur: 54 } + ], + colors: { + amber: '#ffcc00', + red: '#ff0055', + 'double-red': '#ff1a1a', + disabled: '#777777' + }, + staleAlpha: 0.35, + parameters: [ + { key: 'complaintsOpen', label: 'Complaints Open', icon: 'warning', scale: 'count10', refreshMinutes: 15, thresholds: { amberUpper: 52.5, redUpper: 75, amberLower: -52.5, redLower: -75 } }, + { key: 'invoiceActions', label: 'Invoice Actions', icon: 'invoice', scale: 'count10', refreshMinutes: 15, thresholds: { amberUpper: 59.5, redUpper: 85, amberLower: -59.5, redLower: -85 } }, + { key: 'deliveryPersonLeave', label: 'Delivery Person Leave', icon: 'person', scale: 'count10', refreshMinutes: 720, thresholds: { amberUpper: 49, redUpper: 70, amberLower: -49, redLower: -70 } }, + { key: 'refillSpreadDays', label: 'Refill Spread', icon: 'calendar', scale: 'daysCritical', scaleBase: 10, scaleMax: 165, refreshMinutes: 1440, display: { suffix: 'd' }, thresholds: { amberUpper: 50, redUpper: 100, doubleRedUpper: 150, amberLower: -70, redLower: -100 }, detailMode: 'refill-spread', areaKey: 'refillSpreadAreas', detailTitle: 'REFILL SPREAD AREA SCAN', detailLevels: [{ level: 'amber', above: 5 }, { level: 'red', above: 10 }] }, + { key: 'pendencyDays', label: 'Pendency', icon: 'hourglass', scale: 'pendency', scaleIdeal: 1, scaleBase: 3, scaleMax: 115, refreshMinutes: 720, display: { suffix: 'd', decimals: 1 }, thresholds: { amberUpper: 33.33, redUpper: 100, amberLower: -70, redLower: -100 }, detailMode: 'pendency', areaKey: 'pendencyAreas', detailTitle: 'PENDENCY AREA SCAN', detailLevels: [{ level: 'amber', above: 1 }, { level: 'red', above: 3 }] }, + { key: 'bpclDepositLakhs', label: 'BPCL Deposit', icon: 'deposit', scale: 'raw', refreshMinutes: 30, display: { prefix: '₹', suffix: 'L', decimals: 1 }, thresholds: { amberUpper: 4, redUpper: 6, amberLower: -1, redLower: -3 } } + ], + extraAxes: [ + { label: 'BPCL Deposit Good', parameterKey: 'bpclDepositLakhs', value: 6, color: 'rgba(0,255,120,.5)', width: 1.8, dash: [4, 4] }, + { label: 'BPCL Deposit Soft', parameterKey: 'bpclDepositLakhs', value: 4, color: 'rgba(120,255,160,.34)', width: 1.4, dash: [2, 5] } + ] + }; + + const data = { + complaintsOpen: 0, + invoiceActions: 2, + deliveryPersonLeave: 0, + refillSpreadDays: 12, + pendencyDays: 2.7, + bpclDepositLakhs: 3, + updatedAt: { + bpclDepositLakhs: Date.now() - (31 * 60 * 1000) + }, + refillSpreadAreas: { + 'KK NAGAR': 12, + 'WEST MAMBALAM': 9, + 'ASHOK NAGAR': 7, + 'T NAGAR': 11, + 'VADAPALANI': 6, + 'KODAMBAKKAM': 8, + 'SALIGRAMAM': 5, + 'VIRUGAMBAKKAM': 10, + 'NESAPAKKAM': 13, + 'JAFFERKHANPET': 6, + 'EKKATTUTHANGAL': 4, + 'MGR NAGAR': 9, + 'SAIDAPET': 7 + }, + pendencyAreas: { + 'KK NAGAR': 3.4, + 'WEST MAMBALAM': 2.9, + 'ASHOK NAGAR': 2.6, + 'T NAGAR': 3.1, + 'VADAPALANI': 2.2, + 'KODAMBAKKAM': 2.8, + 'SALIGRAMAM': 1.9, + 'VIRUGAMBAKKAM': 2.4, + 'NESAPAKKAM': 3.0, + 'JAFFERKHANPET': 2.1, + 'EKKATTUTHANGAL': 1.7, + 'MGR NAGAR': 2.5, + 'SAIDAPET': 2.0 + } + }; + + const chartContainer = document.getElementById('demo-chart'); + let tva = createTvaControl({ container: chartContainer, config, data }); + + function applyDemoTheme(theme) { + chartContainer.dataset.tvaTheme = theme === 'auto' ? '' : theme; + if (theme === 'auto') chartContainer.removeAttribute('data-tva-theme'); + document.body.classList.toggle('demo-light', theme === 'light' || (theme === 'auto' && matchMedia('(prefers-color-scheme: light)').matches)); + document.querySelectorAll('.demo-toolbar button').forEach(button => button.classList.toggle('is-active', button.dataset.theme === theme)); + tva.refreshTheme(); + window.tva = tva; + } + + document.querySelector('.demo-toolbar').addEventListener('click', event => { + const button = event.target.closest('button[data-theme]'); + if (button) applyDemoTheme(button.dataset.theme); + }); + + matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => { + if (document.querySelector('.demo-toolbar button[data-theme="auto"]').classList.contains('is-active')) applyDemoTheme('auto'); + }); + + window.tva = tva; + </script> +</body> +</html>
diff --git a/tva-control.css b/tva-control.css @@ -0,0 +1,363 @@ +/* Standalone TVA control styles. Pair with tva-control.js. */ +.tva-control-container, +.action-chart-container { + color-scheme: dark; + --tva-bg: #161616; + --tva-border: #333333; + --tva-plot-glow: rgba(255, 0, 85, 0.08); + --tva-white: #ffffff; + --tva-control-active-bg: rgba(0, 255, 204, 0.14); + --tva-control-border-muted: rgba(0, 255, 204, 0.28); + --tva-double-red-shadow: rgba(255, 0, 0, 0.72); + --tva-control-bg: rgba(12, 12, 12, 0.72); + --tva-control-border: rgba(0, 255, 204, 0.26); + --tva-control-border-active: rgba(0, 255, 204, 0.72); + --tva-control-text: #dffff8; + --tva-title: #00ffcc; + --tva-alert-amber: #ffcc00; + --tva-alert-red: #ff0055; + --tva-alert-double-red: #ff1a1a; + --tva-icon-cutout: #161616; + --tva-fullscreen-border: rgba(255, 0, 85, 0.55); + --tva-fullscreen-shadow: rgba(255, 0, 85, 0.18); + --tva-fullscreen-inset: rgba(0, 255, 204, 0.035); + --tva-chart-grid: #222; + --tva-chart-detail-grid: #242424; + --tva-axis-text: #ffffff; + --tva-detail-axis-text: #aaaaaa; + --tva-plot-icon: #ffffff; + --tva-stale-text: #9aa6ac; + --tva-stale-label-fill: rgba(2, 6, 8, 0.84); + --tva-normal-label-fill: rgba(5, 34, 30, 0.62); + --tva-normal-label-stroke: rgba(116, 137, 148, 0.44); + --tva-normal-line: #4f646e; + --tva-stale-line: #4f646e; + --tva-border-alert-color: #ff1a1a; +} + +.tva-control-container[data-tva-theme="light"], +.action-chart-container[data-tva-theme="light"] { + color-scheme: light; + --tva-bg: #f1f5f4; + --tva-border: #dde7e5; + --tva-plot-glow: rgba(255, 0, 85, 0.06); + --tva-white: #ffffff; + --tva-control-active-bg: rgba(0, 128, 112, 0.1); + --tva-control-border-muted: rgba(0, 128, 112, 0.3); + --tva-double-red-shadow: rgba(255, 0, 0, 0.34); + --tva-control-bg: rgba(255, 255, 255, 0.86); + --tva-control-border: rgba(0, 128, 112, 0.34); + --tva-control-border-active: rgba(0, 128, 112, 0.82); + --tva-control-text: #173f3a; + --tva-title: #006f62; + --tva-alert-amber: #8a5c00; + --tva-alert-red: #c00045; + --tva-alert-double-red: #b00000; + --tva-icon-cutout: #f1f5f4; + --tva-fullscreen-border: rgba(208, 0, 75, 0.5); + --tva-fullscreen-shadow: rgba(208, 0, 75, 0.16); + --tva-fullscreen-inset: rgba(0, 128, 112, 0.04); + --tva-chart-grid: rgba(0, 48, 87, 0.055); + --tva-chart-detail-grid: rgba(0, 48, 87, 0.055); + --tva-axis-text: #173f3a; + --tva-detail-axis-text: #49615e; + --tva-plot-icon: #111827; + --tva-stale-text: #4f646e; + --tva-stale-label-fill: rgba(255, 255, 255, 0.88); + --tva-normal-label-fill: rgba(255, 255, 255, 0.82); + --tva-normal-label-stroke: rgba(23, 63, 58, 0.24); + --tva-normal-line: #90a4ae; + --tva-stale-line: #90a4ae; + --tva-border-alert-color: #c40000; +} + +@media (prefers-color-scheme: light) { + .tva-control-container:not([data-tva-theme="dark"]), + .action-chart-container:not([data-tva-theme="dark"]) { + color-scheme: light; + --tva-bg: #f1f5f4; + --tva-border: #dde7e5; + --tva-plot-glow: rgba(255, 0, 85, 0.06); + --tva-white: #ffffff; + --tva-control-active-bg: rgba(0, 128, 112, 0.1); + --tva-control-border-muted: rgba(0, 128, 112, 0.3); + --tva-double-red-shadow: rgba(255, 0, 0, 0.34); + --tva-control-bg: rgba(255, 255, 255, 0.86); + --tva-control-border: rgba(0, 128, 112, 0.34); + --tva-control-border-active: rgba(0, 128, 112, 0.82); + --tva-control-text: #173f3a; + --tva-title: #006f62; + --tva-alert-amber: #8a5c00; + --tva-alert-red: #c00045; + --tva-alert-double-red: #b00000; + --tva-icon-cutout: #f1f5f4; + --tva-fullscreen-border: rgba(208, 0, 75, 0.5); + --tva-fullscreen-shadow: rgba(208, 0, 75, 0.16); + --tva-fullscreen-inset: rgba(0, 128, 112, 0.04); + --tva-chart-grid: rgba(0, 48, 87, 0.055); + --tva-chart-detail-grid: rgba(0, 48, 87, 0.055); + --tva-axis-text: #173f3a; + --tva-detail-axis-text: #49615e; + --tva-plot-icon: #111827; + --tva-stale-text: #4f646e; + --tva-stale-label-fill: rgba(255, 255, 255, 0.88); + --tva-normal-label-fill: rgba(255, 255, 255, 0.82); + --tva-normal-label-stroke: rgba(23, 63, 58, 0.24); + --tva-normal-line: #90a4ae; + --tva-stale-line: #90a4ae; + --tva-border-alert-color: #c40000; + } +} + +.tva-control-container, +.action-chart-container { + background: radial-gradient(circle at 50% 20%, var(--tva-plot-glow), transparent 32%), var(--tva-bg); + border: 1px solid var(--tva-border); + border-radius: 12px; + height: 280px; + margin-bottom: 12px; + padding: 10px 0; + position: relative; + transition: border-color 180ms ease, box-shadow 180ms ease; +} + +.tva-control-container.tva-border-alert, +.action-chart-container.tva-border-alert { + animation: tvaBorderAlertPulse 1.1s ease-in-out infinite; + border-color: var(--tva-border-alert-color); +} + +@keyframes tvaBorderAlertPulse { + 0%, 100% { + border-color: var(--tva-border-alert-color); + box-shadow: 0 0 0 rgba(255, 0, 0, 0), inset 0 0 0 rgba(255, 0, 0, 0); + } + 50% { + border-color: var(--tva-border-alert-color); + box-shadow: 0 0 22px color-mix(in srgb, var(--tva-border-alert-color) 42%, transparent), inset 0 0 18px color-mix(in srgb, var(--tva-border-alert-color) 16%, transparent); + } +} + +.tva-control-container canvas, +.action-chart-container canvas { + display: block; + height: 100% !important; + max-height: 280px; + width: 100% !important; +} + +.tva-chart-controls { + align-items: center; + display: flex; + gap: 6px; + justify-content: flex-end; + left: 10px; + pointer-events: none; + position: absolute; + right: 10px; + top: 6px; + z-index: 5; +} + +.tva-chart-controls button { + background: var(--tva-control-bg); + border: 1px solid var(--tva-control-border); + border-radius: 0; + color: var(--tva-control-text); + cursor: pointer; + font: 700 10px/1 monospace; + letter-spacing: 0.04em; + min-height: 22px; + min-width: 22px; + padding: 4px 6px; + pointer-events: auto; + text-transform: uppercase; +} + +.tva-chart-controls button:hover, +.tva-chart-controls button.is-active { + border-color: var(--tva-control-border-active); + color: var(--tva-white); +} + +.tva-chart-controls button.is-active { + background: var(--tva-control-active-bg); +} + +.tva-chart-heading { + left: 50%; + pointer-events: auto; + position: absolute; + top: 4px; + transform: translateX(-50%); + white-space: nowrap; +} + +.tva-chart-mode-select { + appearance: none; + background: var(--tva-control-bg); + border: 1px solid var(--tva-control-border); + border-radius: 999px; + color: var(--tva-title); + cursor: pointer; + font: 800 11px/1 monospace; + letter-spacing: 0.08em; + max-width: min(58vw, 360px); + padding: 5px 24px 5px 12px; + text-align: center; + text-transform: uppercase; +} + +.tva-chart-heading::after { + color: var(--tva-title); + content: "▾"; + font-size: 10px; + pointer-events: none; + position: absolute; + right: 9px; + top: 50%; + transform: translateY(-50%); +} + +.sr-only { + height: 1px; + margin: -1px; + overflow: hidden; + position: absolute; + width: 1px; +} + +.tva-chart-back { + background: transparent !important; + border-color: var(--tva-control-border-muted) !important; + color: var(--tva-title); + left: 0; + margin-right: 0; + min-width: 22px; + position: absolute; +} + +.tva-fullscreen-icon { + display: block; + height: 12px; + position: relative; + width: 12px; +} + +.tva-fullscreen-icon::before, +.tva-fullscreen-icon::after { + border-color: currentColor; + border-style: solid; + content: ""; + height: 5px; + position: absolute; + width: 5px; +} + +.tva-fullscreen-icon::before { + border-width: 2px 0 0 2px; + left: 0; + top: 0; +} + +.tva-fullscreen-icon::after { + border-width: 0 2px 2px 0; + bottom: 0; + right: 0; +} + +.tva-chart-fullscreen.is-restore .tva-fullscreen-icon::before { + border-width: 0 2px 2px 0; + left: 1px; + top: 1px; +} + +.tva-chart-fullscreen.is-restore .tva-fullscreen-icon::after { + border-width: 2px 0 0 2px; + bottom: 1px; + right: 1px; +} + +.tva-alert-badge { + align-items: center; + background: transparent; + border: 0; + border-radius: 0; + color: var(--tva-alert-amber); + display: flex; + font: 800 9px/1 monospace; + gap: 5px; + left: 10px; + letter-spacing: 0.12em; + padding: 0; + pointer-events: none; + position: absolute; + text-transform: uppercase; + top: 10px; + z-index: 3; +} + +.tva-alert-icon { + border-bottom: 10px solid currentColor; + border-left: 6px solid transparent; + border-right: 6px solid transparent; + display: inline-block; + height: 0; + position: relative; + width: 0; +} + +.tva-alert-icon::before { + background: var(--tva-icon-cutout); + content: ""; + height: 4px; + left: -1px; + position: absolute; + top: 3px; + width: 2px; +} + +.tva-alert-icon::after { + background: var(--tva-icon-cutout); + border-radius: 1px; + content: ""; + height: 2px; + left: -1px; + position: absolute; + top: 8px; + width: 2px; +} + +.tva-alert-badge.is-critical { + background: transparent; + border-color: transparent; + color: var(--tva-alert-red); +} + +.tva-alert-badge.is-double-red { + color: var(--tva-alert-double-red); + text-shadow: 0 0 10px var(--tva-double-red-shadow); +} + +.tva-alert-badge.is-amber { + opacity: 1; +} + +.tva-chart-fullscreen-mode { + border-color: var(--tva-fullscreen-border); + border-radius: 0; + bottom: 8px; + box-shadow: 0 0 48px var(--tva-fullscreen-shadow), inset 0 0 30px var(--tva-fullscreen-inset); + height: auto; + left: 8px; + margin: 0; + padding: 10px; + position: fixed; + right: 8px; + top: 8px; + z-index: 1000; +} + +.tva-chart-fullscreen-mode canvas { + max-height: none; +}
diff --git a/tva-control.js b/tva-control.js @@ -0,0 +1,194 @@ +(function () { + function number(value, fallback = 0) { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; + } + function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } + function clone(value) { return JSON.parse(JSON.stringify(value)); } + function camel(key) { return String(key).replace(/-([a-z])/g, (_, c) => c.toUpperCase()); } + function escapeAttr(value) { return String(value).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); } + function colorWithAlpha(color, alpha) { + if (String(color).startsWith('#') && color.length === 7) { + const r = parseInt(color.slice(1, 3), 16), g = parseInt(color.slice(3, 5), 16), b = parseInt(color.slice(5, 7), 16); + return `rgba(${r},${g},${b},${alpha})`; + } + return color; + } + function normalizeAreas(value) { + const rows = Array.isArray(value) ? value : value && typeof value === 'object' ? Object.entries(value).map(([name, days]) => ({ name, days })) : []; + return rows.map((row, index) => ({ + name: String(row.name || row.area || row.areaName || `Area ${index + 1}`).trim(), + days: number(row.days ?? row.pendencyDays ?? row.refillSpreadDays ?? row.currentDays) + })).filter(row => row.name); + } + function getTrend(previousValue, currentValue, threshold = 15) { + if (!Number.isFinite(previousValue) || !Number.isFinite(currentValue)) return 'flat'; + const delta = currentValue - previousValue; + if (delta >= threshold) return 'up'; + if (delta <= -threshold) return 'down'; + return 'flat'; + } + function isStale(updatedAt, refreshMs, now = Date.now()) { + if (!refreshMs) return false; + if (!updatedAt) return true; + return now - updatedAt > refreshMs; + } + function mergeData(base, patch, aliases = {}) { + if (!patch) return base; + const next = { ...base }; + Object.entries(patch).forEach(([rawKey, value]) => { + if (value === undefined || value === null || rawKey === 'type') return; + const key = aliases[rawKey] || rawKey; + if (key === 'colors' && value && typeof value === 'object') next.colors = { ...(next.colors || {}), ...value }; + else if (key === 'metricFreshnessMinutes' && value && typeof value === 'object') next.metricFreshnessMinutes = { ...(next.metricFreshnessMinutes || {}), ...value }; + else if (key.endsWith('Areas')) next[key] = normalizeAreas(value); + else if (typeof next[key] === 'number') next[key] = number(value, next[key]); + else next[key] = value; + }); + return next; + } + const DEFAULT_COLORS = { + normal: '#4f646e', + stale: '#4f646e', + disabled: '#777777' + }; + + const DEFAULT_UI_COLORS = { + staleText: null, + neutralGradientMid: '#879aa3', + staleLabelFill: null, + normalLabelFill: null, + normalLabelStroke: null, + grid: null, + detailGrid: null, + tick: null, + detailTick: null, + transparent: 'rgba(0,0,0,0)', + white: '#fff', + plotIcon: null + }; + + function drawIcon(ctx, type, x, y, color) { + ctx.save(); ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = 1.25; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; + if (type === 'invoice') { ctx.strokeRect(x - 5, y + 1, 10, 11.5); [4, 7, 10].forEach(o => { ctx.beginPath(); ctx.moveTo(x - 3, y + o); ctx.lineTo(x + 3, y + o); ctx.stroke(); }); } + else if (type === 'person') { ctx.beginPath(); ctx.arc(x, y + 3.8, 2.8, 0, Math.PI * 2); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x - 5, y + 12); ctx.quadraticCurveTo(x, y + 7.6, x + 5, y + 12); ctx.stroke(); } + else if (type === 'calendar') { ctx.strokeRect(x - 5, y + 3, 10, 10); ctx.beginPath(); ctx.moveTo(x - 5, y + 6); ctx.lineTo(x + 5, y + 6); ctx.moveTo(x - 2.8, y + 1); ctx.lineTo(x - 2.8, y + 4); ctx.moveTo(x + 2.8, y + 1); ctx.lineTo(x + 2.8, y + 4); ctx.stroke(); ctx.fillRect(x - 2.8, y + 8, 1.3, 1.3); ctx.fillRect(x + 1.5, y + 8, 1.3, 1.3); } + else if (type === 'deposit') { ctx.strokeRect(x - 5, y + 4, 10, 8); ctx.beginPath(); ctx.moveTo(x - 6, y + 4); ctx.lineTo(x, y + .5); ctx.lineTo(x + 6, y + 4); ctx.moveTo(x - 3, y + 7); ctx.lineTo(x + 3, y + 7); ctx.moveTo(x - 3, y + 10); ctx.lineTo(x + 3, y + 10); ctx.stroke(); } + else if (type === 'hourglass') { ctx.beginPath(); ctx.moveTo(x - 5, y + 1); ctx.lineTo(x + 5, y + 1); ctx.lineTo(x - 5, y + 12.5); ctx.lineTo(x + 5, y + 12.5); ctx.closePath(); ctx.stroke(); } + else { ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x - 5.5, y + 10.5); ctx.lineTo(x + 5.5, y + 10.5); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x, y + 3.5); ctx.lineTo(x, y + 7.2); ctx.stroke(); ctx.beginPath(); ctx.arc(x, y + 9.2, .6, 0, Math.PI * 2); ctx.fill(); } + ctx.restore(); + } + window.TvaControlInternals = { getTrend, isStale, mergeData, normalizeAreas }; + + window.createTvaControl = function createTvaControl({ canvas, container, config = {}, data = {} }) { + if (!canvas && container) canvas = container.querySelector('canvas') || container.appendChild(document.createElement('canvas')); + container = container || canvas.closest('.tva-control-container, .action-chart-container') || canvas.parentElement; + container.classList.add('tva-control-container'); + const init = config && Object.keys(config).length ? config : data.init || {}; + const parameters = init.parameters || []; + const levels = init.warningLevels || []; + if (!parameters.length) throw new Error('createTvaControl requires init.parameters'); + if (!levels.length) throw new Error('createTvaControl requires init.warningLevels'); + + const aliases = init.aliases || {}; + const labels = parameters.map(p => p.label); + const metricKeys = parameters.map(p => p.key); + const metricDatasetIndex = levels.filter(l => l.showAxis !== false).length * 2 + (init.extraAxes || []).length; + const baseState = () => ({ colors: { ...DEFAULT_COLORS, ...(init.colors || {}) }, uiColors: { ...DEFAULT_UI_COLORS, ...(init.uiColors || {}) }, staleAlpha: 0.35, trendThreshold: 15 }); + let state = mergeData(baseState(), data, aliases); + const cssVar = name => getComputedStyle(container).getPropertyValue(name).trim(); + function resolveUiColors() { + const configured = init.uiColors || {}; + const pick = (key, cssName, fallback) => configured[key] || cssVar(cssName) || fallback; + state.colors.normal = init.colors && init.colors.normal ? init.colors.normal : cssVar('--tva-normal-line') || DEFAULT_COLORS.normal; + state.colors.stale = init.colors && init.colors.stale ? init.colors.stale : cssVar('--tva-stale-line') || state.colors.normal; + state.uiColors = { + ...DEFAULT_UI_COLORS, + ...configured, + grid: pick('grid', '--tva-chart-grid', '#222'), + detailGrid: pick('detailGrid', '--tva-chart-detail-grid', '#242424'), + tick: pick('tick', '--tva-axis-text', '#fff'), + detailTick: pick('detailTick', '--tva-detail-axis-text', '#aaa'), + plotIcon: pick('plotIcon', '--tva-plot-icon', configured.white || DEFAULT_UI_COLORS.white), + staleText: pick('staleText', '--tva-stale-text', '#9aa6ac'), + staleLabelFill: pick('staleLabelFill', '--tva-stale-label-fill', 'rgba(2,6,8,.84)'), + normalLabelFill: pick('normalLabelFill', '--tva-normal-label-fill', 'rgba(5,34,30,.62)'), + normalLabelStroke: pick('normalLabelStroke', '--tva-normal-label-stroke', 'rgba(116,137,148,.44)') + }; + } + resolveUiColors(); + let chart = null, mode = 'timeline', criticalBlink = true, stalePhase = 0, staleDirection = 1, previousMetricValues = null; + let updatedAtByKey = Object.fromEntries(metricKeys.map(k => [k, Date.now()])); + if (data.updatedAt) Object.entries(data.updatedAt).forEach(([k, v]) => { const ts = typeof v === 'string' ? Date.parse(v) : number(v, NaN); if (Number.isFinite(ts)) updatedAtByKey[k] = ts; }); + + const controls = document.createElement('div'); controls.className = 'tva-chart-controls'; + const modeOptions = [{ key: 'timeline', label: init.title || 'Timeline' }, ...parameters.filter(p => p.detailMode).map(p => ({ key: p.detailMode, label: p.detailTitle || `${p.label} Area Scan` }))]; + controls.innerHTML = `<button type="button" class="tva-chart-back" hidden>←</button><label class="tva-chart-heading"><span class="sr-only">Chart type</span><select class="tva-chart-mode-select">${modeOptions.map(o => `<option value="${escapeAttr(o.key)}">${escapeAttr(o.label)}</option>`).join('')}</select></label><button type="button" class="tva-chart-fullscreen" title="Fullscreen chart" aria-label="Fullscreen chart"><span class="tva-fullscreen-icon" aria-hidden="true"></span></button>`; + const alertBadge = document.createElement('div'); alertBadge.className = 'tva-alert-badge'; alertBadge.hidden = true; + if (!container.querySelector('.tva-chart-controls')) container.prepend(controls); + if (!container.querySelector('.tva-alert-badge')) container.prepend(alertBadge); + controls.querySelector('.tva-chart-back').onclick = () => switchMode('timeline'); + controls.querySelector('.tva-chart-mode-select').onchange = e => switchMode(e.target.value); + controls.querySelector('.tva-chart-fullscreen').onclick = () => { container.classList.toggle('tva-chart-fullscreen-mode'); syncControls(); chart && chart.resize(); chart && chart.update('none'); }; + + function getValue(p) { return number(state[p.key], number(p.defaultValue)); } + function limit(p, level, side, fallback) { return number(p.thresholds && p.thresholds[`${camel(level.key)}${side}`], fallback); } + function metricValue(p) { + const v = getValue(p); + if (p.scale === 'count10') return clamp(v * 10, -100, 100); + if (p.scale === 'daysCritical') return clamp(v / number(p.scaleBase, 10) * 100, 0, number(p.scaleMax, 165)); + if (p.scale === 'pendency') return v <= number(p.scaleIdeal, 1) ? 0 : clamp(v / number(p.scaleBase, 3) * 100, 0, number(p.scaleMax, 115)); + return v; + } + function values() { return parameters.map(metricValue); } + function isMetricStale(i) { return isStale(updatedAtByKey[parameters[i].key], number(parameters[i].refreshMinutes, 0) * 60000); } + function levelColor(level) { return state.colors[level.key] || state.colors[camel(level.key)] || state.colors.normal; } + function breachedLevel(i, v) { let hit = null; levels.forEach(l => { if (v > limit(parameters[i], l, 'Upper', Infinity) || v < limit(parameters[i], l, 'Lower', -Infinity)) hit = l; }); return hit; } + function staleColor(full = false) { return full ? state.colors.stale : colorWithAlpha(state.colors.stale, number(state.staleAlpha, 0.35)); } + function metricColor(i, v) { if (isMetricStale(i)) return staleColor(false); const l = breachedLevel(i, v); return l ? levelColor(l) : state.colors.normal; } + function formatPoint(p) { const v = getValue(p), d = p.display || {}, dec = Number.isInteger(d.decimals) ? d.decimals : 0; const s = Number.isInteger(v) || dec === 0 ? String(Math.round(v)) : v.toFixed(dec); return `${d.prefix || ''}${s}${d.suffix || ''}`; } + function trend(i) { const v = values(); return getTrend(previousMetricValues && previousMetricValues[i], v[i], number(state.trendThreshold, 15)); } + function zoomBounds(vs) { let min = Math.min(0, ...vs), max = Math.max(0, ...vs); if (min === max) { min -= 10; max += 10; } const pad = Math.max(8, (max - min) * .24); return { min: Math.floor(min - pad), max: Math.ceil(max + pad) }; } + function gradient(ctx) { const v = values(), c0 = metricColor(ctx.p0DataIndex, v[ctx.p0DataIndex]), c1 = metricColor(ctx.p1DataIndex, v[ctx.p1DataIndex]); if (c0 === c1 || !ctx.p0 || !ctx.p1) return c1; const g = ctx.chart.ctx.createLinearGradient(ctx.p0.x, ctx.p0.y, ctx.p1.x, ctx.p1.y); const stale0 = isMetricStale(ctx.p0DataIndex), stale1 = isMetricStale(ctx.p1DataIndex); if (stale0 || stale1) { const base = staleColor(false), full = staleColor(true), width = 0.12, phase = stalePhase; [[0, base], [Math.max(0, phase - width), base], [phase, full], [Math.min(1, phase + width), base], [1, base]].sort((a, b) => a[0] - b[0]).forEach(([stop, color]) => g.addColorStop(stop, color)); return g; } g.addColorStop(0, c0); const l0 = breachedLevel(ctx.p0DataIndex, v[ctx.p0DataIndex]); const l1 = breachedLevel(ctx.p1DataIndex, v[ctx.p1DataIndex]); const dom0 = l0 && number(l0.dominance, 0); const dom1 = l1 && number(l1.dominance, 0); if (dom0) g.addColorStop(dom0, c0); else if (dom1) g.addColorStop(1 - dom1, c1); else g.addColorStop(.5, state.uiColors.neutralGradientMid); g.addColorStop(1, c1); return g; } + + const ambientGlow = init.ambientGlow || {}; + function ambientGlowEnabled() { return ambientGlow.enabled !== false && ambientGlow.enabled !== 0; } + function levelGlowEnabled(level) { return level && level.ambientGlow !== false && level.glow !== false; } + const ambientGlowPlugin = { id: 'tvaAmbientGlow', beforeDraw(c) { if (mode !== 'timeline' || !ambientGlowEnabled()) return; const meta = c.getDatasetMeta(metricDatasetIndex), area = c.chartArea; if (!meta || !area) return; const vs = values(), ctx = c.ctx; ctx.save(); ctx.beginPath(); ctx.rect(0, 0, c.width, c.height); ctx.clip(); meta.data.forEach((pt, i) => { if (isMetricStale(i)) return; const lvl = breachedLevel(i, vs[i]); if (!levelGlowEnabled(lvl)) return; const { x, y } = pt.getProps(['x', 'y'], true), color = lvl.glowColor || levelColor(lvl), radius = number(lvl.glowRadius, number(ambientGlow.radius, 72)), blur = number(lvl.glowBlur, number(ambientGlow.blur, 36)), alpha = number(lvl.glowAlpha, number(ambientGlow.alpha, .16)), spread = radius + blur; const g = ctx.createRadialGradient(x, y, 0, x, y, spread); g.addColorStop(0, colorWithAlpha(color, alpha)); g.addColorStop(.34, colorWithAlpha(color, alpha * .42)); g.addColorStop(.72, colorWithAlpha(color, alpha * .12)); g.addColorStop(1, colorWithAlpha(color, 0)); ctx.fillStyle = g; ctx.fillRect(x - spread, y - spread, spread * 2, spread * 2); }); ctx.restore(); } }; + const zeroAxisPlugin = { id: 'tvaZeroAxis', beforeDatasetsDraw(c) { if (mode !== 'timeline') return; const y = c.scales.y; if (!y) return; const py = y.getPixelForValue(0), ctx = c.ctx; ctx.save(); ctx.strokeStyle = colorWithAlpha(state.colors.normal, .48); ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(0, py); ctx.lineTo(c.width, py); ctx.stroke(); ctx.restore(); } }; + const labelPlugin = { id: 'tvaLabels', afterDatasetsDraw(c) { if (mode !== 'timeline') return; const meta = c.getDatasetMeta(metricDatasetIndex); if (!meta) return; const vs = values(); meta.data.forEach((pt, i) => { const p = parameters[i], stale = isMetricStale(i), lvl = !stale && breachedLevel(i, vs[i]), critical = lvl && lvl.blink !== false && lvl.key !== levels[0].key; const { x, y } = pt.getProps(['x', 'y'], true), gy = y - c.chartArea.top < 52 ? y + 18 : y - 43, text = stale ? 'STALE' : formatPoint(p), ctx = c.ctx; ctx.save(); ctx.globalAlpha = stale ? .72 : critical ? (criticalBlink ? 1 : .38) : 1; ctx.font = 'bold 9px monospace'; const w = Math.max(28, ctx.measureText(text).width + 10), gx = Math.min(Math.max(x - w / 2, c.chartArea.left + 2), c.chartArea.right - w - 2); ctx.fillStyle = stale ? state.uiColors.staleLabelFill : lvl ? colorWithAlpha(levelColor(lvl), .18) : state.uiColors.normalLabelFill; ctx.strokeStyle = stale ? staleColor(false) : lvl ? levelColor(lvl) : state.uiColors.normalLabelStroke; ctx.beginPath(); ctx.rect(gx, gy, w, 31); ctx.fill(); ctx.stroke(); drawIcon(ctx, p.icon || 'warning', gx + w / 2, gy + 3, stale ? state.uiColors.staleText : state.uiColors.plotIcon); ctx.fillStyle = stale ? state.uiColors.staleText : state.uiColors.plotIcon; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(text, gx + w / 2, gy + 24); ctx.restore(); }); } }; + + function thresholdDataset(level, side) { return parameters.map(p => limit(p, level, side, side === 'Upper' ? Infinity : -Infinity)); } + function timelineConfig() { const vs = values(); const datasets = []; levels.filter(l => l.showAxis !== false).forEach(l => { datasets.push({ label: `${l.label || l.key} Upper`, data: thresholdDataset(l, 'Upper'), borderColor: colorWithAlpha(levelColor(l), number(l.axisAlpha, .35)), borderWidth: number(l.axisWidth, 1.6), borderDash: l.axisDash || [4, 5], pointRadius: 0, tension: .4 }); datasets.push({ label: `${l.label || l.key} Lower`, data: thresholdDataset(l, 'Lower'), borderColor: colorWithAlpha(levelColor(l), number(l.axisAlpha, .35)), borderWidth: number(l.axisWidth, 1.6), borderDash: l.axisDash || [4, 5], pointRadius: 0, tension: .4 }); }); (init.extraAxes || []).forEach(axis => datasets.push({ label: axis.label, data: parameters.map(p => p.key === axis.parameterKey ? number(axis.value) : null), borderColor: axis.color || state.colors.normal, borderWidth: number(axis.width, 1.4), borderDash: axis.dash || [3, 5], pointRadius: 0, spanGaps: false })); datasets.push({ label: 'Timeline Metric', data: vs, borderWidth: 3.5, tension: .4, fill: false, borderColor: state.colors.normal, segment: { borderColor: gradient, borderDash: c => isMetricStale(c.p0DataIndex) || isMetricStale(c.p1DataIndex) ? [3, 5] : [] }, pointBorderColor: c => metricColor(c.dataIndex, vs[c.dataIndex]), pointBackgroundColor: c => metricColor(c.dataIndex, vs[c.dataIndex]), pointStyle: c => isMetricStale(c.dataIndex) ? 'circle' : trend(c.dataIndex) === 'flat' ? 'circle' : 'triangle', rotation: c => trend(c.dataIndex) === 'down' ? 180 : 0, pointRadius: c => isMetricStale(c.dataIndex) ? 3 : trend(c.dataIndex) === 'flat' ? 4 : 5.5, pointHoverRadius: 8 }); return { type: 'line', data: { labels, datasets }, options: { responsive: true, maintainAspectRatio: false, layout: { padding: { left: 2, right: 6, top: number(init.topPadding, 34), bottom: 4 } }, onClick: (_e, els) => { const hit = els[0]; if (!hit || hit.datasetIndex !== metricDatasetIndex) return; if (parameters[hit.index].detailMode) switchMode(parameters[hit.index].detailMode); }, plugins: { title: { display: false }, legend: { display: false }, tooltip: { callbacks: { title: items => items.length ? labels[items[0].dataIndex] : '', label: c => c.datasetIndex === metricDatasetIndex ? formatPoint(parameters[c.dataIndex]) : null } } }, scales: { x: { offset: false, border: { display: false }, grid: { color: state.uiColors.grid }, ticks: { color: state.uiColors.tick, font: { weight: 'bold', size: 10 }, callback: (_v, i) => container.classList.contains('tva-chart-fullscreen-mode') ? labels[i] : '' } }, y: { ...zoomBounds(vs), border: { display: false }, grid: { color: c => c.tick.value === 0 ? state.uiColors.transparent : state.uiColors.grid }, ticks: { display: false } } } }, plugins: [ambientGlowPlugin, zeroAxisPlugin, labelPlugin] }; } + function detailParam() { return parameters.find(p => p.detailMode === mode); } + function barConfig() { const p = detailParam(), rows = normalizeAreas(state[p.areaKey]), days = rows.map(r => r.days), dl = p.detailLevels || []; return { type: 'bar', data: { labels: rows.map(r => r.name), datasets: [{ data: days, borderWidth: 1.2, borderRadius: 8, backgroundColor: c => { const lvl = dl.findLast(l => (c.raw || 0) > number(l.above, Infinity)); return lvl ? colorWithAlpha(colorForDetail(lvl), .38) : colorWithAlpha(state.colors.normal, .3); }, borderColor: c => { const lvl = dl.findLast(l => (c.raw || 0) > number(l.above, Infinity)); return lvl ? colorForDetail(lvl) : state.colors.normal; } }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { title: { display: false }, subtitle: { display: true, text: p.detailSubtitle || '', color: state.colors[dl[0] && dl[0].level] || state.colors.normal, font: { size: 10, weight: 'bold' } }, legend: { display: false } }, scales: { x: { grid: { color: state.uiColors.detailGrid }, ticks: { color: state.uiColors.tick, font: { weight: 'bold', size: 10 } } }, y: { min: 0, max: Math.max(...days, ...dl.map(l => number(l.above, 0))) + 1.5, ticks: { color: state.uiColors.detailTick, callback: v => `${v}d` } } } } }; } + function colorForDetail(l) { return state.colors[l.level] || state.colors[camel(l.level)] || state.colors.normal; } + function syncControls() { const select = controls.querySelector('.tva-chart-mode-select'), back = controls.querySelector('.tva-chart-back'), fs = controls.querySelector('.tva-chart-fullscreen'); if (select) select.value = mode; back.hidden = mode === 'timeline'; fs.classList.toggle('is-restore', container.classList.contains('tva-chart-fullscreen-mode')); const vs = values(), active = vs.map((v, i) => isMetricStale(i) ? null : breachedLevel(i, v)).filter(Boolean).sort((a, b) => number(b.priority, 0) - number(a.priority, 0))[0], borderAlert = active && (active.borderBlink || active.blinkBorder || active.borderAlert); alertBadge.hidden = mode !== 'timeline' || !active; alertBadge.innerHTML = active ? `<span class="tva-alert-icon" aria-hidden="true"></span>${active.label || active.key.toUpperCase()}` : ''; alertBadge.style.color = active ? levelColor(active) : ''; container.classList.toggle('tva-border-alert', !!borderAlert); if (borderAlert) container.style.setProperty('--tva-border-alert-color', levelColor(active)); else container.style.removeProperty('--tva-border-alert-color'); } + function render() { if (chart) chart.destroy(); chart = new Chart(canvas.getContext('2d'), mode === 'timeline' ? timelineConfig() : barConfig()); syncControls(); } + let blinkId = null; + let staleSweepId = null; + function hasCriticalBlink() { if (mode !== 'timeline') return false; return values().some((v, i) => { if (isMetricStale(i)) return false; const level = breachedLevel(i, v); return !!(level && level.blink !== false); }); } + function hasStaleSweep() { return mode === 'timeline' && values().some((_v, i) => isMetricStale(i)); } + function syncBlinkTimer() { + const shouldBlink = hasCriticalBlink(); + if (shouldBlink && !blinkId) { + blinkId = setInterval(() => { criticalBlink = !criticalBlink; if (chart && mode === 'timeline') chart.update('none'); }, number(init.blinkMs, 1100)); + } else if (!shouldBlink && blinkId) { + clearInterval(blinkId); blinkId = null; criticalBlink = true; + } + + const shouldSweep = hasStaleSweep(); + if (shouldSweep && !staleSweepId) { + staleSweepId = setInterval(() => { stalePhase += staleDirection * 0.08; if (stalePhase >= 1) { stalePhase = 1; staleDirection = -1; } else if (stalePhase <= 0) { stalePhase = 0; staleDirection = 1; } if (chart && mode === 'timeline') chart.update('none'); }, number(init.staleSweepMs, 140)); + } else if (!shouldSweep && staleSweepId) { + clearInterval(staleSweepId); staleSweepId = null; stalePhase = 0; staleDirection = 1; + } + } + function refresh() { if (!chart) { render(); syncBlinkTimer(); return; } if (mode !== 'timeline') { render(); syncBlinkTimer(); return; } const nextConfig = timelineConfig(); chart.data.labels = nextConfig.data.labels; nextConfig.data.datasets.forEach((dataset, index) => { if (chart.data.datasets[index]) chart.data.datasets[index].data = dataset.data; }); const metricDataset = chart.data.datasets[metricDatasetIndex]; if (metricDataset) metricDataset.data = values(); Object.assign(chart.options.scales.y, zoomBounds(values())); syncControls(); syncBlinkTimer(); chart.update('none'); } + function switchMode(next) { mode = next; render(); syncBlinkTimer(); } + render(); syncBlinkTimer(); + function publicData() { const out = { ...clone(state), updatedAt: clone(updatedAtByKey) }; delete out.uiColors; return out; } + function touchChanged(patch) { const now = Date.now(); Object.entries(patch || {}).forEach(([raw, val]) => { const key = aliases[raw] || raw; if (metricKeys.includes(key) && val !== undefined && val !== null) updatedAtByKey[key] = now; }); if (patch && patch.updatedAt && typeof patch.updatedAt === 'object') Object.entries(patch.updatedAt).forEach(([raw, value]) => { const key = aliases[raw] || raw; const timestamp = typeof value === 'string' ? Date.parse(value) : number(value, NaN); if (metricKeys.includes(key) && Number.isFinite(timestamp)) updatedAtByKey[key] = timestamp; }); } + return { update(patch) { const before = values(); state = mergeData(state, patch, aliases); resolveUiColors(); if (values().some((v, i) => v !== before[i])) previousMetricValues = before; touchChanged(patch); refresh(); }, setData(next) { previousMetricValues = values(); state = mergeData(baseState(), next, aliases); resolveUiColors(); updatedAtByKey = Object.fromEntries(metricKeys.map(k => [k, Date.now()])); refresh(); }, refreshTheme() { resolveUiColors(); render(); syncBlinkTimer(); }, getData() { return publicData(); }, destroy() { if (blinkId) clearInterval(blinkId); if (staleSweepId) clearInterval(staleSweepId); container.classList.remove('tva-border-alert'); container.style.removeProperty('--tva-border-alert-color'); if (chart) chart.destroy(); controls.remove(); alertBadge.remove(); } }; + }; +})();
: asapien/superpulse