# Waltermart Monitoring (MVC)

Node/Express app with two hands-free screens for every active Waltermart mall (35 malls, 69 TRs):

- **Portfolio summary** (`/summary`): executive view. A fixed KPI band, the top exception, a cycling
  "Needs attention" list, status-coloured mall tiles and a rotating mall with operating and monitoring
  health, open issues and its last 30 days.
- **Mall display** (`/kiosk`): the public screen inside each mall. It rotates through every mall in
  alphabetical order, with one plain-language system status, a power-flow scene, solar contribution,
  charts, weather and everyday equivalents. No equipment counts, alarms or red.

The browser only talks to this server. solarops and OpenWeather are called server-side, so secrets
never reach the page.

## Run on Windows (one click)

Double-click `start-kiosk.bat`. It checks Node.js, creates `.env` on the first run (paste the solarops
secret into it), installs packages, starts the server (or reuses a running one) and opens the mall
display full screen. `start-kiosk.bat window | summary | server | stop` open the display in a normal
window, open the portfolio summary, start only the server, or stop it. Press Alt+F4 to leave full screen.

## Run with Docker

`.env` (solarops secret) and `config/config.json` (weather key) are not copied into the image; they are
supplied when the container starts. Copy `.env.example` to `.env` and fill in `SOLAROPS_HMAC_SECRET` first.

```sh
docker compose up -d --build   # start, rebuilding after code changes; http://localhost:3000/kiosk
docker compose logs -f         # server log
docker compose down            # stop
```

## Run locally

```sh
npm install
cp .env.example .env                               # then set SOLAROPS_HMAC_SECRET
cp config/config.example.json config/config.json   # optional: OpenWeather key, tariff
npm start                                          # or: npm run dev  (restarts on file changes)
```

- Portfolio summary: http://localhost:3000/summary
- Mall display: http://localhost:3000/kiosk (`?mall=antipolo` starts on a given mall)
- Tour: http://localhost:3000/tour shows each mall's summary for a minute, then its mall display for a
  minute, then the next mall, in the summary's order (outages first, then reduced, no data, normal) (`?mall=antipolo` to start there, `?seconds=30` to change the time per view)

## Settings

| Setting | Where | Notes |
|---|---|---|
| `SOLAROPS_CLIENT_ID`, `SOLAROPS_CLIENT_KEY` | `.env` | This app's own solarops key (`waltermart` in the API's `API_CLIENT_KEYS`). With both set, requests are signed as this app and `SOLAROPS_HMAC_SECRET` is not used |
| `SOLAROPS_HMAC_SECRET` | `.env` | The old shared secret (`API_HMAC_SECRET` from `solaredge_api/.env`), only until the own key is set |
| `SOLAROPS_BASE_URL` | `.env` | Default `https://solarops.nsr.com.ph/solaredge-api` |
| `OPENWEATHER_KEY` / `openWeatherKey` | `.env` / `config.json` | Weather tile and night view. Without it the weather tile shows "unavailable" |
| `TARIFF_PHP_PER_KWH` / `tariffPhpPerKwh` | `.env` / `config.json` | Optional. When set, the summary shows ₱ savings; otherwise CO₂ avoided |
| `DATA_UPDATES_AT` | `.env` | Default `01:00,10:00,15:00`. When solarops refreshes Waltermart energy (its 01:00 sync plus `ENERGY_REFRESH_AT` in solaredge_api); the screens show the next one. Keep the two in step |
| `CACHE_CLEAR_TOKEN` | `.env` | Optional. Token for `POST /api/cache/clear`; empty turns that endpoint off |
| `CACHE_CLEAR_COOLDOWN_SEC` | `.env` | Default 300. Minimum time between two cache clears |
| `BIND_ADDR` | `.env` | Default `127.0.0.1` (compose): only nginx on the server reaches port 3000. `0.0.0.0` only with a firewall |
| `RATE_LIMIT_PER_MIN` | `.env` | Default 300 requests per minute per client IP on `/api` |
| `CSP_MODE` | `.env` | `enforce` (default) or `report-only`, the rollback switch if a browser blocks something |
| `TRUST_PROXY` | `.env` | Default `loopback, linklocal, uniquelocal`: nginx via Docker's private network |
| `PORT`, `timezone` | `.env` / `config.json` | 3000, Asia/Manila |

On a server, put the weather key in `.env` as `OPENWEATHER_KEY`: `config/config.json` is not in git, so a
fresh checkout has none.

## Where the data comes from

Everything SolarEdge comes from the team's **solarops API** (V2-shaped `/sites` paths, HMAC-signed),
never from SolarEdge directly. solarops serves a daily copy, so the newest complete day is usually
**yesterday**; both screens show that date ("Yesterday", "Data for Oct 25"). They switch to "Today" by
themselves once solarops has today's data.

