Compare commits
3 Commits
a27acf9357
...
45cde10a21
| Author | SHA1 | Date | |
|---|---|---|---|
| 45cde10a21 | |||
| 55d6f8be7c | |||
| 28345295b6 |
@@ -0,0 +1,179 @@
|
|||||||
|
# Health Routine – Package Scanner
|
||||||
|
|
||||||
|
> ALWAYS UPDATE THIS FILE AFTER MAKING CHANGES
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
A single-page web app (`index.html`) used internally by Health Routine staff to scan **package** barcodes.
|
||||||
|
A user selects their name, scans/types a code, and the result is looked up via a webhook and appended to a table.
|
||||||
|
Runs in any browser — designed for phones, tablets, and desktop.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
```
|
||||||
|
index.html — the entire app (HTML + CSS + JS, no build step)
|
||||||
|
logo.png — Health Routine brand logo (used in the header)
|
||||||
|
agent.md — this file
|
||||||
|
start — bash script that launches live-server on localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
## Design
|
||||||
|
Colors are pulled directly from healthroutine.de's CSS variables:
|
||||||
|
|
||||||
|
| Token | Hex | Usage |
|
||||||
|
|------------------|-----------|-------------------------------------|
|
||||||
|
| `--primary` | `#005f5a` | Controls bar, table header, buttons |
|
||||||
|
| `--primary-dark` | `#004845` | Hover states |
|
||||||
|
| `--primary-light`| `#e0f0ef` | Row hover, badge backgrounds |
|
||||||
|
| `--bg` | `#f7f7fa` | Page background |
|
||||||
|
| `--card` | `#eaeaf2` | Alternating table rows |
|
||||||
|
| `--sage` | `#82917d` | (brand footer green, available) |
|
||||||
|
| `--error` | `#c71b1b` | Error states |
|
||||||
|
| `--success` | `#15803d` | Success toasts |
|
||||||
|
|
||||||
|
Font: system font stack (`-apple-system`, `Segoe UI`, etc.)
|
||||||
|
|
||||||
|
## Webhook
|
||||||
|
|
||||||
|
**Base URL:** `https://brandize.app.n8n.cloud/webhook/e0268b0f-4935-49ba-bfdf-1c0ee01d3b9d`
|
||||||
|
|
||||||
|
### GET — load users
|
||||||
|
Called once on page load to populate the user dropdown.
|
||||||
|
|
||||||
|
```
|
||||||
|
GET <base_url>
|
||||||
|
Authorization: Basic <base64>
|
||||||
|
```
|
||||||
|
|
||||||
|
Response — n8n may return a JSON array, a single object, or NDJSON.
|
||||||
|
All three formats are handled by `parseJson()` (see below).
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{ "Name": "Oliver", "id": 1, "createdAt": "...", "updatedAt": "..." },
|
||||||
|
{ "Name": "Luka", "id": 2, ... },
|
||||||
|
{ "Name": "Benni", "id": 3, ... }
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### POST — submit scan
|
||||||
|
Called when the user presses Enter in the scan input.
|
||||||
|
|
||||||
|
```
|
||||||
|
POST <base_url>
|
||||||
|
Authorization: Basic <base64>
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{ "user": "Oliver", "code": "SCANNED_BARCODE_STRING" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Success response:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Christa Gierdahl, Christa Gierdahl",
|
||||||
|
"producttag": "0-HR-Nail-Care-5",
|
||||||
|
"batch": "BATCH/25-11-14/06173",
|
||||||
|
"country": "DE"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Error response (non-2xx **or** 200 with error field):
|
||||||
|
```json
|
||||||
|
{ "error": "Human-readable error description" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Fields mapped to table columns:
|
||||||
|
- `country` → **Country** (teal pill badge)
|
||||||
|
- `name` → **Name**
|
||||||
|
- `producttag` → **Tag** (monospace pill, truncated with tooltip on hover)
|
||||||
|
- `batch` → received but not displayed in the table
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
The webhook requires HTTP Basic Auth.
|
||||||
|
|
||||||
|
- On `401` (GET or POST) a modal appears asking for username + password.
|
||||||
|
- Credentials are saved to a **cookie** (`hr_auth`, 30-day expiry, `SameSite=Strict`) so the user is not prompted again.
|
||||||
|
- On page load, the cookie is read and credentials restored before the first network call.
|
||||||
|
- If the modal is triggered again (e.g. wrong password), the fields are **pre-filled** from the cookie and focus lands on the password field for quick confirmation.
|
||||||
|
- `saveCreds(user, pass)` — JSON-stringifies, URI-encodes, base64-encodes, writes cookie.
|
||||||
|
- `loadCredsFromCookie()` — reverses that; returns `{ user, pass }` or `null`.
|
||||||
|
- `clearCredsCookie()` — available but not exposed in UI (call from browser console if needed).
|
||||||
|
|
||||||
|
### Error handling (POST)
|
||||||
|
Two cases:
|
||||||
|
1. **Non-2xx response** — body is parsed; if `errData.error` exists it is shown verbatim; otherwise a generic `HTTP <status>` message is shown.
|
||||||
|
2. **200 response with `error` field** — treated as failure: `item.error` is displayed, row is *not* added to the table.
|
||||||
|
|
||||||
|
Errors appear in the **persistent status banner** (red, no auto-dismiss) and the scan input is selected so the user can re-scan or correct the code.
|
||||||
|
|
||||||
|
### NDJSON / response format
|
||||||
|
n8n sometimes returns multiple items as NDJSON (one JSON object per line) instead of a proper JSON array. `parseJson(res)` handles all three formats:
|
||||||
|
1. Standard JSON array `[...]`
|
||||||
|
2. Single JSON object `{...}` — passed through as-is
|
||||||
|
3. NDJSON — split on `\n`, each line parsed individually, returned as an array
|
||||||
|
|
||||||
|
## UI layout
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────┐
|
||||||
|
│ [HR logo] Health Routine | Package Scanner │ ← white brand bar
|
||||||
|
├─────────────────────────────────────────────────────┤
|
||||||
|
│ [▥ SCAN HERE_____________] [User ▾] [✕ Clear] │ ← teal controls bar
|
||||||
|
├─────────────────────────────────────────────────────┤
|
||||||
|
│ SCAN LOG 3 scans ● │
|
||||||
|
│ ┌───────────────────────────────────────────────┐ │
|
||||||
|
│ │ COUNTRY │ NAME │ TAG │ │ ← sticky header
|
||||||
|
│ ├──────────┼───────────────────────┼─────────────┤ │
|
||||||
|
│ │ DE │ Christa Gierdahl │ 0-HR-Nail… │ │ ← newest row on top
|
||||||
|
│ │ AT │ ... │ ... │ │
|
||||||
|
│ │ scrollable area │ │ │
|
||||||
|
│ └───────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
On mobile (< 620 px): scan input goes full-width on its own row; user dropdown and clear button share the row below.
|
||||||
|
|
||||||
|
## Key behaviours
|
||||||
|
- **On load**: cookie credentials restored → GET webhook fires → dropdown populated → scan input auto-focused
|
||||||
|
- **Enter key**: trims input → duplicate check → clears input **immediately** → adds pending row → pushed onto FIFO queue → `drainQueue()` starts if idle
|
||||||
|
- **Clear button**: empties the table, clears the scan input, resets the scan counter
|
||||||
|
- **No user selected**: red toast + highlighted dropdown; does not submit
|
||||||
|
- **401 on any request**: modal prompts for credentials (pre-filled from cookie), saves to cookie, retries original call
|
||||||
|
- **Webhook error**: `error` field shown verbatim in persistent red banner; input selected for re-scan
|
||||||
|
- **Network error**: dismissing error banner; input selected so user can retry
|
||||||
|
- **Dropdown error state**: tapping/focusing the dropdown while it shows an error re-triggers `loadUsers()`
|
||||||
|
- **NDJSON/array/object**: `parseJson()` normalises all response formats from n8n
|
||||||
|
- **Duplicate scan**: `isDuplicate(code)` queries `.col-code` cells (present on pending, resolved, and error rows) before enqueuing
|
||||||
|
- **Scan queue**: `scanQueue[]` is a FIFO array of `{ code, user, rowEl }`. `drainQueue()` runs sequentially in the background — one `processItem()` at a time. Scans can be added faster than the webhook responds; each gets its own pending row immediately
|
||||||
|
- **Pending row**: shows a spinner + `Processing… <code>` while the item is in-flight; replaced in-place by the resolved row or an error row
|
||||||
|
- **Error row**: red background, shows the error message and the raw code; code is still in `.col-code` so it cannot be re-scanned
|
||||||
|
- **Queue pill**: teal badge next to the scan counter showing `N pending`; hidden when queue is empty
|
||||||
|
- **Auth mid-queue**: if `processItem` gets 401, it returns `"auth"` to `drainQueue`, which pauses (`queueBusy = false`), shows the auth modal with `drainQueue` as the retry callback — queue resumes from the same item after login
|
||||||
|
- **Clear**: also drains `scanQueue` and resets `queueBusy`
|
||||||
|
|
||||||
|
## Scan flow (sequence)
|
||||||
|
```
|
||||||
|
Enter key
|
||||||
|
└─ enqueue(code)
|
||||||
|
├─ validation (user selected? duplicate?)
|
||||||
|
├─ scanInput.value = "" ← immediate clear
|
||||||
|
├─ addPendingRow(code) ← spinner row in table
|
||||||
|
└─ scanQueue.push(...) ← add to FIFO
|
||||||
|
└─ drainQueue() if idle
|
||||||
|
└─ processItem() loop
|
||||||
|
├─ fetch POST webhook
|
||||||
|
├─ resolveRow() ← replace spinner with result
|
||||||
|
└─ rowError() ← replace spinner with error
|
||||||
|
```
|
||||||
|
|
||||||
|
## Table columns (DOM)
|
||||||
|
| Visible | Header | CSS class | Content |
|
||||||
|
|---------|--------|-----------|---------|
|
||||||
|
| ✓ | Country | — | `item.country` wrapped in teal badge |
|
||||||
|
| ✓ | Name | `name-cell` | `item.name` |
|
||||||
|
| ✓ | Tag | — | `item.producttag` in monospace pill |
|
||||||
|
| ✗ | Code | `col-code` | Raw scanned code (`display:none`), used for duplicate detection |
|
||||||
|
|
||||||
|
## How to run
|
||||||
|
Open `index.html` directly in a browser (`file://`) — no server needed for local use.
|
||||||
|
Or run the `start` script for live-reload during development:
|
||||||
|
```bash
|
||||||
|
./start # requires Node.js; installs live-server globally if missing
|
||||||
|
```
|
||||||
+306
-61
@@ -6,7 +6,7 @@
|
|||||||
name="viewport"
|
name="viewport"
|
||||||
content="width=device-width, initial-scale=1.0, user-scalable=no"
|
content="width=device-width, initial-scale=1.0, user-scalable=no"
|
||||||
/>
|
/>
|
||||||
<title>Health Routine – Product Scanner</title>
|
<title>Health Routine – Package Scanner</title>
|
||||||
<style>
|
<style>
|
||||||
*,
|
*,
|
||||||
*::before,
|
*::before,
|
||||||
@@ -396,6 +396,95 @@
|
|||||||
width: 200px;
|
width: 200px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Hidden code column — stores raw scan code for duplicate checking */
|
||||||
|
.col-code {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Queue status pill */
|
||||||
|
.queue-pill {
|
||||||
|
background: var(--primary-light);
|
||||||
|
color: var(--primary);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
padding: 2px 11px;
|
||||||
|
border-radius: 99px;
|
||||||
|
letter-spacing: 0.2px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
.queue-pill.hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pending row */
|
||||||
|
.row-pending td {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-cell {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 11px 18px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-spinner {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
border: 2px solid rgba(0, 95, 90, 0.2);
|
||||||
|
border-top-color: var(--primary);
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: spin 0.7s linear infinite;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-label {
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-code {
|
||||||
|
font-family: "Courier New", monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text);
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Error row */
|
||||||
|
.row-error td {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-cell {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 11px 18px;
|
||||||
|
background: var(--error-bg);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-icon {
|
||||||
|
color: var(--error);
|
||||||
|
font-weight: 700;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-msg {
|
||||||
|
color: var(--error);
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-code {
|
||||||
|
font-family: "Courier New", monospace;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--error);
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
|
||||||
tbody tr {
|
tbody tr {
|
||||||
border-bottom: 1px solid var(--card);
|
border-bottom: 1px solid var(--card);
|
||||||
animation: rowIn 0.28s ease-out;
|
animation: rowIn 0.28s ease-out;
|
||||||
@@ -808,7 +897,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<span class="brand-name">Health Routine</span>
|
<span class="brand-name">Health Routine</span>
|
||||||
<div class="brand-divider"></div>
|
<div class="brand-divider"></div>
|
||||||
<span class="brand-subtitle">Product Scanner</span>
|
<span class="brand-subtitle">Package Scanner</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Controls bar -->
|
<!-- Controls bar -->
|
||||||
@@ -871,7 +960,20 @@
|
|||||||
<main>
|
<main>
|
||||||
<div class="table-meta">
|
<div class="table-meta">
|
||||||
<span class="table-label">Scan Log</span>
|
<span class="table-label">Scan Log</span>
|
||||||
<span class="count-pill zero" id="countPill">0 scans</span>
|
<div style="display: flex; align-items: center; gap: 8px">
|
||||||
|
<span class="queue-pill hidden" id="queuePill">
|
||||||
|
<span
|
||||||
|
class="pending-spinner"
|
||||||
|
style="
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-width: 1.5px;
|
||||||
|
"
|
||||||
|
></span>
|
||||||
|
<span id="queuePillText">0 pending</span>
|
||||||
|
</span>
|
||||||
|
<span class="count-pill zero" id="countPill">0 scans</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="table-wrapper" id="tableWrapper">
|
<div class="table-wrapper" id="tableWrapper">
|
||||||
@@ -881,6 +983,7 @@
|
|||||||
<th>Country</th>
|
<th>Country</th>
|
||||||
<th>Name</th>
|
<th>Name</th>
|
||||||
<th>Tag</th>
|
<th>Tag</th>
|
||||||
|
<th class="col-code">Code</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="tableBody"></tbody>
|
<tbody id="tableBody"></tbody>
|
||||||
@@ -898,7 +1001,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="empty-title">No scans yet</div>
|
<div class="empty-title">No scans yet</div>
|
||||||
<div class="empty-hint">
|
<div class="empty-hint">
|
||||||
Select a user, then scan or type a product code and
|
Select a user, then scan or type a package code and
|
||||||
press Enter
|
press Enter
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -975,10 +1078,12 @@
|
|||||||
const WEBHOOK =
|
const WEBHOOK =
|
||||||
"https://brandize.app.n8n.cloud/webhook/e0268b0f-4935-49ba-bfdf-1c0ee01d3b9d";
|
"https://brandize.app.n8n.cloud/webhook/e0268b0f-4935-49ba-bfdf-1c0ee01d3b9d";
|
||||||
|
|
||||||
// ── State ───────────────────────────────────────────────────────────────
|
// ── State ───────────────────────────────────────────────────────────────────
|
||||||
let creds = null; // { user, pass }
|
let creds = null; // { user, pass }
|
||||||
let pendingAuthCb = null; // function to retry after auth
|
let pendingAuthCb = null; // function to retry after auth
|
||||||
let scanCount = 0;
|
let scanCount = 0;
|
||||||
|
const scanQueue = []; // { code, user, rowEl } — FIFO
|
||||||
|
let queueBusy = false; // true while drainQueue is running
|
||||||
|
|
||||||
// ── DOM refs ─────────────────────────────────────────────────────────────
|
// ── DOM refs ─────────────────────────────────────────────────────────────
|
||||||
const scanInput = document.getElementById("scanInput");
|
const scanInput = document.getElementById("scanInput");
|
||||||
@@ -986,6 +1091,8 @@
|
|||||||
const tableBody = document.getElementById("tableBody");
|
const tableBody = document.getElementById("tableBody");
|
||||||
const emptyState = document.getElementById("emptyState");
|
const emptyState = document.getElementById("emptyState");
|
||||||
const countPill = document.getElementById("countPill");
|
const countPill = document.getElementById("countPill");
|
||||||
|
const queuePill = document.getElementById("queuePill");
|
||||||
|
const queuePillText = document.getElementById("queuePillText");
|
||||||
const banner = document.getElementById("statusBanner");
|
const banner = document.getElementById("statusBanner");
|
||||||
const authModal = document.getElementById("authModal");
|
const authModal = document.getElementById("authModal");
|
||||||
const authUser = document.getElementById("authUser");
|
const authUser = document.getElementById("authUser");
|
||||||
@@ -994,6 +1101,51 @@
|
|||||||
const modalError = document.getElementById("modalError");
|
const modalError = document.getElementById("modalError");
|
||||||
const toast = document.getElementById("toast");
|
const toast = document.getElementById("toast");
|
||||||
|
|
||||||
|
// ── Cookie helpers ────────────────────────────────────────────────────────
|
||||||
|
function saveCreds(user, pass) {
|
||||||
|
const val = btoa(
|
||||||
|
encodeURIComponent(JSON.stringify({ user, pass })),
|
||||||
|
);
|
||||||
|
document.cookie = `hr_auth=${val}; max-age=${30 * 24 * 3600}; SameSite=Strict; path=/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadCredsFromCookie() {
|
||||||
|
const match = document.cookie.match(
|
||||||
|
/(?:^|;\s*)hr_auth=([^;]+)/,
|
||||||
|
);
|
||||||
|
if (match) {
|
||||||
|
try {
|
||||||
|
return JSON.parse(decodeURIComponent(atob(match[1])));
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearCredsCookie() {
|
||||||
|
document.cookie = "hr_auth=; max-age=0; path=/";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── JSON parser (handles array, single object, and NDJSON) ───────────────
|
||||||
|
async function parseJson(res) {
|
||||||
|
const text = await res.text();
|
||||||
|
// Standard JSON (array or object)
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(text);
|
||||||
|
return parsed;
|
||||||
|
} catch (_) {}
|
||||||
|
// NDJSON — n8n sometimes returns one object per line
|
||||||
|
try {
|
||||||
|
const lines = text
|
||||||
|
.trim()
|
||||||
|
.split("\n")
|
||||||
|
.filter((l) => l.trim());
|
||||||
|
if (lines.length > 0) {
|
||||||
|
return lines.map((l) => JSON.parse(l));
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
throw new Error("Could not parse server response");
|
||||||
|
}
|
||||||
|
|
||||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||||
function esc(str) {
|
function esc(str) {
|
||||||
return String(str ?? "")
|
return String(str ?? "")
|
||||||
@@ -1052,10 +1204,16 @@
|
|||||||
function needAuth(retryCb) {
|
function needAuth(retryCb) {
|
||||||
pendingAuthCb = retryCb;
|
pendingAuthCb = retryCb;
|
||||||
modalError.style.display = "none";
|
modalError.style.display = "none";
|
||||||
authUser.value = "";
|
// Pre-fill from saved cookie so user only needs to confirm
|
||||||
authPass.value = "";
|
const saved = loadCredsFromCookie();
|
||||||
|
authUser.value = saved?.user || "";
|
||||||
|
authPass.value = saved?.pass || "";
|
||||||
authModal.classList.remove("hidden");
|
authModal.classList.remove("hidden");
|
||||||
setTimeout(() => authUser.focus(), 50);
|
// Focus password if username already filled, otherwise username
|
||||||
|
setTimeout(
|
||||||
|
() => (saved ? authPass.focus() : authUser.focus()),
|
||||||
|
50,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function cancelAuth() {
|
function cancelAuth() {
|
||||||
@@ -1075,6 +1233,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
creds = { user: u, pass: p };
|
creds = { user: u, pass: p };
|
||||||
|
saveCreds(u, p); // persist to cookie
|
||||||
authBtn.classList.add("loading");
|
authBtn.classList.add("loading");
|
||||||
authBtn.disabled = true;
|
authBtn.disabled = true;
|
||||||
modalError.style.display = "none";
|
modalError.style.display = "none";
|
||||||
@@ -1120,7 +1279,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await parseJson(res);
|
||||||
buildDropdown(data);
|
buildDropdown(data);
|
||||||
hideBanner();
|
hideBanner();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -1149,14 +1308,35 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Submit Scan ──────────────────────────────────────────────────────────
|
// ── Duplicate check ──────────────────────────────────────────────────────
|
||||||
async function submitScan(code) {
|
// Checks both resolved rows and pending rows (all have .col-code)
|
||||||
|
function isDuplicate(code) {
|
||||||
|
for (const cell of tableBody.querySelectorAll(".col-code")) {
|
||||||
|
if (cell.textContent === code) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Queue pill ──────────────────────────────────────────────────────────
|
||||||
|
function updateQueuePill() {
|
||||||
|
const n = scanQueue.length;
|
||||||
|
if (n > 0) {
|
||||||
|
queuePillText.textContent =
|
||||||
|
n + (n === 1 ? " pending" : " pending");
|
||||||
|
queuePill.classList.remove("hidden");
|
||||||
|
} else {
|
||||||
|
queuePill.classList.add("hidden");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Enqueue (called immediately on Enter) ──────────────────────────────
|
||||||
|
function enqueue(raw) {
|
||||||
|
const code = raw.trim();
|
||||||
|
if (!code) return;
|
||||||
|
|
||||||
const user = userSelect.value;
|
const user = userSelect.value;
|
||||||
if (!user) {
|
if (!user) {
|
||||||
showToast("Please select a user first!", "fail");
|
showToast("Please select a user first!", "fail");
|
||||||
userSelect.focus();
|
|
||||||
// Short shake animation on the select
|
|
||||||
userSelect.style.transition = "none";
|
|
||||||
userSelect.style.outline = "2px solid rgba(255,80,80,0.8)";
|
userSelect.style.outline = "2px solid rgba(255,80,80,0.8)";
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
userSelect.style.outline = "";
|
userSelect.style.outline = "";
|
||||||
@@ -1164,76 +1344,138 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
showBanner("Looking up product…", "loading");
|
if (isDuplicate(code)) {
|
||||||
|
showToast("⚠️ Already scanned: " + code, "fail", 4000);
|
||||||
|
scanInput.select();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear input immediately so the next scan can happen right away
|
||||||
|
scanInput.value = "";
|
||||||
|
scanInput.focus();
|
||||||
|
hideBanner();
|
||||||
|
|
||||||
|
// Add a pending row to the table (also registers code for dupe detection)
|
||||||
|
const rowEl = addPendingRow(code);
|
||||||
|
|
||||||
|
// Push onto queue
|
||||||
|
scanQueue.push({ code, user, rowEl });
|
||||||
|
updateQueuePill();
|
||||||
|
|
||||||
|
// Kick off the queue processor if it isn’t running already
|
||||||
|
if (!queueBusy) drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Queue drain (processes items sequentially in the background) ────────
|
||||||
|
async function drainQueue() {
|
||||||
|
if (queueBusy) return;
|
||||||
|
queueBusy = true;
|
||||||
|
while (scanQueue.length > 0) {
|
||||||
|
const item = scanQueue[0]; // peek — only shift after handling
|
||||||
|
const result = await processItem(item);
|
||||||
|
if (result === "auth") {
|
||||||
|
// Credentials needed — pause queue, resume after login
|
||||||
|
queueBusy = false;
|
||||||
|
needAuth(drainQueue);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
scanQueue.shift();
|
||||||
|
updateQueuePill();
|
||||||
|
}
|
||||||
|
queueBusy = false;
|
||||||
|
updateQueuePill();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Process one queued item ────────────────────────────────────────────
|
||||||
|
async function processItem({ code, user, rowEl }) {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(WEBHOOK, {
|
const res = await fetch(WEBHOOK, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: getHeaders(true),
|
headers: getHeaders(true),
|
||||||
body: JSON.stringify({ user, code: code.trim() }),
|
body: JSON.stringify({ user, code }),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) return "auth"; // signal caller to pause
|
||||||
hideBanner();
|
|
||||||
// Restore input so it's not lost
|
|
||||||
scanInput.value = code;
|
|
||||||
needAuth(() => submitScan(code));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
showBanner(
|
let errMsg = `Scan failed (HTTP ${res.status})`;
|
||||||
`Scan failed (HTTP ${res.status}).`,
|
try {
|
||||||
"error",
|
const errData = await parseJson(res);
|
||||||
5000,
|
if (errData?.error) errMsg = errData.error;
|
||||||
);
|
} catch (_) {}
|
||||||
scanInput.select();
|
rowError(rowEl, errMsg);
|
||||||
return;
|
return "ok";
|
||||||
}
|
}
|
||||||
|
|
||||||
const item = await res.json();
|
const item = await parseJson(res);
|
||||||
hideBanner();
|
if (item?.error) {
|
||||||
addRow(item);
|
rowError(rowEl, item.error);
|
||||||
showToast(
|
return "ok";
|
||||||
"✓ Added: " + (item.name || item.producttag || code),
|
}
|
||||||
"ok",
|
|
||||||
);
|
|
||||||
|
|
||||||
// Clear input and keep focus for next scan
|
resolveRow(rowEl, item);
|
||||||
scanInput.value = "";
|
return "ok";
|
||||||
scanInput.focus();
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
showBanner(
|
rowError(rowEl, "Network error – could not reach server");
|
||||||
"Network error – scan not recorded.",
|
return "ok";
|
||||||
"error",
|
|
||||||
5000,
|
|
||||||
);
|
|
||||||
scanInput.select();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Table Row ────────────────────────────────────────────────────────────
|
// ── Table rows ────────────────────────────────────────────────────────────────
|
||||||
function addRow(item) {
|
function addPendingRow(code) {
|
||||||
emptyState.style.display = "none";
|
emptyState.style.display = "none";
|
||||||
|
const tr = document.createElement("tr");
|
||||||
|
tr.className = "row-pending";
|
||||||
|
tr.innerHTML = `
|
||||||
|
<td colspan="3" class="pending-cell">
|
||||||
|
<span class="pending-spinner"></span>
|
||||||
|
<span class="pending-label">Processing…</span>
|
||||||
|
<span class="pending-code">${esc(code)}</span>
|
||||||
|
</td>
|
||||||
|
<td class="col-code">${esc(code)}</td>
|
||||||
|
`;
|
||||||
|
tableBody.insertBefore(tr, tableBody.firstChild);
|
||||||
|
return tr;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveRow(rowEl, item) {
|
||||||
|
const code = rowEl.querySelector(".col-code").textContent;
|
||||||
|
rowEl.className = "";
|
||||||
|
rowEl.innerHTML = `
|
||||||
|
<td><span class="country-badge">${esc(item.country || "—")}</span></td>
|
||||||
|
<td class="name-cell">${esc(item.name || "—")}</td>
|
||||||
|
<td><span class="tag-pill" title="${esc(item.producttag || "")}">${esc(item.producttag || "—")}</span></td>
|
||||||
|
<td class="col-code">${esc(code)}</td>
|
||||||
|
`;
|
||||||
scanCount++;
|
scanCount++;
|
||||||
countPill.textContent =
|
countPill.textContent =
|
||||||
scanCount + (scanCount === 1 ? " scan" : " scans");
|
scanCount + (scanCount === 1 ? " scan" : " scans");
|
||||||
countPill.classList.remove("zero");
|
countPill.classList.remove("zero");
|
||||||
|
|
||||||
const tr = document.createElement("tr");
|
|
||||||
tr.innerHTML = `
|
|
||||||
<td><span class="country-badge">${esc(item.country || "—")}</span></td>
|
|
||||||
<td class="name-cell">${esc(item.name || "—")}</td>
|
|
||||||
<td><span class="tag-pill" title="${esc(item.producttag || "")}">${esc(item.producttag || "—")}</span></td>
|
|
||||||
`;
|
|
||||||
// Newest row at the top
|
|
||||||
tableBody.insertBefore(tr, tableBody.firstChild);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Clear ────────────────────────────────────────────────────────────────
|
function rowError(rowEl, msg) {
|
||||||
|
const code = rowEl.querySelector(".col-code").textContent;
|
||||||
|
rowEl.className = "row-error";
|
||||||
|
rowEl.innerHTML = `
|
||||||
|
<td colspan="3" class="error-cell">
|
||||||
|
<span class="error-icon">✕</span>
|
||||||
|
<span class="error-msg">${esc(msg)}</span>
|
||||||
|
<span class="error-code">${esc(code)}</span>
|
||||||
|
</td>
|
||||||
|
<td class="col-code">${esc(code)}</td>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Clear ──────────────────────────────────────────────────────────────────────
|
||||||
function clearTable() {
|
function clearTable() {
|
||||||
if (scanCount === 0 && !scanInput.value) return;
|
const hasContent =
|
||||||
|
scanCount > 0 || scanQueue.length > 0 || scanInput.value;
|
||||||
|
if (!hasContent) return;
|
||||||
|
// Cancel any pending queue items
|
||||||
|
scanQueue.length = 0;
|
||||||
|
queueBusy = false;
|
||||||
|
updateQueuePill();
|
||||||
tableBody.innerHTML = "";
|
tableBody.innerHTML = "";
|
||||||
scanInput.value = "";
|
scanInput.value = "";
|
||||||
scanCount = 0;
|
scanCount = 0;
|
||||||
@@ -1244,11 +1486,11 @@
|
|||||||
showToast("Table cleared", "", 2000);
|
showToast("Table cleared", "", 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Scan Input Enter ─────────────────────────────────────────────────────
|
// ── Scan Input Enter ──────────────────────────────────────────────────────────
|
||||||
scanInput.addEventListener("keydown", (e) => {
|
scanInput.addEventListener("keydown", (e) => {
|
||||||
if (e.key === "Enter") {
|
if (e.key === "Enter") {
|
||||||
const v = scanInput.value.trim();
|
const v = scanInput.value.trim();
|
||||||
if (v) submitScan(v);
|
if (v) enqueue(v);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1265,6 +1507,9 @@
|
|||||||
|
|
||||||
// ── Init ─────────────────────────────────────────────────────────────────
|
// ── Init ─────────────────────────────────────────────────────────────────
|
||||||
window.addEventListener("DOMContentLoaded", () => {
|
window.addEventListener("DOMContentLoaded", () => {
|
||||||
|
// Restore saved credentials before the first network call
|
||||||
|
const saved = loadCredsFromCookie();
|
||||||
|
if (saved) creds = saved;
|
||||||
loadUsers();
|
loadUsers();
|
||||||
scanInput.focus();
|
scanInput.focus();
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user