| Data | solarops endpoint | Cache |
|---|---|---|
| Which malls and TRs, kWp, install date | `/sites` (name contains "Waltermart", ACTIVE) | 10 min (fleet) |
| Daily energy, last 30 days, month to date | `/sites/{id}/energy?resolution=DAY` | 30 min |
| Hourly power curve (newest day that has it) | `/sites/{id}/power?resolution=HOUR` | 30 min |
| Production, consumption, solar share (last 30 days) | `/sites/{id}/overview` | 30 min |
| Inverters, meters, gateways in service | `/sites/{id}/devices` (active units only) | 6 h |
| Open issues | `/sites/{id}/alerts` (not CLOSED) | 30 min |
| CO₂ avoided since installation | `/sites/{id}/environmental-benefits` | 6 h |
| Weather, sunrise and sunset | OpenWeatherMap, at the TR's location (`/sites/{id}`) | 1 h |

TRs are grouped into malls by name ("Waltermart Altaraza - TR1 (124.16 kWp)" → Altaraza, TR1).

### How a mall's status is worked out

- **Data unavailable** (gray): no TR has a value for the data day.
- **Major outage** (red): a TR is under 80 % available. A TR that produced under 5 % of the fleet's median
  yield counts as 0 % available; otherwise availability is the share of its inverters without an open
  equipment alert of SolarEdge impact 5 or more.
- **Reduced capacity** (amber): the mall is under 98 % available.
- **Partial connection** (amber): a TR is missing for the data day, or has an open communication alert of
  impact 4 or more.
- **Normal** (green): none of the above. Lower-impact alerts (single panels, fans) don't change the status.

"vs Fleet" compares the mall's kWh/kWp with the median of all TRs that day. "Lost" is the energy a faulty
TR made below that median. The mall display maps these to its four public messages: normal, monitoring
data unavailable (partial), reduced capacity (outage or reduced), data unavailable.

## Structure

```
server.js            starts the app and loads the fleet once
app.js               Express setup: EJS views, static files, routes, error handling
config/              index.js (config.json + .env + environment)
routes/              pages.js (HTML) and api.js (JSON, mounted at /api)
controllers/         fleetController (fleet + weather), pageController, cacheController
models/
  fleetModel         solarops -> malls, status, issues, charts (cached)
  weatherModel       OpenWeather per mall (cached)
services/            solarOps (HMAC-signed client), openWeather
lib/                 cache, time, http helpers, security (headers/CSP, rate limit, log redaction)
views/pages/         summary.ejs, kiosk.ejs, error.ejs
public/css/          summary.css, kiosk.css (base.css for the error page)
public/js/pages/     summary.js, kiosk.js, tour.js (public/js/config.js reads the page settings)
public/fonts/        self-hosted Outfit and JetBrains Mono (OFL)
test/                node:test suite (npm test), runs against a fake solarops
```

## API

| Endpoint | Returns |
|---|---|
| `GET /api/fleet` | `{ malls: [...], dataDay, today, fleetYield, dates, builtAt, tariffPhpPerKwh }` (no SolarEdge IDs) |
| `GET /api/malls/:mall/weather` | `{ tempC, humidity, condition, description, clouds, sunrise, sunset }` |
| `POST /api/cache/clear` | drops the in-memory cache; needs header `X-Admin-Token: <CACHE_CLEAR_TOKEN>` (403 without it, off when the token is unset; 429 within the cooldown) |
| `GET /healthz` | `{ ok: true }` for the Docker health check and uptime monitors; no upstream calls |
| `POST /csp-report` | browsers' CSP violation reports (8 KB max, 30 a minute), logged as `[csp]` lines |

All pages and `/api` are public and read-only by design (public mall screens); the only state-changing call
is the token-protected cache clear. `/api` is limited to `RATE_LIMIT_PER_MIN` requests per minute per IP.
Errors return fixed messages; details go only to the server log, with secrets redacted.

## Security

Hardened against the NetSolar Development and Hardening Manual v1.8; the run record, server steps and nginx
snippet are in [docs/security/](docs/security/). `npm test` covers headers and CSP, input validation, the admin
token, the rate limit and log redaction. `.github/workflows/security.yml` runs tests, npm audit, gitleaks,
Semgrep, hadolint and Trivy on every pull request.

## Screens

Both pages fill the screen exactly with no scrolling and need no input. Sizes are in `rem`, and the root
font size follows the viewport, so they scale from a phone to a 4K TV. Landscape and portrait layouts are
both supported. The summary rotates every 10 s, the mall display every 15 s, and both reload data every
10 minutes.
