From 9182f70442590a31d21ffefb7d7d3e1337ef1475 Mon Sep 17 00:00:00 2001 From: Suriyakumarvijayanayagam Date: Mon, 7 Sep 2026 11:52:32 +0530 Subject: [PATCH] A customer number people can say out loud Every id in the schema is a uuid and stays one. What was wrong was putting one in front of a person: RecordVisit named every new customer 'Visitor ' || left(id::text, 8), so the arrivals feed, the shop PC and the mobile app all read "Visitor 3446ec35" - the string a shop assistant reads to a colleague and types into a search box. label is a stored column staff can overwrite and SearchVisitors matches on, so formatting around it in a front end would have left the data wrong on three surfaces. Migration 012 adds a per-client visitors.number, taken from a counter on clients with UPDATE ... RETURNING inside the visit transaction. Per client rather than global: a global sequence would tell any customer who signs up how many people the whole platform has ever seen, from their own first visitor number. The backfill numbers existing rows by first_seen_at and relabels only the eight-hex pattern the old statement produced, so a human-typed name is never overwritten. Three of the four things anyone addresses by URL already had a human name and the API simply refused it - a site has a slug, a camera has the id the engine knows it by. refs.go accepts either form anywhere an id is taken; a uuid resolves with no lookup, so every URL a client already stored keeps working. - An ambiguous camera name resolves to nothing, never to a guess: two shops may each have an "Office1" and acting on the first row would edit the wrong shop's camera. - 404 on a path, 400 on a query filter. /api/visits answered fine and it was the filter that was wrong. - site and site_id are both accepted everywhere now. They differed per endpoint, and an unknown query parameter is silently ignored, so getting it the wrong way round returned the whole estate. - The search matches V-13, which is what the product now shows. Two bugs found by running it rather than testing it: - 'Visitor ' || $2::text beside number = $2 makes Postgres deduce two types for one parameter and refuse the insert. It compiled and passed every in-memory test; the first real database rejected it, along with the existing face tests that share the path. - The fallback avatar said "V1" for Visitor 13, Visitor 10 and Visitor 15 alike, and read as the V-1 reference for a fourth person. It shows the number now. The prop is customerRef, not ref - React reserves that name and it would never have arrived. Verified on the live database and through the running API: 13 hex labels became Visitor 1-13 in first-seen order, two typed names left alone, and the same customer reachable by uuid, V-13 and 13. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01HViLj9gYNRtSr7YVZmW5sn --- API.md | 53 ++++- CLAUDE.md | 99 +++++++++ .../{index-whFsTNQf.js => index-B3nvDQ-a.js} | 2 +- desktop/frontend/dist/index.html | 2 +- desktop/frontend/src/views/Customers.jsx | 9 +- desktop/internal/cloud/client.go | 5 +- server/internal/api/api.go | 8 + server/internal/api/fake_test.go | 84 +++++++- server/internal/api/handlers_arrivals.go | 20 +- server/internal/api/handlers_cameras.go | 23 +-- server/internal/api/handlers_checks.go | 10 +- server/internal/api/handlers_enrolment.go | 5 +- server/internal/api/handlers_images.go | 10 +- server/internal/api/handlers_live.go | 5 +- server/internal/api/handlers_people.go | 20 +- server/internal/api/handlers_reports.go | 16 +- server/internal/api/refs.go | 192 ++++++++++++++++++ server/internal/api/refs_test.go | 110 ++++++++++ server/internal/api/types.go | 9 +- server/internal/store/api_arrivals.go | 5 +- .../internal/store/api_arrivals_live_test.go | 6 +- server/internal/store/api_people.go | 28 ++- server/internal/store/api_refs.go | 81 ++++++++ server/internal/store/api_refs_live_test.go | 182 +++++++++++++++++ server/internal/store/store.go | 32 ++- .../{index-Dv7hKDIX.js => index-BI5JLIeo.js} | 2 +- server/internal/web/dist/index.html | 2 +- server/migrations/012_visitor_numbers.sql | 81 ++++++++ web/src/views/Customers.jsx | 7 + web/src/views/Live.jsx | 30 ++- 30 files changed, 1055 insertions(+), 83 deletions(-) rename desktop/frontend/dist/assets/{index-whFsTNQf.js => index-B3nvDQ-a.js} (92%) create mode 100644 server/internal/api/refs.go create mode 100644 server/internal/api/refs_test.go create mode 100644 server/internal/store/api_refs.go create mode 100644 server/internal/store/api_refs_live_test.go rename server/internal/web/dist/assets/{index-Dv7hKDIX.js => index-BI5JLIeo.js} (85%) create mode 100644 server/migrations/012_visitor_numbers.sql diff --git a/API.md b/API.md index 22204c9..488c93a 100644 --- a/API.md +++ b/API.md @@ -9,6 +9,42 @@ repository uses exactly these calls; anything it can do, an app can do. --- +## 0. Identifiers — you do not have to use uuids + +Every id in the database is a uuid and every one of them still works. But a uuid +is not something a person can say, type or recognise, so **anywhere a path or a +`site` parameter takes an id, it also takes the name people actually use**: + +| thing | reference | example | +|---|---|---| +| customer | `V-` | `V-42` — also accepts bare `42` | +| shop | its slug | `chennai` | +| camera | the id the engine knows it by | `Office1` | +| person | their email address | `priya@tenext.in` | + +``` +GET /api/visitors/3446ec35-2c1f-4c8e-9a77-0d1e2f3a4b5c/history +GET /api/visitors/V-42/history ← the same customer +GET /api/visits?site=chennai +PATCH /api/cameras/Office1 +``` + +The customer number is **per company**, so `V-42` at one tenant and `V-42` at +another are different people, and a reference never resolves outside the tenant +the session belongs to. It is also what the label says: a customer nobody has +named is called `Visitor 42`, and `ref` on every customer object carries `V-42` +for display. + +Two shops in one company may each have a camera called `Office1`. That is +ambiguous, so it resolves to **nothing** rather than to a guess — use the uuid, +or scope by site. + +An unknown reference in a **path** is `404`; an unknown one in a **query filter** +is `400`, because the collection itself was fine and it was the filter that was +wrong. + +--- + ## 1. Signing in ### `POST /api/auth/login` @@ -179,7 +215,7 @@ in. Reactivating restores the account but not their old sessions. ### `GET /api/visits` -`?limit=50&cursor=…&site_id=…` +`?limit=50&cursor=…&site=…` (`site_id` also accepted; a slug or a uuid) ```json { @@ -187,7 +223,7 @@ in. Reactivating restores the account but not their old sessions. "visit_id": "…", "seq": 412, "occurred_at": "2026-09-05T06:01:45Z", "site_id": "…", "site": "TeNext Chennai", "camera_id": "Office1", - "visitor_id": "…", "label": "Priya", + "visitor_id": "…", "visitor_ref": "V-42", "label": "Priya", "is_new_visitor": false, "similarity": 0.71, "quality": 0.66, "attributes": { "gender": "Male", "age": 32, "emotion": "neutral" }, "image": { "available": true, @@ -261,12 +297,15 @@ two rows in *"who looked at my customers"* for one glance at one person. | | | |---|---| -| `GET /api/visitors?q=…` | search by name or phone | +| `GET /api/visitors?q=…` | search by name, phone, or customer number (`42`, `V-42`) | | `GET /api/visitors/{id}/history` | their past visits | | `PUT /api/visitors/{id}/profile` | name, phone, notes — staff and above | | `DELETE /api/visitors/{id}` | **erasure** — manager and above | | `POST /api/purchases` | link a sale to a visit | +`{id}` is a uuid **or** `V-42` **or** `42`. Every customer object carries `ref` +("V-42") beside `id`, and `label` reads "Visitor 42" until somebody names them. + Erasure destroys the face template and the photo outright and keeps the visit rows, unlinked. It is irreversible. If the photo cannot be deleted the whole request fails with **502** and *nothing* is erased — so an error there means the @@ -285,10 +324,10 @@ data is still there, and must be reported as a failure, never swallowed. | `GET /api/reports/footfall` | `?from=&to=&site=&tz=&bucket=` | | `GET /api/reports/conversion` | same parameters; revenue and basket size | -**The site parameter is spelled differently here.** Reports take `site`; the -arrivals feed takes `site_id`. That is a wart, not a rule — but an unknown query -parameter is silently ignored, so getting it wrong returns the whole estate -rather than an error. +**`site` and `site_id` are both accepted everywhere**, and either may be a slug +or a uuid. They used to differ per endpoint, which mattered because an unknown +query parameter is silently ignored — so getting it the wrong way round returned +the whole estate instead of an error. `site` is the documented spelling. Dates are `YYYY-MM-DD`. `to` is **inclusive**: "1st to the 7th" includes the 7th. diff --git a/CLAUDE.md b/CLAUDE.md index f8cba9e..32221af 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1954,6 +1954,105 @@ Verified live 2026-08-31, whole chain: enrol → upload-url → PUT → anonymou JPEG downloaded → erase → presigned GET **404**, 0 templates, 0 profiles, label `Erased`, visit row kept. +## Identifiers: a customer number people can say (migration 012) + +Every id in the schema is a uuid and stays one. What was wrong was putting one +in front of a person. `RecordVisit` named every new customer from theirs: + +```sql +UPDATE visitors SET label = 'Visitor ' || left(id::text, 8) +``` + +So the name on the arrivals feed, on the shop PC, and in the mobile app was +**"Visitor 3446ec35"** — the string a shop assistant reads out to a colleague, +writes on a card, and types into a search box. Not a display problem to paper +over in a front end either: `label` is a stored column staff can overwrite and +`SearchVisitors` matches on, so it had to be fixed where it is written. + +`visitors.number` is a **per-client** sequence and the label is now +`Visitor 42`, referenced as **`V-42`**. Three properties, each ruling out an +alternative: + +- **Speakable.** The whole point. +- **Per client, not global.** A global sequence tells any customer who signs up + how many people the entire platform has ever seen, from their own first + visitor number. Per tenant it reveals a tenant's own count to that tenant's + own staff, who know it already. +- **Not the primary key.** Ids are minted where nothing can ask a database for + the next value, and eleven tables reference `visitors.id`. This is a public + *reference* beside the key, which is the part humans needed. + +The counter is `clients.visitor_seq`, taken with `UPDATE ... RETURNING` inside +the visit transaction. That returns the value **after** the update — the same +semantics that silently broke the face prune in 011 by handing back what it had +just written, and here exactly what is wanted. It row-locks the client for the +length of the insert, which serialises new-visitor creation per tenant and costs +nothing: it runs only for a face nobody in the estate has ever seen. + +The backfill numbers existing rows by `first_seen_at` and relabels **only** the +eight-lowercase-hex pattern the old statement produced, so a name a human typed +is never overwritten. Verified on the live database: 13 hex labels became +Visitor 1-13 in first-seen order, two "Walk-in test" names were left alone, and +`visitor_seq` landed on 15. + +### Three of the four things already had a human name; the API refused it + +That is the part worth keeping. Only visitors genuinely lacked a reference: + +| thing | reference | since | +|---|---|---| +| shop | `slug` — "chennai" | 001 | +| camera | `camera_id` — "Office1", and what `visits.camera_id` holds | 005 | +| customer | `V-` | 012 | +| person | email | 002 | + +`refs.go` accepts either form anywhere an id is taken. A uuid resolves with no +lookup at all, so nothing that worked yesterday changes — including every URL a +client has already stored. Only a non-uuid costs a query. + +- **A camera id is unique per SITE, not per tenant.** Two shops may each have an + `Office1`, so an ambiguous name resolves to **nothing** rather than to + whichever row sorted first — acting on a guess would edit the wrong shop's + camera. +- **404 on a path, 400 on a query filter.** `/api/visits` exists and answered; + what was wrong was the filter, and a 404 there reads as "the arrivals feed is + gone". A path segment names the resource itself, so an unknown one *is* a 404. +- **`site` and `site_id` are both accepted everywhere now.** Reports took one and + the arrivals feed the other, and an unknown query parameter is silently + ignored — so getting it the wrong way round returned the whole estate instead + of an error, which is a wrong number nobody would question. +- **The search matches the reference.** `V-13` is what the product now shows, so + it is what gets pasted into the search box, and `label ILIKE '%V-13%'` finds + nothing because the label says "Visitor 13". A search that comes back empty + for the identifier you were just shown is worse than no search. + +The **edge** engine has always numbered its identities from a SQLite rowid, so +"Visitor 3" there and "Visitor 47" here are the same person under two numbers. +Left alone deliberately: making them agree means the shop PC asking the server +for a number, which cannot work offline — and the edge number appears only on +the engine's own diagnostic dashboard. + +### Two bugs, one from a real database and one from a real browser + +- **`'Visitor ' || $2::text` next to `number = $2`.** Postgres deduces two types + for one parameter and refuses the whole insert: *"inconsistent types deduced + for parameter $2"*. It compiled, it passed every in-memory test, and it failed + on the first real database — along with the existing face tests, which go + through the same path. The label is formatted in Go now. +- **The avatar said `V1` for three different people.** With no photograph the + arrivals feed draws initials, and `initials("Visitor 13")` takes the first + letter of each word — `V1`, which is also what "Visitor 10" and "Visitor 15" + produce, and which reads as the `V-1` reference for a fourth person. It shows + the number itself now. Found by opening the page: every test here passes a + human name. The prop carrying it is `customerRef`, not `ref` — React reserves + that name, so it would never have reached the component. + +Fixture note: `embedding(seed)` fills every dimension with one value, so after +L2 normalisation 0.31 and 0.62 are the **same direction** and the matcher +correctly calls them one person. Tests that need several different people use +`distinctFace(i)`, which is orthogonal per index. + + ## Setting up on a new machine 1. Copy the `Behavision` folder **including `.env`** (gitignored, holds diff --git a/desktop/frontend/dist/assets/index-whFsTNQf.js b/desktop/frontend/dist/assets/index-B3nvDQ-a.js similarity index 92% rename from desktop/frontend/dist/assets/index-whFsTNQf.js rename to desktop/frontend/dist/assets/index-B3nvDQ-a.js index 4ec019f..898eb42 100644 --- a/desktop/frontend/dist/assets/index-whFsTNQf.js +++ b/desktop/frontend/dist/assets/index-B3nvDQ-a.js @@ -37,4 +37,4 @@ `+l[o].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=o&&0<=u);break}}}finally{Pl=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?jn(e):""}function Wc(e){switch(e.tag){case 5:return jn(e.type);case 16:return jn("Lazy");case 13:return jn("Suspense");case 19:return jn("SuspenseList");case 0:case 2:case 15:return e=Tl(e.type,!1),e;case 11:return e=Tl(e.type.render,!1),e;case 1:return e=Tl(e.type,!0),e;default:return""}}function ri(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ut:return"Fragment";case Ft:return"Portal";case ei:return"Profiler";case qi:return"StrictMode";case ti:return"Suspense";case ni:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case hu:return(e.displayName||"Context")+".Consumer";case pu:return(e._context.displayName||"Context")+".Provider";case bi:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case eo:return t=e.displayName||null,t!==null?t:ri(e.type)||"Memo";case et:t=e._payload,e=e._init;try{return ri(e(t))}catch{}}return null}function Qc(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ri(t);case 8:return t===qi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ht(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function vu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Kc(e){var t=vu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ur(e){e._valueTracker||(e._valueTracker=Kc(e))}function yu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=vu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Fr(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function li(e,t){var n=t.checked;return Q({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Yo(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ht(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function gu(e,t){t=t.checked,t!=null&&Ji(e,"checked",t,!1)}function ii(e,t){gu(e,t);var n=ht(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?oi(e,t.type,n):t.hasOwnProperty("defaultValue")&&oi(e,t.type,ht(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Xo(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function oi(e,t,n){(t!=="number"||Fr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Nn=Array.isArray;function Gt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=ar.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var _n={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Yc=["Webkit","ms","Moz","O"];Object.keys(_n).forEach(function(e){Yc.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),_n[t]=_n[e]})});function ku(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||_n.hasOwnProperty(e)&&_n[e]?(""+t).trim():t+"px"}function ju(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ku(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Xc=Q({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ai(e,t){if(t){if(Xc[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(w(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(w(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(w(61))}if(t.style!=null&&typeof t.style!="object")throw Error(w(62))}}function ci(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var di=null;function to(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var fi=null,Zt=null,Jt=null;function Jo(e){if(e=nr(e)){if(typeof fi!="function")throw Error(w(280));var t=e.stateNode;t&&(t=fl(t),fi(e.stateNode,e.type,t))}}function Nu(e){Zt?Jt?Jt.push(e):Jt=[e]:Zt=e}function Cu(){if(Zt){var e=Zt,t=Jt;if(Jt=Zt=null,Jo(e),t)for(e=0;e>>=0,e===0?32:31-(id(e)/od|0)|0}var cr=64,dr=4194304;function Cn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Ar(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var u=o&~l;u!==0?r=Cn(u):(i&=o,i!==0&&(r=Cn(i)))}else o=n&~l,o!==0?r=Cn(o):i!==0&&(r=Cn(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function er(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Me(t),e[t]=n}function cd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Tn),os=" ",ss=!1;function Qu(e,t){switch(e){case"keyup":return Ud.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ku(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var $t=!1;function Bd(e,t){switch(e){case"compositionend":return Ku(t);case"keypress":return t.which!==32?null:(ss=!0,os);case"textInput":return e=t.data,e===os&&ss?null:e;default:return null}}function Ad(e,t){if($t)return e==="compositionend"||!ao&&Qu(e,t)?(e=Hu(),Pr=oo=lt=null,$t=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=ds(n)}}function Zu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Zu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ju(){for(var e=window,t=Fr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Fr(e.document)}return t}function co(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Zd(e){var t=Ju(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Zu(n.ownerDocument.documentElement,n)){if(r!==null&&co(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=fs(n,i);var o=fs(n,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Bt=null,gi=null,Ln=null,wi=!1;function ps(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;wi||Bt==null||Bt!==Fr(r)||(r=Bt,"selectionStart"in r&&co(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ln&&Hn(Ln,r)||(Ln=r,r=Wr(gi,"onSelect"),0Ht||(e.current=Ci[Ht],Ci[Ht]=null,Ht--)}function F(e,t){Ht++,Ci[Ht]=e.current,e.current=t}var mt={},se=yt(mt),he=yt(!1),Pt=mt;function rn(e,t){var n=e.type.contextTypes;if(!n)return mt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function me(e){return e=e.childContextTypes,e!=null}function Kr(){$(he),$(se)}function xs(e,t,n){if(se.current!==mt)throw Error(w(168));F(se,t),F(he,n)}function oa(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(w(108,Qc(e)||"Unknown",l));return Q({},n,r)}function Yr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||mt,Pt=se.current,F(se,e),F(he,he.current),!0}function Ss(e,t,n){var r=e.stateNode;if(!r)throw Error(w(169));n?(e=oa(e,t,Pt),r.__reactInternalMemoizedMergedChildContext=e,$(he),$(se),F(se,e)):$(he),F(he,n)}var We=null,pl=!1,Hl=!1;function sa(e){We===null?We=[e]:We.push(e)}function af(e){pl=!0,sa(e)}function gt(){if(!Hl&&We!==null){Hl=!0;var e=0,t=M;try{var n=We;for(M=1;e>=o,l-=o,Qe=1<<32-Me(t)+l|n<E?(V=j,j=null):V=j.sibling;var L=m(h,j,f[E],y);if(L===null){j===null&&(j=V);break}e&&j&&L.alternate===null&&t(h,j),d=i(L,d,E),_===null?S=L:_.sibling=L,_=L,j=V}if(E===f.length)return n(h,j),B&&St(h,E),S;if(j===null){for(;EE?(V=j,j=null):V=j.sibling;var ze=m(h,j,L.value,y);if(ze===null){j===null&&(j=V);break}e&&j&&ze.alternate===null&&t(h,j),d=i(ze,d,E),_===null?S=ze:_.sibling=ze,_=ze,j=V}if(L.done)return n(h,j),B&&St(h,E),S;if(j===null){for(;!L.done;E++,L=f.next())L=v(h,L.value,y),L!==null&&(d=i(L,d,E),_===null?S=L:_.sibling=L,_=L);return B&&St(h,E),S}for(j=r(h,j);!L.done;E++,L=f.next())L=g(j,h,E,L.value,y),L!==null&&(e&&L.alternate!==null&&j.delete(L.key===null?E:L.key),d=i(L,d,E),_===null?S=L:_.sibling=L,_=L);return e&&j.forEach(function(pn){return t(h,pn)}),B&&St(h,E),S}function O(h,d,f,y){if(typeof f=="object"&&f!==null&&f.type===Ut&&f.key===null&&(f=f.props.children),typeof f=="object"&&f!==null){switch(f.$$typeof){case sr:e:{for(var S=f.key,_=d;_!==null;){if(_.key===S){if(S=f.type,S===Ut){if(_.tag===7){n(h,_.sibling),d=l(_,f.props.children),d.return=h,h=d;break e}}else if(_.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===et&&Ns(S)===_.type){n(h,_.sibling),d=l(_,f.props),d.ref=xn(h,_,f),d.return=h,h=d;break e}n(h,_);break}else t(h,_);_=_.sibling}f.type===Ut?(d=_t(f.props.children,h.mode,y,f.key),d.return=h,h=d):(y=Ir(f.type,f.key,f.props,null,h.mode,y),y.ref=xn(h,d,f),y.return=h,h=y)}return o(h);case Ft:e:{for(_=f.key;d!==null;){if(d.key===_)if(d.tag===4&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){n(h,d.sibling),d=l(d,f.children||[]),d.return=h,h=d;break e}else{n(h,d);break}else t(h,d);d=d.sibling}d=Jl(f,h.mode,y),d.return=h,h=d}return o(h);case et:return _=f._init,O(h,d,_(f._payload),y)}if(Nn(f))return x(h,d,f,y);if(mn(f))return k(h,d,f,y);gr(h,f)}return typeof f=="string"&&f!==""||typeof f=="number"?(f=""+f,d!==null&&d.tag===6?(n(h,d.sibling),d=l(d,f),d.return=h,h=d):(n(h,d),d=Zl(f,h.mode,y),d.return=h,h=d),o(h)):n(h,d)}return O}var on=da(!0),fa=da(!1),Zr=yt(null),Jr=null,Kt=null,mo=null;function vo(){mo=Kt=Jr=null}function yo(e){var t=Zr.current;$(Zr),e._currentValue=t}function Pi(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function bt(e,t){Jr=e,mo=Kt=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(pe=!0),e.firstContext=null)}function _e(e){var t=e._currentValue;if(mo!==e)if(e={context:e,memoizedValue:t,next:null},Kt===null){if(Jr===null)throw Error(w(308));Kt=e,Jr.dependencies={lanes:0,firstContext:e}}else Kt=Kt.next=e;return t}var Nt=null;function go(e){Nt===null?Nt=[e]:Nt.push(e)}function pa(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,go(t)):(n.next=l.next,l.next=n),t.interleaved=n,Ze(e,r)}function Ze(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var tt=!1;function wo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ha(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ye(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ct(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,D&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Ze(e,n)}return l=r.interleaved,l===null?(t.next=t,go(r)):(t.next=l.next,l.next=t),r.interleaved=t,Ze(e,n)}function zr(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ro(e,n)}}function Cs(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function qr(e,t,n,r){var l=e.updateQueue;tt=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var a=u,c=a.next;a.next=null,o===null?i=c:o.next=c,o=a;var p=e.alternate;p!==null&&(p=p.updateQueue,u=p.lastBaseUpdate,u!==o&&(u===null?p.firstBaseUpdate=c:u.next=c,p.lastBaseUpdate=a))}if(i!==null){var v=l.baseState;o=0,p=c=a=null,u=i;do{var m=u.lane,g=u.eventTime;if((r&m)===m){p!==null&&(p=p.next={eventTime:g,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var x=e,k=u;switch(m=t,g=n,k.tag){case 1:if(x=k.payload,typeof x=="function"){v=x.call(g,v,m);break e}v=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=k.payload,m=typeof x=="function"?x.call(g,v,m):x,m==null)break e;v=Q({},v,m);break e;case 2:tt=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,m=l.effects,m===null?l.effects=[u]:m.push(u))}else g={eventTime:g,lane:m,tag:u.tag,payload:u.payload,callback:u.callback,next:null},p===null?(c=p=g,a=v):p=p.next=g,o|=m;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;m=u,u=m.next,m.next=null,l.lastBaseUpdate=m,l.shared.pending=null}}while(!0);if(p===null&&(a=v),l.baseState=a,l.firstBaseUpdate=c,l.lastBaseUpdate=p,t=l.shared.interleaved,t!==null){l=t;do o|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);Lt|=o,e.lanes=o,e.memoizedState=v}}function Es(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Ql.transition;Ql.transition={};try{e(!1),t()}finally{M=n,Ql.transition=r}}function La(){return Pe().memoizedState}function pf(e,t,n){var r=ft(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ra(e))Da(t,n);else if(n=pa(e,t,n,r),n!==null){var l=ae();Ie(n,e,r,l),Oa(n,t,r)}}function hf(e,t,n){var r=ft(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ra(e))Da(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,u=i(o,n);if(l.hasEagerState=!0,l.eagerState=u,Fe(u,o)){var a=t.interleaved;a===null?(l.next=l,go(t)):(l.next=a.next,a.next=l),t.interleaved=l;return}}catch{}finally{}n=pa(e,t,l,r),n!==null&&(l=ae(),Ie(n,e,r,l),Oa(n,t,r))}}function Ra(e){var t=e.alternate;return e===W||t!==null&&t===W}function Da(e,t){Rn=el=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Oa(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ro(e,n)}}var tl={readContext:_e,useCallback:le,useContext:le,useEffect:le,useImperativeHandle:le,useInsertionEffect:le,useLayoutEffect:le,useMemo:le,useReducer:le,useRef:le,useState:le,useDebugValue:le,useDeferredValue:le,useTransition:le,useMutableSource:le,useSyncExternalStore:le,useId:le,unstable_isNewReconciler:!1},mf={readContext:_e,useCallback:function(e,t){return $e().memoizedState=[e,t===void 0?null:t],e},useContext:_e,useEffect:Ps,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Rr(4194308,4,Ea.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Rr(4194308,4,e,t)},useInsertionEffect:function(e,t){return Rr(4,2,e,t)},useMemo:function(e,t){var n=$e();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=$e();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=pf.bind(null,W,e),[r.memoizedState,e]},useRef:function(e){var t=$e();return e={current:e},t.memoizedState=e},useState:_s,useDebugValue:_o,useDeferredValue:function(e){return $e().memoizedState=e},useTransition:function(){var e=_s(!1),t=e[0];return e=ff.bind(null,e[1]),$e().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=W,l=$e();if(B){if(n===void 0)throw Error(w(407));n=n()}else{if(n=t(),ee===null)throw Error(w(349));zt&30||ga(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Ps(xa.bind(null,r,i,e),[e]),r.flags|=2048,Jn(9,wa.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=$e(),t=ee.identifierPrefix;if(B){var n=Ke,r=Qe;n=(r&~(1<<32-Me(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Gn++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Be]=t,e[Kn]=r,Wa(e,t,!1,!1),t.stateNode=e;e:{switch(o=ci(n,r),n){case"dialog":U("cancel",e),U("close",e),l=r;break;case"iframe":case"object":case"embed":U("load",e),l=r;break;case"video":case"audio":for(l=0;lan&&(t.flags|=128,r=!0,Sn(i,!1),t.lanes=4194304)}else{if(!r)if(e=br(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Sn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!B)return ie(t),null}else 2*X()-i.renderingStartTime>an&&n!==1073741824&&(t.flags|=128,r=!0,Sn(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=X(),t.sibling=null,n=H.current,F(H,r?n&1|2:n&1),t):(ie(t),null);case 22:case 23:return Do(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ye&1073741824&&(ie(t),t.subtreeFlags&6&&(t.flags|=8192)):ie(t),null;case 24:return null;case 25:return null}throw Error(w(156,t.tag))}function jf(e,t){switch(po(t),t.tag){case 1:return me(t.type)&&Kr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return sn(),$(he),$(se),ko(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return So(t),null;case 13:if($(H),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(w(340));ln()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return $(H),null;case 4:return sn(),null;case 10:return yo(t.type._context),null;case 22:case 23:return Do(),null;case 24:return null;default:return null}}var xr=!1,oe=!1,Nf=typeof WeakSet=="function"?WeakSet:Set,N=null;function Yt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){K(e,t,r)}else n.current=null}function Fi(e,t,n){try{n()}catch(r){K(e,t,r)}}var $s=!1;function Cf(e,t){if(xi=Vr,e=Ju(),co(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,u=-1,a=-1,c=0,p=0,v=e,m=null;t:for(;;){for(var g;v!==n||l!==0&&v.nodeType!==3||(u=o+l),v!==i||r!==0&&v.nodeType!==3||(a=o+r),v.nodeType===3&&(o+=v.nodeValue.length),(g=v.firstChild)!==null;)m=v,v=g;for(;;){if(v===e)break t;if(m===n&&++c===l&&(u=o),m===i&&++p===r&&(a=o),(g=v.nextSibling)!==null)break;v=m,m=v.parentNode}v=g}n=u===-1||a===-1?null:{start:u,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Si={focusedElem:e,selectionRange:n},Vr=!1,N=t;N!==null;)if(t=N,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,N=e;else for(;N!==null;){t=N;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var k=x.memoizedProps,O=x.memoizedState,h=t.stateNode,d=h.getSnapshotBeforeUpdate(t.elementType===t.type?k:Re(t.type,k),O);h.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var f=t.stateNode.containerInfo;f.nodeType===1?f.textContent="":f.nodeType===9&&f.documentElement&&f.removeChild(f.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(w(163))}}catch(y){K(t,t.return,y)}if(e=t.sibling,e!==null){e.return=t.return,N=e;break}N=t.return}return x=$s,$s=!1,x}function Dn(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Fi(t,n,i)}l=l.next}while(l!==r)}}function vl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ui(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ya(e){var t=e.alternate;t!==null&&(e.alternate=null,Ya(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Be],delete t[Kn],delete t[Ni],delete t[sf],delete t[uf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xa(e){return e.tag===5||e.tag===3||e.tag===4}function Bs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xa(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function $i(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Qr));else if(r!==4&&(e=e.child,e!==null))for($i(e,t,n),e=e.sibling;e!==null;)$i(e,t,n),e=e.sibling}function Bi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Bi(e,t,n),e=e.sibling;e!==null;)Bi(e,t,n),e=e.sibling}var te=null,De=!1;function be(e,t,n){for(n=n.child;n!==null;)Ga(e,t,n),n=n.sibling}function Ga(e,t,n){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(ul,n)}catch{}switch(n.tag){case 5:oe||Yt(n,t);case 6:var r=te,l=De;te=null,be(e,t,n),te=r,De=l,te!==null&&(De?(e=te,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):te.removeChild(n.stateNode));break;case 18:te!==null&&(De?(e=te,n=n.stateNode,e.nodeType===8?Vl(e.parentNode,n):e.nodeType===1&&Vl(e,n),An(e)):Vl(te,n.stateNode));break;case 4:r=te,l=De,te=n.stateNode.containerInfo,De=!0,be(e,t,n),te=r,De=l;break;case 0:case 11:case 14:case 15:if(!oe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Fi(n,t,o),l=l.next}while(l!==r)}be(e,t,n);break;case 1:if(!oe&&(Yt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){K(n,t,u)}be(e,t,n);break;case 21:be(e,t,n);break;case 22:n.mode&1?(oe=(r=oe)||n.memoizedState!==null,be(e,t,n),oe=r):be(e,t,n);break;default:be(e,t,n)}}function As(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Nf),t.forEach(function(r){var l=Of.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Le(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=X()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*_f(r/1960))-r,10e?16:e,it===null)var r=!1;else{if(e=it,it=null,ll=0,D&6)throw Error(w(331));var l=D;for(D|=4,N=e.current;N!==null;){var i=N,o=i.child;if(N.flags&16){var u=i.deletions;if(u!==null){for(var a=0;aX()-Lo?Et(e,0):zo|=n),ve(e,t)}function rc(e,t){t===0&&(e.mode&1?(t=dr,dr<<=1,!(dr&130023424)&&(dr=4194304)):t=1);var n=ae();e=Ze(e,t),e!==null&&(er(e,t,n),ve(e,n))}function Df(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),rc(e,n)}function Of(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(w(314))}r!==null&&r.delete(t),rc(e,n)}var lc;lc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||he.current)pe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pe=!1,Sf(e,t,n);pe=!!(e.flags&131072)}else pe=!1,B&&t.flags&1048576&&ua(t,Gr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Dr(e,t),e=t.pendingProps;var l=rn(t,se.current);bt(t,n),l=No(null,t,r,e,l,n);var i=Co();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,me(r)?(i=!0,Yr(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,wo(t),l.updater=ml,t.stateNode=l,l._reactInternals=t,zi(t,r,e,n),t=Di(null,t,r,!0,i,n)):(t.tag=0,B&&i&&fo(t),ue(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Dr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=If(r),e=Re(r,e),l){case 0:t=Ri(null,t,r,e,n);break e;case 1:t=Is(null,t,r,e,n);break e;case 11:t=Os(null,t,r,e,n);break e;case 14:t=Ms(null,t,r,Re(r.type,e),n);break e}throw Error(w(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Ri(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Is(e,t,r,l,n);case 3:e:{if(Aa(t),e===null)throw Error(w(387));r=t.pendingProps,i=t.memoizedState,l=i.element,ha(e,t),qr(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=un(Error(w(423)),t),t=Fs(e,t,r,n,l);break e}else if(r!==l){l=un(Error(w(424)),t),t=Fs(e,t,r,n,l);break e}else for(ge=at(t.stateNode.containerInfo.firstChild),we=t,B=!0,Oe=null,n=fa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ln(),r===l){t=Je(e,t,n);break e}ue(e,t,r,n)}t=t.child}return t;case 5:return ma(t),e===null&&_i(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,ki(r,l)?o=null:i!==null&&ki(r,i)&&(t.flags|=32),Ba(e,t),ue(e,t,o,n),t.child;case 6:return e===null&&_i(t),null;case 13:return Va(e,t,n);case 4:return xo(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=on(t,null,r,n):ue(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Os(e,t,r,l,n);case 7:return ue(e,t,t.pendingProps,n),t.child;case 8:return ue(e,t,t.pendingProps.children,n),t.child;case 12:return ue(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,o=l.value,F(Zr,r._currentValue),r._currentValue=o,i!==null)if(Fe(i.value,o)){if(i.children===l.children&&!he.current){t=Je(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var u=i.dependencies;if(u!==null){o=i.child;for(var a=u.firstContext;a!==null;){if(a.context===r){if(i.tag===1){a=Ye(-1,n&-n),a.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var p=c.pending;p===null?a.next=a:(a.next=p.next,p.next=a),c.pending=a}}i.lanes|=n,a=i.alternate,a!==null&&(a.lanes|=n),Pi(i.return,n,t),u.lanes|=n;break}a=a.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(w(341));o.lanes|=n,u=o.alternate,u!==null&&(u.lanes|=n),Pi(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ue(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,bt(t,n),l=_e(l),r=r(l),t.flags|=1,ue(e,t,r,n),t.child;case 14:return r=t.type,l=Re(r,t.pendingProps),l=Re(r.type,l),Ms(e,t,r,l,n);case 15:return Ua(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Dr(e,t),t.tag=1,me(r)?(e=!0,Yr(t)):e=!1,bt(t,n),Ma(t,r,l),zi(t,r,l,n),Di(null,t,r,!0,e,n);case 19:return Ha(e,t,n);case 22:return $a(e,t,n)}throw Error(w(156,t.tag))};function ic(e,t){return Ru(e,t)}function Mf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ce(e,t,n,r){return new Mf(e,t,n,r)}function Mo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function If(e){if(typeof e=="function")return Mo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===bi)return 11;if(e===eo)return 14}return 2}function pt(e,t){var n=e.alternate;return n===null?(n=Ce(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Ir(e,t,n,r,l,i){var o=2;if(r=e,typeof e=="function")Mo(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Ut:return _t(n.children,l,i,t);case qi:o=8,l|=8;break;case ei:return e=Ce(12,n,t,l|2),e.elementType=ei,e.lanes=i,e;case ti:return e=Ce(13,n,t,l),e.elementType=ti,e.lanes=i,e;case ni:return e=Ce(19,n,t,l),e.elementType=ni,e.lanes=i,e;case mu:return gl(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case pu:o=10;break e;case hu:o=9;break e;case bi:o=11;break e;case eo:o=14;break e;case et:o=16,r=null;break e}throw Error(w(130,e==null?e:typeof e,""))}return t=Ce(o,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function _t(e,t,n,r){return e=Ce(7,e,r,t),e.lanes=n,e}function gl(e,t,n,r){return e=Ce(22,e,r,t),e.elementType=mu,e.lanes=n,e.stateNode={isHidden:!1},e}function Zl(e,t,n){return e=Ce(6,e,null,t),e.lanes=n,e}function Jl(e,t,n){return t=Ce(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Ff(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ll(0),this.expirationTimes=Ll(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ll(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Io(e,t,n,r,l,i,o,u,a){return e=new Ff(e,t,n,u,a),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ce(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wo(i),e}function Uf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ac)}catch(e){console.error(e)}}ac(),au.exports=Se;var Hf=au.exports,cc,Gs=Hf;cc=Gs.createRoot,Gs.hydrateRoot;const dc=()=>{var e,t;return(t=(e=window==null?void 0:window.go)==null?void 0:e.main)==null?void 0:t.App},Wf=()=>!!dc();async function I(e,...t){const n=dc();if(!n||typeof n[e]!="function")throw new Error(`${e} is unavailable — run this inside the Behavision app`);return n[e](...t)}const A={session:()=>I("Session"),login:(e,t)=>I("Login",e,t),logout:()=>I("Logout"),claim:e=>I("Claim",e),runStandalone:()=>I("RunStandalone"),engineStatus:()=>I("EngineStatus"),startEngine:()=>I("StartEngine"),stopEngine:()=>I("StopEngine"),cameras:()=>I("Cameras"),testCamera:e=>I("TestCamera",e),saveCamera:(e,t)=>I("SaveCamera",e,t),deleteCamera:e=>I("DeleteCamera",e),startPlacement:(e,t)=>I("StartPlacementCheck",e,t),placementResult:e=>I("PlacementResult",e),streamURL:e=>I("StreamURL",e),live:()=>I("Live"),pipelineStatus:()=>I("PipelineStatus"),localIdentities:e=>I("LocalIdentities",e),localSightings:e=>I("LocalSightings",e),footfall:(e,t,n)=>I("Footfall",e,t,n),sites:()=>I("Sites"),visitorHistory:(e,t)=>I("VisitorHistory",e,t),visitorPhoto:e=>I("VisitorPhoto",e),forgetCustomer:e=>I("ForgetCustomer",e),sales:(e,t)=>I("Sales",e,t),customers:(e,t)=>I("Customers",e,t),saveProfile:e=>I("SaveProfile",e),recordPurchase:(e,t,n,r)=>I("RecordPurchase",e,t,n,r)};function Te(e){return e?typeof e=="string"?e:e.message||String(e):"Something went wrong."}function Dt(e,t,n=[]){const[r,l]=P.useState(null),[i,o]=P.useState(null),[u,a]=P.useState(!0),c=P.useRef(!0),p=P.useRef(!1),v=P.useCallback(async()=>{if(!p.current){p.current=!0;try{const m=await e();if(!c.current)return;l(m),o(null)}catch(m){c.current&&o(Te(m))}finally{p.current=!1,c.current&&a(!1)}}},n);return P.useEffect(()=>{if(c.current=!0,v(),!t)return()=>{c.current=!1};const m=setInterval(v,t);return()=>{c.current=!1,clearInterval(m)}},[v,t]),{data:r,error:i,loading:u,reload:v}}function Qf(e){if(!e)return"—";const t=typeof e=="number"?new Date(e*1e3):new Date(e);return isNaN(t)?"—":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Zs(e){if(!e)return"—";const t=typeof e=="number"?new Date(e*1e3):new Date(e);return isNaN(t)?"—":t.toLocaleDateString([],{day:"numeric",month:"short"})}function Kf({onDone:e}){const[t,n]=P.useState(""),[r,l]=P.useState(""),[i,o]=P.useState(!1),[u,a]=P.useState(null);async function c(p){p.preventDefault(),o(!0),a(null);try{e(await A.login(t.trim(),r))}catch(v){a(Te(v))}finally{o(!1)}}return s.jsx("div",{className:"login",children:s.jsxs("div",{className:"box",children:[s.jsx("h1",{children:"Behavision"}),s.jsx("p",{className:"lead",children:"Sign in to connect this PC to your store."}),s.jsxs("form",{onSubmit:c,children:[u&&s.jsx("div",{className:"err",children:u}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Email"}),s.jsx("input",{type:"email",value:t,autoComplete:"username",required:!0,autoFocus:!0,onChange:p=>n(p.target.value)})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:r,autoComplete:"current-password",required:!0,onChange:p=>l(p.target.value)})]}),s.jsx("button",{className:"btn primary",disabled:i||!t||!r,children:i?"Signing in…":"Sign in"})]}),s.jsx("p",{className:"foot",children:"Signing in downloads this store's recognition models and connects it to your account. Nothing is sent until a camera is set up."})]})})}function Js({onDone:e,onCancel:t}){const[n,r]=P.useState(""),[l,i]=P.useState(null),[o,u]=P.useState(null),[a,c]=P.useState(!1);async function p(m){m.preventDefault(),i("claim"),u(null);try{e(await A.claim(n))}catch(g){u(Te(g))}finally{i(null)}}async function v(){i("alone"),u(null);try{e(await A.runStandalone())}catch(m){u(Te(m))}finally{i(null)}}return s.jsx("div",{className:"login",children:s.jsxs("div",{className:"box",children:[s.jsx("h1",{children:t?"Link to head office":"Set up this PC"}),s.jsx("p",{className:"lead",children:"Type the installation code for this shop. You only do this once."}),s.jsxs("form",{onSubmit:p,children:[o&&s.jsx("div",{className:"err",children:o}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Installation code"}),s.jsx("input",{value:n,autoFocus:!0,required:!0,placeholder:"ABCDEF-123456-GHIJKL-789012",autoComplete:"off",spellCheck:"false",style:{textTransform:"uppercase",letterSpacing:".06em"},onChange:m=>r(m.target.value)})]}),s.jsx("button",{className:"btn primary",disabled:!!l||n.trim().length<6,children:l==="claim"?"Linking…":"Link this PC"})]}),s.jsx("p",{className:"foot",children:"The code works once. Ask whoever manages your shops for it — they can create one from the Behavision platform, under the shop."}),s.jsx("div",{className:"alt",children:t?s.jsx("button",{type:"button",className:"linkbtn",onClick:t,children:"Not now — go back"}):a?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"note",children:"This PC will watch its cameras and recognise returning customers on its own. Nothing is sent anywhere. You can link it to head office later without losing anything recorded here."}),s.jsx("button",{type:"button",className:"btn",disabled:!!l,onClick:v,children:l==="alone"?"Setting up…":"Use this PC on its own"})]}):s.jsx("button",{type:"button",className:"linkbtn",onClick:()=>c(!0),children:"No head office — set this PC up on its own"})})]})})}function fc(){var a,c;const{data:e,error:t}=Dt(()=>A.live(),3e3),{data:n}=Dt(()=>A.pipelineStatus(),5e3),r=Zf(),l=((a=e==null?void 0:e.stats)==null?void 0:a.cameras)??[],i=((c=e==null?void 0:e.stats)==null?void 0:c.gallery)??{},o=(e==null?void 0:e.events)??[],u=l.reduce((p,v)=>{var g,x;const m=(x=(g=v==null?void 0:v.pipeline)==null?void 0:g.best_quality)==null?void 0:x.fraction_below_gate;return typeof m=="number"&&m>p?m:p},0);return s.jsxs("div",{className:"page",children:[s.jsxs("header",{children:[s.jsx("h2",{children:"Live"}),s.jsx("p",{children:"Cameras, recent detections, and whether this site is recognising people."})]}),t&&s.jsx("div",{className:"err",children:t}),s.jsxs("div",{className:"grid cols-4",style:{marginBottom:16},children:[s.jsx(jr,{label:"People known",value:i.identities??"—"}),s.jsx(jr,{label:"Sightings",value:i.sightings??"—"}),s.jsx(jr,{label:"Cameras live",value:`${l.filter(p=>p.connected).length}/${l.length||0}`}),s.jsx(jr,{label:"Below quality gate",value:l.length?`${Math.round(u*100)}%`:"—",tone:u>.5?"bad":u>.2?"warn":"ok",sub:u>.5?"Most visitors are being missed — check camera placement":"Share of faces too poor to enrol"})]}),s.jsx(Yf,{pipe:n}),s.jsxs("div",{className:"grid cols-2",children:[s.jsx("div",{children:s.jsxs("div",{className:"card",children:[s.jsx("h3",{children:"Cameras"}),l.length===0?s.jsx("div",{className:"empty",children:"No cameras yet. Add one in Cameras."}):s.jsx("div",{className:"feeds",children:l.map(p=>s.jsxs("div",{className:"feed",children:[r[p.camera_id]?s.jsx("img",{src:r[p.camera_id],alt:p.camera_id}):s.jsx("div",{style:{aspectRatio:"16/9"}}),s.jsxs("div",{className:"cap",children:[s.jsx("span",{children:p.camera_id}),s.jsxs("span",{className:`pill ${p.connected?"ok":"bad"}`,children:[s.jsx("i",{className:`dot ${p.connected?"ok":"bad"}`}),p.connected?"live":"offline"]})]})]},p.camera_id))})]})}),s.jsxs("div",{className:"card",children:[s.jsx("h3",{children:"Recent detections"}),o.length===0?s.jsx("div",{className:"empty",children:"Nothing detected yet."}):s.jsx("ul",{className:"events",children:o.map((p,v)=>s.jsx(Xf,{e:p},v))})]})]})]})}function Yf({pipe:e}){if(!e)return null;if(e.standalone)return s.jsxs("div",{className:"card",style:{marginBottom:16,display:"flex",gap:10,alignItems:"center"},children:[s.jsx("i",{className:"dot ok"}),s.jsx("strong",{style:{fontSize:13},children:"Running on this PC only"}),s.jsx("span",{className:"note",children:"Recognition and customers stay here."})]});const t=e.claimed&&!e.broker_up;return s.jsxs("div",{className:"card",style:{marginBottom:16,display:"flex",gap:22,alignItems:"center",flexWrap:"wrap"},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("i",{className:`dot ${e.claimed?e.broker_up?"ok":"bad":"idle"}`}),s.jsx("strong",{style:{fontSize:13},children:e.claimed?e.broker_up?"Sending to head office":"Offline — saving locally":"Not linked to head office"})]}),s.jsxs("span",{className:"note",children:[e.accepted," recorded today"]}),e.queued>0&&s.jsxs("span",{className:"note",style:t?{color:"var(--warn)"}:void 0,children:[e.queued," waiting to send"]}),e.dropped>0&&s.jsxs("span",{className:"note",style:{color:"var(--bad)"},children:[e.dropped," lost — this PC was offline too long"]})]})}function Xf({e}){var l,i,o,u,a;const t=e.type==="person.new"?"new":e.type==="person.seen"?"seen":e.type==="person.missed"?"miss":"",n=((l=e.data)==null?void 0:l.age)??((i=e.data)==null?void 0:i.age_range),r=[(o=e.data)==null?void 0:o.gender,n,(u=e.data)==null?void 0:u.emotion].filter(Boolean).join(", ");return s.jsxs("li",{children:[s.jsx("span",{className:"when",children:Qf(e.ts)}),s.jsx("span",{className:`tag ${t}`,children:Gf(e.type)}),s.jsxs("span",{style:{flex:1,minWidth:0},children:[((a=e.data)==null?void 0:a.label)||e.camera_id,r&&s.jsxs("span",{className:"note",children:[" · ",r]})]})]})}function Gf(e){return{"person.new":"new","person.seen":"returning","person.missed":"missed","camera.up":"camera up","camera.down":"camera down","identity.merged":"merged"}[e]??e}function jr({label:e,value:t,sub:n,tone:r}){return s.jsxs("div",{className:"card stat",children:[s.jsx("h3",{children:e}),s.jsx("div",{className:"value",style:r?{color:`var(--${r})`}:void 0,children:t}),n&&s.jsx("div",{className:"sub",children:n})]})}function Zf(){const[e,t]=P.useState({}),{data:n}=Dt(()=>A.cameras(),1e4);return P.useEffect(()=>{let r=!1;return(async()=>{const l={};for(const o of n??[]){if(e[o.id]){l[o.id]=e[o.id];continue}try{l[o.id]=await A.streamURL(o.id)}catch{}}const i=Object.keys(l).length!==Object.keys(e).length||Object.keys(l).some(o=>l[o]!==e[o]);!r&&i&&t(l)})(),()=>{r=!0}},[n]),e}function Jf(e){const[t,n]=P.useState(null);return P.useEffect(()=>{let r=!0;return n(null),A.visitorPhoto(e).then(l=>{r&&n(l)}).catch(()=>{r&&n({available:!1,reason:""})}),()=>{r=!1}},[e]),t}function qf({photo:e,name:t,onBroken:n}){if(e!=null&&e.available)return s.jsx("img",{className:"avatar",src:e.url,alt:`Photo of ${t}`,onError:n});const r=String(t||"").split(/\s+/).filter(Boolean).slice(0,2).map(l=>l[0].toUpperCase()).join("")||"?";return s.jsx("div",{className:"avatar none",role:"img","aria-label":`No photo of ${t}`,children:s.jsx("span",{children:r})})}function bf({customer:e}){const{data:t,error:n,loading:r}=Dt(()=>A.visitorHistory(e.id,50),0,[e.id]);if(r)return s.jsx("p",{className:"note",children:"Loading visits…"});if(n)return s.jsxs("p",{className:"note",children:["Could not load visits: ",n]});const l=t??[];return l.length===0?s.jsx("p",{className:"note",children:"No recorded visits yet."}):s.jsx("ul",{className:"timeline",children:l.map(i=>s.jsxs("li",{children:[s.jsx("span",{className:"when",children:ep(i.occurred_at)}),s.jsxs("span",{className:"where",children:[i.site||"this store",i.camera_id?s.jsxs("span",{className:"note",children:[" · ",i.camera_id]}):null]}),i.is_new_visitor&&s.jsx("span",{className:"tag new",children:"first visit"})]},i.id))})}function ep(e){const t=new Date(e);return isNaN(t)?"—":t.toLocaleString([],{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}function tp({customer:e,onCancel:t,onDone:n}){const r=e.full_name||e.label,[l,i]=P.useState(""),[o,u]=P.useState(!1),[a,c]=P.useState(null),p=l.trim().toLowerCase()===r.trim().toLowerCase();async function v(){u(!0),c(null);try{await A.forgetCustomer(e.id),n()}catch(m){c(Te(m)),u(!1)}}return s.jsxs("div",{className:"confirm",children:[s.jsxs("h4",{children:["Erase ",r,"?"]}),s.jsxs("div",{className:"cols",children:[s.jsxs("div",{children:[s.jsx("p",{className:"lbl bad",children:"Deleted for good"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Their face data — they will not be recognised again"}),s.jsx("li",{children:"Their photo"}),s.jsx("li",{children:"Their name, phone, email and notes"})]})]}),s.jsxs("div",{children:[s.jsx("p",{className:"lbl",children:"Kept"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Past visits, with their name removed — your footfall figures do not change"}),s.jsx("li",{children:"The consent record, marked withdrawn, as proof of what was agreed"})]})]})]}),s.jsx("p",{className:"note",children:"This cannot be undone. If they come back they will be recorded as a new customer."}),a&&s.jsx("div",{className:"err",children:a}),s.jsxs("label",{className:"field",children:[s.jsxs("span",{children:["Type ",s.jsx("b",{children:r})," to confirm"]}),s.jsx("input",{value:l,onChange:m=>i(m.target.value),autoFocus:!0,autoComplete:"off",spellCheck:"false","aria-label":`Type ${r} to confirm erasure`})]}),s.jsxs("div",{className:"row",children:[s.jsx("button",{type:"button",className:"btn danger",disabled:!p||o,onClick:v,children:o?"Erasing…":"Erase permanently"}),s.jsx("button",{type:"button",className:"btn",onClick:t,disabled:o,children:"Cancel"})]})]})}function np({customer:e,session:t,onClose:n,onSaved:r}){var _;const[l,i]=P.useState({full_name:e.full_name??"",phone:e.phone??"",email:e.email??"",gender:"",date_of_birth:"",notes:"",consent:e.has_consent??!1}),[o,u]=P.useState({amount:"",items:"",notes:""}),[a,c]=P.useState(!1),[p,v]=P.useState(null),[m,g]=P.useState(!1),[x,k]=P.useState(null),O=Jf(e.id),h=x??O,d=(_=t==null?void 0:t.user)==null?void 0:_.role,f=["admin","owner","manager"].includes(d),y=j=>E=>i({...l,[j]:E.target.value});async function S(j){j.preventDefault(),c(!0),v(null);try{await A.saveProfile({visitor_id:e.id,...l});const E=parseFloat(o.amount);if(!isNaN(E)&&E>0){const V=o.items.split(",").map(L=>L.trim()).filter(Boolean);await A.recordPurchase(e.id,E,V,o.notes)}r()}catch(E){v(Te(E))}finally{c(!1)}}return s.jsx("div",{className:"drawer",onMouseDown:j=>j.target===j.currentTarget&&n(),children:s.jsxs("div",{className:"panel",children:[s.jsxs("div",{className:"who",children:[s.jsx(qf,{photo:h,name:e.full_name||e.label,onBroken:()=>k({available:!1,reason:"The photo could not be loaded."})}),s.jsxs("div",{className:"grow",children:[s.jsx("h3",{children:e.full_name||e.label}),s.jsxs("p",{className:"note",children:[e.visit_count," visit",e.visit_count===1?"":"s",e.last_seen_at&&` · last seen ${new Date(e.last_seen_at).toLocaleDateString()}`]}),h&&!h.available&&h.reason&&s.jsx("p",{className:"note",children:h.reason})]}),s.jsx("button",{type:"button",className:"btn sm",onClick:n,children:"Close"})]}),s.jsxs("form",{onSubmit:S,children:[p&&s.jsx("div",{className:"err",children:p}),s.jsxs("div",{className:"card",style:{marginBottom:14},children:[s.jsx("h3",{children:"Customer details"}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Full name"}),s.jsx("input",{value:l.full_name,onChange:y("full_name"),autoFocus:!0})]}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Phone"}),s.jsx("input",{value:l.phone,onChange:y("phone"),inputMode:"tel"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Email"}),s.jsx("input",{value:l.email,onChange:y("email"),type:"email"})]})]}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Gender"}),s.jsxs("select",{value:l.gender,onChange:y("gender"),children:[s.jsx("option",{value:"",children:"Not recorded"}),s.jsx("option",{children:"Female"}),s.jsx("option",{children:"Male"}),s.jsx("option",{children:"Other"})]})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Date of birth"}),s.jsx("input",{type:"date",value:l.date_of_birth,onChange:y("date_of_birth")})]})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Notes"}),s.jsx("textarea",{value:l.notes,onChange:y("notes"),placeholder:"Preferences, sizes, anything worth remembering"})]})]}),s.jsxs("div",{className:"card",style:{marginBottom:14},children:[s.jsx("h3",{children:"Purchase (optional)"}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Amount"}),s.jsx("input",{value:o.amount,inputMode:"decimal",placeholder:"0.00",onChange:j=>u({...o,amount:j.target.value})})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Items"}),s.jsx("input",{value:o.items,placeholder:"shirt, belt",onChange:j=>u({...o,items:j.target.value})})]})]}),s.jsx("p",{className:"note",children:"Leave the amount blank if they did not buy anything — a visit without a sale is still worth recording."})]}),s.jsxs("div",{className:"card",style:{marginBottom:16},children:[s.jsx("h3",{children:"Consent"}),s.jsxs("label",{style:{display:"flex",gap:10,alignItems:"flex-start",fontSize:13,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:l.consent,style:{marginTop:3},onChange:j=>i({...l,consent:j.target.checked})}),s.jsx("span",{children:"This customer agreed to us keeping their details and recognising them on future visits."})]}),s.jsx("p",{className:"note",style:{marginTop:10},children:"Recorded with the date and who collected it. They can withdraw it at any time, which erases their face data."})]}),s.jsxs("div",{className:"card",style:{marginBottom:14},children:[s.jsx("h3",{children:"Visits"}),s.jsx(bf,{customer:e})]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{className:"btn primary",disabled:a,children:a?"Saving…":"Save"}),s.jsx("button",{type:"button",className:"btn",onClick:n,children:"Cancel"})]}),f&&s.jsxs("div",{className:"card danger-zone",children:[s.jsx("h3",{children:"At the customer's request"}),m?s.jsx(tp,{customer:e,onCancel:()=>g(!1),onDone:r}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"note",children:"Erase this person's face data, photo and details. Their past visits stay in your footfall figures, without their name."}),s.jsx("button",{type:"button",className:"btn danger",onClick:()=>g(!0),children:"Erase this customer…"})]})]})]})]})})}function rp({session:e}){const[t,n]=P.useState(""),[r,l]=P.useState(null),{data:i,error:o,reload:u}=Dt(()=>A.customers(t,200),3e4,[t]),a=i??[],c=a.filter(p=>p.has_profile).length;return s.jsxs("div",{className:"page",children:[s.jsxs("header",{children:[s.jsx("h2",{children:"Customers"}),s.jsx("p",{children:"Everyone this business has recognised. Fill in details once and they are known at every store."})]}),o&&s.jsx("div",{className:"err",children:o}),s.jsxs("div",{className:"grid cols-4",style:{marginBottom:16},children:[s.jsx(Nr,{label:"Known people",value:a.length||"—"}),s.jsx(Nr,{label:"With details",value:c||"—",sub:a.length?`${Math.round(100*c/a.length)}% captured`:null}),s.jsx(Nr,{label:"Returning",value:a.filter(p=>p.visit_count>1).length||"—"}),s.jsx(Nr,{label:"With consent",value:a.filter(p=>p.has_consent).length||"—"})]}),s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",gap:10,marginBottom:12},children:[s.jsx("input",{className:"field",style:{flex:1,margin:0,background:"var(--ground)",border:"1px solid var(--line)",borderRadius:6,padding:"8px 10px"},placeholder:"Search by name or phone",value:t,onChange:p=>n(p.target.value)}),s.jsx("button",{className:"btn",onClick:u,children:"Refresh"})]}),a.length===0?s.jsx("div",{className:"empty",children:"No customers yet. They appear here the first time a camera sees them."}):s.jsx("div",{className:"tablewrap",children:s.jsxs("table",{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Customer"}),s.jsx("th",{children:"Phone"}),s.jsx("th",{className:"num",children:"Visits"}),s.jsx("th",{children:"First seen"}),s.jsx("th",{children:"Last seen"}),s.jsx("th",{children:"Details"})]})}),s.jsx("tbody",{children:a.map(p=>s.jsxs("tr",{className:"click",onClick:()=>l(p),children:[s.jsx("td",{children:p.full_name||s.jsx("span",{className:"note",children:p.label})}),s.jsx("td",{className:"mono",children:p.phone||"—"}),s.jsx("td",{className:"num",children:p.visit_count}),s.jsx("td",{children:Zs(p.first_seen_at)}),s.jsx("td",{children:Zs(p.last_seen_at)}),s.jsx("td",{children:p.has_profile?s.jsxs("span",{className:"pill ok",children:[s.jsx("i",{className:"dot ok"}),"captured"]}):s.jsxs("span",{className:"pill warn",children:[s.jsx("i",{className:"dot warn"}),"needed"]})})]},p.id))})]})})]}),r&&s.jsx(np,{customer:r,session:e,onClose:()=>l(null),onSaved:()=>{l(null),u()}})]})}function Nr({label:e,value:t,sub:n}){return s.jsxs("div",{className:"card stat",children:[s.jsx("h3",{children:e}),s.jsx("div",{className:"value",children:t}),n&&s.jsx("div",{className:"sub",children:n})]})}const tn=[{id:"hikvision",label:"Hikvision",path:"/Streaming/Channels/101",note:"Channel 1, main stream. Use /Streaming/Channels/102 for the lower-quality sub stream."},{id:"dahua",label:"Dahua",path:"/cam/realmonitor?channel=1&subtype=0",note:"Channel 1, main stream. subtype=1 is the sub stream."},{id:"cpplus",label:"CP Plus",path:"/cam/realmonitor?channel=1&subtype=0",note:"CP Plus cameras use the Dahua stream path."},{id:"uniview",label:"Uniview",path:"/media/video1",note:"Some older Uniview models use /video1 instead."},{id:"tplink",label:"TP-Link / Tapo",path:"/stream1",note:"Tapo cameras need a separate camera account created in the Tapo app — your Tapo login will not work."},{id:"reolink",label:"Reolink",path:"/h264Preview_01_main",note:"Use /h264Preview_01_sub for the lower-quality stream."},{id:"amcrest",label:"Amcrest",path:"/cam/realmonitor?channel=1&subtype=0",note:"Amcrest cameras use the Dahua stream path."},{id:"axis",label:"Axis",path:"/axis-media/media.amp",note:""},{id:"onvif",label:"Other (ONVIF)",path:"/onvif1",note:"Many generic cameras answer here. If it does not work, look for “RTSP” in the camera’s own app."},{id:"manual",label:"I know the path",path:"",note:""}],ql=e=>tn.find(t=>t.id===e)||tn[tn.length-1],pc={id:"",host:"",port:554,path:"",username:"",password:"",max_width:1280};function lp(){const{data:e,error:t,reload:n}=Dt(()=>A.cameras(),8e3),[r,l]=P.useState(null),[i,o]=P.useState(null),u=e??[];async function a(c){if(confirm(`Remove camera "${c}"? Recognition from it stops immediately.`))try{await A.deleteCamera(c),n()}catch(p){alert(Te(p))}}return s.jsxs("div",{className:"page",children:[s.jsxs("header",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end"},children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Cameras"}),s.jsx("p",{children:"Add a camera, check it can see faces properly, then it starts working."})]}),s.jsx("button",{className:"btn primary",onClick:()=>l({...pc}),children:"Add camera"})]}),t&&s.jsx("div",{className:"err",children:t}),s.jsx("div",{className:"card",children:u.length===0?s.jsx("div",{className:"empty",children:"No cameras yet."}):s.jsx("div",{className:"tablewrap",children:s.jsxs("table",{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Address"}),s.jsx("th",{children:"Status"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:u.map(c=>s.jsxs("tr",{children:[s.jsx("td",{children:c.id}),s.jsx("td",{className:"mono",children:c.url}),s.jsx("td",{children:c.connected===void 0?s.jsxs("span",{className:"pill",children:[s.jsx("i",{className:"dot idle"}),"stopped"]}):c.connected?s.jsxs("span",{className:"pill ok",children:[s.jsx("i",{className:"dot ok"}),"live"]}):s.jsxs("span",{className:"pill bad",children:[s.jsx("i",{className:"dot bad"}),"offline"]})}),s.jsxs("td",{style:{textAlign:"right",whiteSpace:"nowrap"},children:[s.jsx("button",{className:"btn sm",onClick:()=>o(c.id),children:"Check placement"})," ",s.jsx("button",{className:"btn sm",onClick:()=>l(c),children:"Edit"})," ",s.jsx("button",{className:"btn sm danger",onClick:()=>a(c.id),children:"Remove"})]})]},c.id))})]})})}),r&&s.jsx(ip,{cam:r,onClose:()=>l(null),onSaved:()=>{l(null),n()}}),i&&s.jsx(op,{id:i,onClose:()=>o(null)})]})}function ip({cam:e,onClose:t,onSaved:n}){const r=!e.id,[l,i]=P.useState({...pc,...e,password:"",path:e.path||(r?tn[0].path:"")}),[o,u]=P.useState(r?tn[0].id:"manual"),[a,c]=P.useState(null),[p,v]=P.useState(null),[m,g]=P.useState(null),x=f=>y=>i({...l,[f]:y.target.value});function k(f){const y=ql(f.target.value);u(y.id),i(S=>({...S,path:y.path||S.path}))}function O(){const f={};for(const[y,S]of Object.entries(l))S===""||S===null||S===void 0||(f[y]=y==="port"||y==="max_width"?Number(S):S);return f}async function h(){v("test"),g(null),c(null);try{c(await A.testCamera(O()))}catch(f){g(Te(f))}finally{v(null)}}async function d(f){f.preventDefault(),v("save"),g(null);try{await A.saveCamera(r?"":e.id,O()),n()}catch(y){g(Te(y))}finally{v(null)}}return s.jsx("div",{className:"drawer",onMouseDown:f=>f.target===f.currentTarget&&t(),children:s.jsxs("div",{className:"panel",children:[s.jsx("button",{className:"btn sm close",onClick:t,children:"Close"}),s.jsx("h3",{children:r?"Add camera":e.id}),s.jsx("p",{className:"note",style:{marginBottom:18},children:"Test the connection before saving — a wrong address is the most common mistake."}),s.jsxs("form",{onSubmit:d,children:[m&&s.jsx("div",{className:"err",children:m}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Name"}),s.jsx("input",{value:l.id,onChange:x("id"),disabled:!r,placeholder:"entrance",required:!0,autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Make of camera"}),s.jsx("select",{value:o,onChange:k,children:tn.map(f=>s.jsx("option",{value:f.id,children:f.label},f.id))})]}),ql(o).note&&s.jsx("p",{className:"note",style:{marginTop:-8,marginBottom:12},children:ql(o).note}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Camera address"}),s.jsx("input",{value:l.host,onChange:x("host"),placeholder:"192.168.0.138",autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Port"}),s.jsx("input",{value:l.port,onChange:x("port"),inputMode:"numeric",autoComplete:"off"})]})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Stream path"}),s.jsx("input",{value:l.path,onChange:x("path"),placeholder:"/ch0_0.264",autoComplete:"off"})]}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Username"}),s.jsx("input",{value:l.username,onChange:x("username"),name:"camera-account",autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:l.password,onChange:x("password"),name:"camera-secret",autoComplete:"new-password",placeholder:e.has_password?"(unchanged)":""})]})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{type:"button",className:"btn",onClick:h,disabled:!!p,children:p==="test"?"Connecting…":"Test connection"}),s.jsx("button",{className:"btn primary",disabled:!!p||!l.id,children:p==="save"?"Saving…":"Save"})]}),a&&s.jsx("div",{style:{marginTop:14},children:a.ok?s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{color:"var(--ok)",fontSize:13},children:["Connected — ",a.width,"×",a.height]}),a.snapshot&&s.jsx("img",{alt:"Camera preview",style:{width:"100%",marginTop:8,borderRadius:6,border:"1px solid var(--line)"},src:`data:image/jpeg;base64,${a.snapshot}`})]}):s.jsx("div",{className:"err",children:a.error})})]})]})})}function op({id:e,onClose:t}){var c,p;const[n,r]=P.useState({verdict:"starting",advice:[]}),[l,i]=P.useState(null),o=P.useRef(null);P.useEffect(()=>{let v=!0;return(async()=>{try{r(await A.startPlacement(e,25)),o.current=setInterval(async()=>{try{const m=await A.placementResult(e);if(!v)return;r(m),m.running||clearInterval(o.current)}catch(m){v&&i(Te(m))}},1e3)}catch(m){v&&i(Te(m))}})(),()=>{v=!1,clearInterval(o.current)}},[e]);const u={good:"ok",marginal:"warn",poor:"bad",artifact:"bad",no_faces:"warn",inconclusive:"warn"}[n.verdict],a=n.seconds?Math.min(100,n.elapsed/n.seconds*100):0;return s.jsx("div",{className:"drawer",onMouseDown:v=>v.target===v.currentTarget&&t(),children:s.jsxs("div",{className:"panel",children:[s.jsx("button",{className:"btn sm close",onClick:t,children:"Close"}),s.jsxs("h3",{children:["Placement check — ",e]}),s.jsx("p",{className:"note",style:{marginBottom:18},children:"Walk past the camera the way a customer would, a few times."}),l&&s.jsx("div",{className:"err",children:l}),s.jsxs("div",{className:"card",children:[s.jsx("div",{style:{fontSize:15,fontWeight:600,color:u?`var(--${u})`:"var(--ink)"},children:n.headline||"Starting…"}),n.running&&s.jsx("div",{style:{height:5,background:"var(--surface-2)",borderRadius:3,overflow:"hidden",margin:"12px 0"},children:s.jsx("div",{style:{height:"100%",width:`${a}%`,background:"var(--accent)",transition:"width .4s linear"}})}),((c=n.advice)==null?void 0:c.length)>0&&s.jsx("ul",{style:{margin:"12px 0 0 18px",fontSize:13,color:"var(--ink-2)"},children:n.advice.map((v,m)=>s.jsx("li",{style:{marginBottom:5},children:v},m))}),((p=n.quality)==null?void 0:p.n)>0&&s.jsxs("p",{className:"note",style:{marginTop:12},children:[n.quality.n," face",n.quality.n===1?"":"s"," seen · median quality ",n.quality.p50," · gate ",n.gate," ·"," ",Math.round((n.quality.fraction_below_gate??0)*100),"% below it"]})]})]})})}const sp=[{id:"live",label:"Live",glyph:"◉",View:fc},{id:"customers",label:"Customers",glyph:"☺",View:rp,cloud:!0},{id:"cameras",label:"Cameras",glyph:"▢",View:lp}];function up(){var p,v,m;const[e,t]=P.useState(null),[n,r]=P.useState("live"),[l,i]=P.useState(!0),[o,u]=P.useState(!1);if(P.useEffect(()=>{(async()=>{try{t(await A.session())}catch{t(null)}i(!1)})()},[]),!Wf())return s.jsx("div",{className:"login",children:s.jsxs("div",{className:"box",children:[s.jsx("h1",{children:"Behavision"}),s.jsx("p",{className:"lead",children:"This is the Behavision window running outside the app, so it has no connection to the recognition engine. Launch the Behavision application instead."})]})});if(l)return s.jsx("div",{className:"login",children:s.jsx("p",{className:"note",children:"Starting…"})});if(!(e!=null&&e.claimed)&&!(e!=null&&e.standalone))return s.jsx(Js,{onDone:t});if(!(e!=null&&e.standalone)&&!(e!=null&&e.logged_in))return s.jsx(Kf,{onDone:t});const a=sp.filter(g=>!g.cloud||!e.standalone),c=((p=a.find(g=>g.id===n))==null?void 0:p.View)??fc;return o?s.jsx(Js,{onDone:g=>{u(!1),t(g)},onCancel:()=>u(!1)}):s.jsxs("div",{className:"shell",children:[s.jsxs("aside",{className:"side",children:[s.jsxs("div",{className:"brand",children:[s.jsx("h1",{children:"Behavision"}),s.jsx("p",{children:e.site_name||((v=e.user)==null?void 0:v.client_name)||"Store"})]}),s.jsx("nav",{className:"nav",children:a.map(g=>s.jsxs("button",{onClick:()=>r(g.id),"aria-current":g.id===n?"page":void 0,children:[s.jsx("span",{className:"glyph",children:g.glyph}),g.label]},g.id))}),s.jsx(ap,{}),s.jsx("div",{style:{padding:"10px 12px 14px",borderTop:"1px solid var(--line-soft)"},children:e.standalone?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"note",style:{marginBottom:8},children:"Running on its own"}),s.jsx("button",{className:"btn sm",style:{width:"100%"},onClick:()=>u(!0),children:"Link to head office"})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"note",style:{marginBottom:8},children:(m=e.user)==null?void 0:m.email}),s.jsx("button",{className:"btn sm",style:{width:"100%"},onClick:async()=>t(await A.logout()),children:"Sign out"})]})})]}),s.jsx("main",{className:"main",children:s.jsx(c,{session:e})})]})}function ap(){const{data:e,reload:t}=Dt(()=>A.engineStatus(),5e3),[n,r]=P.useState(!1),l=e??{state:"stopped"},i=P.useCallback(async v=>{r(!0);try{await v()}catch(m){alert(Te(m))}finally{r(!1),t()}},[t]),o=l.state==="running",u=Object.values(l.cameras??{}),a=u.filter(Boolean).length;let c="idle",p="Stopped";return l.state==="failed"||l.state==="backoff"?(c="bad",p="Not running"):o&&!l.reachable?(c="warn",p="Starting…"):o&&u.length===0?(c="warn",p="No cameras"):o&&a===0?(c="bad",p="No camera connected"):o&&ai(A.startEngine),children:"Start"}),s.jsx("button",{className:"btn sm",disabled:n||!o,onClick:()=>i(A.stopEngine),children:"Stop"})]})]})}cc(document.getElementById("root")).render(s.jsx(Lc.StrictMode,{children:s.jsx(up,{})})); +`+i.stack}return{value:e,source:t,stack:l,digest:null}}function Xl(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Li(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var gf=typeof WeakMap=="function"?WeakMap:Map;function Ia(e,t,n){n=Ye(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){rl||(rl=!0,Ai=r),Li(e,t)},n}function Fa(e,t,n){n=Ye(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){Li(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){Li(e,t),typeof r!="function"&&(dt===null?dt=new Set([this]):dt.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),n}function Ls(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new gf;var l=new Set;r.set(t,l)}else l=r.get(t),l===void 0&&(l=new Set,r.set(t,l));l.has(n)||(l.add(n),e=Rf.bind(null,e,t,n),t.then(e,e))}function Rs(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ds(e,t,n,r,l){return e.mode&1?(e.flags|=65536,e.lanes=l,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Ye(-1,1),t.tag=2,ct(n,t,1))),n.lanes|=1),e)}var wf=qe.ReactCurrentOwner,pe=!1;function ue(e,t,n,r){t.child=e===null?fa(t,null,n,r):on(t,e.child,n,r)}function Os(e,t,n,r,l){n=n.render;var i=t.ref;return bt(t,l),r=No(e,t,n,r,i,l),n=Co(),e!==null&&!pe?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,Je(e,t,l)):(B&&n&&fo(t),t.flags|=1,ue(e,t,r,l),t.child)}function Ms(e,t,n,r,l){if(e===null){var i=n.type;return typeof i=="function"&&!Mo(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=i,Ua(e,t,i,r,l)):(e=Ir(n.type,null,r,t,t.mode,l),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!(e.lanes&l)){var o=i.memoizedProps;if(n=n.compare,n=n!==null?n:Hn,n(o,r)&&e.ref===t.ref)return Je(e,t,l)}return t.flags|=1,e=pt(i,r),e.ref=t.ref,e.return=t,t.child=e}function Ua(e,t,n,r,l){if(e!==null){var i=e.memoizedProps;if(Hn(i,r)&&e.ref===t.ref)if(pe=!1,t.pendingProps=r=i,(e.lanes&l)!==0)e.flags&131072&&(pe=!0);else return t.lanes=e.lanes,Je(e,t,l)}return Ri(e,t,n,r,l)}function $a(e,t,n){var r=t.pendingProps,l=r.children,i=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},F(Xt,ye),ye|=n;else{if(!(n&1073741824))return e=i!==null?i.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,F(Xt,ye),ye|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,F(Xt,ye),ye|=r}else i!==null?(r=i.baseLanes|n,t.memoizedState=null):r=n,F(Xt,ye),ye|=r;return ue(e,t,l,n),t.child}function Ba(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Ri(e,t,n,r,l){var i=me(n)?Pt:se.current;return i=rn(t,i),bt(t,l),n=No(e,t,n,r,i,l),r=Co(),e!==null&&!pe?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,Je(e,t,l)):(B&&r&&fo(t),t.flags|=1,ue(e,t,n,l),t.child)}function Is(e,t,n,r,l){if(me(n)){var i=!0;Yr(t)}else i=!1;if(bt(t,l),t.stateNode===null)Dr(e,t),Ma(t,n,r),zi(t,n,r,l),r=!0;else if(e===null){var o=t.stateNode,u=t.memoizedProps;o.props=u;var a=o.context,c=n.contextType;typeof c=="object"&&c!==null?c=_e(c):(c=me(n)?Pt:se.current,c=rn(t,c));var p=n.getDerivedStateFromProps,v=typeof p=="function"||typeof o.getSnapshotBeforeUpdate=="function";v||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(u!==r||a!==c)&&zs(t,o,r,c),tt=!1;var m=t.memoizedState;o.state=m,qr(t,r,o,l),a=t.memoizedState,u!==r||m!==a||he.current||tt?(typeof p=="function"&&(Ti(t,n,p,r),a=t.memoizedState),(u=tt||Ts(t,n,u,r,m,a,c))?(v||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=a),o.props=r,o.state=a,o.context=c,r=u):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,ha(e,t),u=t.memoizedProps,c=t.type===t.elementType?u:Re(t.type,u),o.props=c,v=t.pendingProps,m=o.context,a=n.contextType,typeof a=="object"&&a!==null?a=_e(a):(a=me(n)?Pt:se.current,a=rn(t,a));var g=n.getDerivedStateFromProps;(p=typeof g=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(u!==v||m!==a)&&zs(t,o,r,a),tt=!1,m=t.memoizedState,o.state=m,qr(t,r,o,l);var x=t.memoizedState;u!==v||m!==x||he.current||tt?(typeof g=="function"&&(Ti(t,n,g,r),x=t.memoizedState),(c=tt||Ts(t,n,c,r,m,x,a)||!1)?(p||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(r,x,a),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(r,x,a)),typeof o.componentDidUpdate=="function"&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof o.componentDidUpdate!="function"||u===e.memoizedProps&&m===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&m===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=x),o.props=r,o.state=x,o.context=a,r=c):(typeof o.componentDidUpdate!="function"||u===e.memoizedProps&&m===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&m===e.memoizedState||(t.flags|=1024),r=!1)}return Di(e,t,n,r,i,l)}function Di(e,t,n,r,l,i){Ba(e,t);var o=(t.flags&128)!==0;if(!r&&!o)return l&&Ss(t,n,!1),Je(e,t,i);r=t.stateNode,wf.current=t;var u=o&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&o?(t.child=on(t,e.child,null,i),t.child=on(t,null,u,i)):ue(e,t,u,i),t.memoizedState=r.state,l&&Ss(t,n,!0),t.child}function Aa(e){var t=e.stateNode;t.pendingContext?xs(e,t.pendingContext,t.pendingContext!==t.context):t.context&&xs(e,t.context,!1),xo(e,t.containerInfo)}function Fs(e,t,n,r,l){return ln(),ho(l),t.flags|=256,ue(e,t,n,r),t.child}var Oi={dehydrated:null,treeContext:null,retryLane:0};function Mi(e){return{baseLanes:e,cachePool:null,transitions:null}}function Va(e,t,n){var r=t.pendingProps,l=H.current,i=!1,o=(t.flags&128)!==0,u;if((u=o)||(u=e!==null&&e.memoizedState===null?!1:(l&2)!==0),u?(i=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(l|=1),F(H,l&1),e===null)return _i(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(o=r.children,e=r.fallback,i?(r=t.mode,i=t.child,o={mode:"hidden",children:o},!(r&1)&&i!==null?(i.childLanes=0,i.pendingProps=o):i=gl(o,r,0,null),e=_t(e,r,n,null),i.return=t,e.return=t,i.sibling=e,t.child=i,t.child.memoizedState=Mi(n),t.memoizedState=Oi,e):Po(t,o));if(l=e.memoizedState,l!==null&&(u=l.dehydrated,u!==null))return xf(e,t,o,r,u,l,n);if(i){i=r.fallback,o=t.mode,l=e.child,u=l.sibling;var a={mode:"hidden",children:r.children};return!(o&1)&&t.child!==l?(r=t.child,r.childLanes=0,r.pendingProps=a,t.deletions=null):(r=pt(l,a),r.subtreeFlags=l.subtreeFlags&14680064),u!==null?i=pt(u,i):(i=_t(i,o,n,null),i.flags|=2),i.return=t,r.return=t,r.sibling=i,t.child=r,r=i,i=t.child,o=e.child.memoizedState,o=o===null?Mi(n):{baseLanes:o.baseLanes|n,cachePool:null,transitions:o.transitions},i.memoizedState=o,i.childLanes=e.childLanes&~n,t.memoizedState=Oi,r}return i=e.child,e=i.sibling,r=pt(i,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function Po(e,t){return t=gl({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function wr(e,t,n,r){return r!==null&&ho(r),on(t,e.child,null,n),e=Po(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function xf(e,t,n,r,l,i,o){if(n)return t.flags&256?(t.flags&=-257,r=Xl(Error(w(422))),wr(e,t,o,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(i=r.fallback,l=t.mode,r=gl({mode:"visible",children:r.children},l,0,null),i=_t(i,l,o,null),i.flags|=2,r.return=t,i.return=t,r.sibling=i,t.child=r,t.mode&1&&on(t,e.child,null,o),t.child.memoizedState=Mi(o),t.memoizedState=Oi,i);if(!(t.mode&1))return wr(e,t,o,null);if(l.data==="$!"){if(r=l.nextSibling&&l.nextSibling.dataset,r)var u=r.dgst;return r=u,i=Error(w(419)),r=Xl(i,r,void 0),wr(e,t,o,r)}if(u=(o&e.childLanes)!==0,pe||u){if(r=ee,r!==null){switch(o&-o){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}l=l&(r.suspendedLanes|o)?0:l,l!==0&&l!==i.retryLane&&(i.retryLane=l,Ze(e,l),Ie(r,e,l,-1))}return Oo(),r=Xl(Error(w(421))),wr(e,t,o,r)}return l.data==="$?"?(t.flags|=128,t.child=e.child,t=Df.bind(null,e),l._reactRetry=t,null):(e=i.treeContext,ge=at(l.nextSibling),we=t,B=!0,Oe=null,e!==null&&(je[Ne++]=Qe,je[Ne++]=Ke,je[Ne++]=Tt,Qe=e.id,Ke=e.overflow,Tt=t),t=Po(t,r.children),t.flags|=4096,t)}function Us(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),Pi(e.return,t,n)}function Gl(e,t,n,r,l){var i=e.memoizedState;i===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(i.isBackwards=t,i.rendering=null,i.renderingStartTime=0,i.last=r,i.tail=n,i.tailMode=l)}function Ha(e,t,n){var r=t.pendingProps,l=r.revealOrder,i=r.tail;if(ue(e,t,r.children,n),r=H.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Us(e,n,t);else if(e.tag===19)Us(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(F(H,r),!(t.mode&1))t.memoizedState=null;else switch(l){case"forwards":for(n=t.child,l=null;n!==null;)e=n.alternate,e!==null&&br(e)===null&&(l=n),n=n.sibling;n=l,n===null?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),Gl(t,!1,l,n,i);break;case"backwards":for(n=null,l=t.child,t.child=null;l!==null;){if(e=l.alternate,e!==null&&br(e)===null){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}Gl(t,!0,n,null,i);break;case"together":Gl(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Dr(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Je(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Lt|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(w(153));if(t.child!==null){for(e=t.child,n=pt(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=pt(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function Sf(e,t,n){switch(t.tag){case 3:Aa(t),ln();break;case 5:ma(t);break;case 1:me(t.type)&&Yr(t);break;case 4:xo(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,l=t.memoizedProps.value;F(Zr,r._currentValue),r._currentValue=l;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(F(H,H.current&1),t.flags|=128,null):n&t.child.childLanes?Va(e,t,n):(F(H,H.current&1),e=Je(e,t,n),e!==null?e.sibling:null);F(H,H.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return Ha(e,t,n);t.flags|=128}if(l=t.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),F(H,H.current),r)break;return null;case 22:case 23:return t.lanes=0,$a(e,t,n)}return Je(e,t,n)}var Wa,Ii,Qa,Ka;Wa=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};Ii=function(){};Qa=function(e,t,n,r){var l=e.memoizedProps;if(l!==r){e=t.stateNode,Ct(Ve.current);var i=null;switch(n){case"input":l=li(e,l),r=li(e,r),i=[];break;case"select":l=Q({},l,{value:void 0}),r=Q({},r,{value:void 0}),i=[];break;case"textarea":l=si(e,l),r=si(e,r),i=[];break;default:typeof l.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Qr)}ai(n,r);var o;n=null;for(c in l)if(!r.hasOwnProperty(c)&&l.hasOwnProperty(c)&&l[c]!=null)if(c==="style"){var u=l[c];for(o in u)u.hasOwnProperty(o)&&(n||(n={}),n[o]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(In.hasOwnProperty(c)?i||(i=[]):(i=i||[]).push(c,null));for(c in r){var a=r[c];if(u=l!=null?l[c]:void 0,r.hasOwnProperty(c)&&a!==u&&(a!=null||u!=null))if(c==="style")if(u){for(o in u)!u.hasOwnProperty(o)||a&&a.hasOwnProperty(o)||(n||(n={}),n[o]="");for(o in a)a.hasOwnProperty(o)&&u[o]!==a[o]&&(n||(n={}),n[o]=a[o])}else n||(i||(i=[]),i.push(c,n)),n=a;else c==="dangerouslySetInnerHTML"?(a=a?a.__html:void 0,u=u?u.__html:void 0,a!=null&&u!==a&&(i=i||[]).push(c,a)):c==="children"?typeof a!="string"&&typeof a!="number"||(i=i||[]).push(c,""+a):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(In.hasOwnProperty(c)?(a!=null&&c==="onScroll"&&U("scroll",e),i||u===a||(i=[])):(i=i||[]).push(c,a))}n&&(i=i||[]).push("style",n);var c=i;(t.updateQueue=c)&&(t.flags|=4)}};Ka=function(e,t,n,r){n!==r&&(t.flags|=4)};function Sn(e,t){if(!B)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function ie(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags&14680064,r|=l.flags&14680064,l.return=e,l=l.sibling;else for(l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function kf(e,t,n){var r=t.pendingProps;switch(po(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ie(t),null;case 1:return me(t.type)&&Kr(),ie(t),null;case 3:return r=t.stateNode,sn(),$(he),$(se),ko(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(yr(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Oe!==null&&(Wi(Oe),Oe=null))),Ii(e,t),ie(t),null;case 5:So(t);var l=Ct(Xn.current);if(n=t.type,e!==null&&t.stateNode!=null)Qa(e,t,n,r,l),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(w(166));return ie(t),null}if(e=Ct(Ve.current),yr(t)){r=t.stateNode,n=t.type;var i=t.memoizedProps;switch(r[Be]=t,r[Kn]=i,e=(t.mode&1)!==0,n){case"dialog":U("cancel",r),U("close",r);break;case"iframe":case"object":case"embed":U("load",r);break;case"video":case"audio":for(l=0;l<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Be]=t,e[Kn]=r,Wa(e,t,!1,!1),t.stateNode=e;e:{switch(o=ci(n,r),n){case"dialog":U("cancel",e),U("close",e),l=r;break;case"iframe":case"object":case"embed":U("load",e),l=r;break;case"video":case"audio":for(l=0;lan&&(t.flags|=128,r=!0,Sn(i,!1),t.lanes=4194304)}else{if(!r)if(e=br(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Sn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!B)return ie(t),null}else 2*X()-i.renderingStartTime>an&&n!==1073741824&&(t.flags|=128,r=!0,Sn(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=X(),t.sibling=null,n=H.current,F(H,r?n&1|2:n&1),t):(ie(t),null);case 22:case 23:return Do(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ye&1073741824&&(ie(t),t.subtreeFlags&6&&(t.flags|=8192)):ie(t),null;case 24:return null;case 25:return null}throw Error(w(156,t.tag))}function jf(e,t){switch(po(t),t.tag){case 1:return me(t.type)&&Kr(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return sn(),$(he),$(se),ko(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return So(t),null;case 13:if($(H),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(w(340));ln()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return $(H),null;case 4:return sn(),null;case 10:return yo(t.type._context),null;case 22:case 23:return Do(),null;case 24:return null;default:return null}}var xr=!1,oe=!1,Nf=typeof WeakSet=="function"?WeakSet:Set,N=null;function Yt(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){K(e,t,r)}else n.current=null}function Fi(e,t,n){try{n()}catch(r){K(e,t,r)}}var $s=!1;function Cf(e,t){if(xi=Vr,e=Ju(),co(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,u=-1,a=-1,c=0,p=0,v=e,m=null;t:for(;;){for(var g;v!==n||l!==0&&v.nodeType!==3||(u=o+l),v!==i||r!==0&&v.nodeType!==3||(a=o+r),v.nodeType===3&&(o+=v.nodeValue.length),(g=v.firstChild)!==null;)m=v,v=g;for(;;){if(v===e)break t;if(m===n&&++c===l&&(u=o),m===i&&++p===r&&(a=o),(g=v.nextSibling)!==null)break;v=m,m=v.parentNode}v=g}n=u===-1||a===-1?null:{start:u,end:a}}else n=null}n=n||{start:0,end:0}}else n=null;for(Si={focusedElem:e,selectionRange:n},Vr=!1,N=t;N!==null;)if(t=N,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,N=e;else for(;N!==null;){t=N;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var k=x.memoizedProps,O=x.memoizedState,h=t.stateNode,d=h.getSnapshotBeforeUpdate(t.elementType===t.type?k:Re(t.type,k),O);h.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var f=t.stateNode.containerInfo;f.nodeType===1?f.textContent="":f.nodeType===9&&f.documentElement&&f.removeChild(f.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(w(163))}}catch(y){K(t,t.return,y)}if(e=t.sibling,e!==null){e.return=t.return,N=e;break}N=t.return}return x=$s,$s=!1,x}function Dn(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Fi(t,n,i)}l=l.next}while(l!==r)}}function vl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ui(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ya(e){var t=e.alternate;t!==null&&(e.alternate=null,Ya(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Be],delete t[Kn],delete t[Ni],delete t[sf],delete t[uf])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Xa(e){return e.tag===5||e.tag===3||e.tag===4}function Bs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Xa(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function $i(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Qr));else if(r!==4&&(e=e.child,e!==null))for($i(e,t,n),e=e.sibling;e!==null;)$i(e,t,n),e=e.sibling}function Bi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Bi(e,t,n),e=e.sibling;e!==null;)Bi(e,t,n),e=e.sibling}var te=null,De=!1;function be(e,t,n){for(n=n.child;n!==null;)Ga(e,t,n),n=n.sibling}function Ga(e,t,n){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(ul,n)}catch{}switch(n.tag){case 5:oe||Yt(n,t);case 6:var r=te,l=De;te=null,be(e,t,n),te=r,De=l,te!==null&&(De?(e=te,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):te.removeChild(n.stateNode));break;case 18:te!==null&&(De?(e=te,n=n.stateNode,e.nodeType===8?Vl(e.parentNode,n):e.nodeType===1&&Vl(e,n),An(e)):Vl(te,n.stateNode));break;case 4:r=te,l=De,te=n.stateNode.containerInfo,De=!0,be(e,t,n),te=r,De=l;break;case 0:case 11:case 14:case 15:if(!oe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Fi(n,t,o),l=l.next}while(l!==r)}be(e,t,n);break;case 1:if(!oe&&(Yt(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){K(n,t,u)}be(e,t,n);break;case 21:be(e,t,n);break;case 22:n.mode&1?(oe=(r=oe)||n.memoizedState!==null,be(e,t,n),oe=r):be(e,t,n);break;default:be(e,t,n)}}function As(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Nf),t.forEach(function(r){var l=Of.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Le(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=X()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*_f(r/1960))-r,10e?16:e,it===null)var r=!1;else{if(e=it,it=null,ll=0,D&6)throw Error(w(331));var l=D;for(D|=4,N=e.current;N!==null;){var i=N,o=i.child;if(N.flags&16){var u=i.deletions;if(u!==null){for(var a=0;aX()-Lo?Et(e,0):zo|=n),ve(e,t)}function rc(e,t){t===0&&(e.mode&1?(t=dr,dr<<=1,!(dr&130023424)&&(dr=4194304)):t=1);var n=ae();e=Ze(e,t),e!==null&&(er(e,t,n),ve(e,n))}function Df(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),rc(e,n)}function Of(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(w(314))}r!==null&&r.delete(t),rc(e,n)}var lc;lc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||he.current)pe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pe=!1,Sf(e,t,n);pe=!!(e.flags&131072)}else pe=!1,B&&t.flags&1048576&&ua(t,Gr,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Dr(e,t),e=t.pendingProps;var l=rn(t,se.current);bt(t,n),l=No(null,t,r,e,l,n);var i=Co();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,me(r)?(i=!0,Yr(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,wo(t),l.updater=ml,t.stateNode=l,l._reactInternals=t,zi(t,r,e,n),t=Di(null,t,r,!0,i,n)):(t.tag=0,B&&i&&fo(t),ue(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Dr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=If(r),e=Re(r,e),l){case 0:t=Ri(null,t,r,e,n);break e;case 1:t=Is(null,t,r,e,n);break e;case 11:t=Os(null,t,r,e,n);break e;case 14:t=Ms(null,t,r,Re(r.type,e),n);break e}throw Error(w(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Ri(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Is(e,t,r,l,n);case 3:e:{if(Aa(t),e===null)throw Error(w(387));r=t.pendingProps,i=t.memoizedState,l=i.element,ha(e,t),qr(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=un(Error(w(423)),t),t=Fs(e,t,r,n,l);break e}else if(r!==l){l=un(Error(w(424)),t),t=Fs(e,t,r,n,l);break e}else for(ge=at(t.stateNode.containerInfo.firstChild),we=t,B=!0,Oe=null,n=fa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ln(),r===l){t=Je(e,t,n);break e}ue(e,t,r,n)}t=t.child}return t;case 5:return ma(t),e===null&&_i(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,ki(r,l)?o=null:i!==null&&ki(r,i)&&(t.flags|=32),Ba(e,t),ue(e,t,o,n),t.child;case 6:return e===null&&_i(t),null;case 13:return Va(e,t,n);case 4:return xo(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=on(t,null,r,n):ue(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Os(e,t,r,l,n);case 7:return ue(e,t,t.pendingProps,n),t.child;case 8:return ue(e,t,t.pendingProps.children,n),t.child;case 12:return ue(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,o=l.value,F(Zr,r._currentValue),r._currentValue=o,i!==null)if(Fe(i.value,o)){if(i.children===l.children&&!he.current){t=Je(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var u=i.dependencies;if(u!==null){o=i.child;for(var a=u.firstContext;a!==null;){if(a.context===r){if(i.tag===1){a=Ye(-1,n&-n),a.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var p=c.pending;p===null?a.next=a:(a.next=p.next,p.next=a),c.pending=a}}i.lanes|=n,a=i.alternate,a!==null&&(a.lanes|=n),Pi(i.return,n,t),u.lanes|=n;break}a=a.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(w(341));o.lanes|=n,u=o.alternate,u!==null&&(u.lanes|=n),Pi(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ue(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,bt(t,n),l=_e(l),r=r(l),t.flags|=1,ue(e,t,r,n),t.child;case 14:return r=t.type,l=Re(r,t.pendingProps),l=Re(r.type,l),Ms(e,t,r,l,n);case 15:return Ua(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Re(r,l),Dr(e,t),t.tag=1,me(r)?(e=!0,Yr(t)):e=!1,bt(t,n),Ma(t,r,l),zi(t,r,l,n),Di(null,t,r,!0,e,n);case 19:return Ha(e,t,n);case 22:return $a(e,t,n)}throw Error(w(156,t.tag))};function ic(e,t){return Ru(e,t)}function Mf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ce(e,t,n,r){return new Mf(e,t,n,r)}function Mo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function If(e){if(typeof e=="function")return Mo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===bi)return 11;if(e===eo)return 14}return 2}function pt(e,t){var n=e.alternate;return n===null?(n=Ce(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Ir(e,t,n,r,l,i){var o=2;if(r=e,typeof e=="function")Mo(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Ut:return _t(n.children,l,i,t);case qi:o=8,l|=8;break;case ei:return e=Ce(12,n,t,l|2),e.elementType=ei,e.lanes=i,e;case ti:return e=Ce(13,n,t,l),e.elementType=ti,e.lanes=i,e;case ni:return e=Ce(19,n,t,l),e.elementType=ni,e.lanes=i,e;case mu:return gl(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case pu:o=10;break e;case hu:o=9;break e;case bi:o=11;break e;case eo:o=14;break e;case et:o=16,r=null;break e}throw Error(w(130,e==null?e:typeof e,""))}return t=Ce(o,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function _t(e,t,n,r){return e=Ce(7,e,r,t),e.lanes=n,e}function gl(e,t,n,r){return e=Ce(22,e,r,t),e.elementType=mu,e.lanes=n,e.stateNode={isHidden:!1},e}function Zl(e,t,n){return e=Ce(6,e,null,t),e.lanes=n,e}function Jl(e,t,n){return t=Ce(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Ff(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ll(0),this.expirationTimes=Ll(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ll(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Io(e,t,n,r,l,i,o,u,a){return e=new Ff(e,t,n,u,a),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ce(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wo(i),e}function Uf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ac)}catch(e){console.error(e)}}ac(),au.exports=Se;var Hf=au.exports,cc,Gs=Hf;cc=Gs.createRoot,Gs.hydrateRoot;const dc=()=>{var e,t;return(t=(e=window==null?void 0:window.go)==null?void 0:e.main)==null?void 0:t.App},Wf=()=>!!dc();async function I(e,...t){const n=dc();if(!n||typeof n[e]!="function")throw new Error(`${e} is unavailable — run this inside the Behavision app`);return n[e](...t)}const A={session:()=>I("Session"),login:(e,t)=>I("Login",e,t),logout:()=>I("Logout"),claim:e=>I("Claim",e),runStandalone:()=>I("RunStandalone"),engineStatus:()=>I("EngineStatus"),startEngine:()=>I("StartEngine"),stopEngine:()=>I("StopEngine"),cameras:()=>I("Cameras"),testCamera:e=>I("TestCamera",e),saveCamera:(e,t)=>I("SaveCamera",e,t),deleteCamera:e=>I("DeleteCamera",e),startPlacement:(e,t)=>I("StartPlacementCheck",e,t),placementResult:e=>I("PlacementResult",e),streamURL:e=>I("StreamURL",e),live:()=>I("Live"),pipelineStatus:()=>I("PipelineStatus"),localIdentities:e=>I("LocalIdentities",e),localSightings:e=>I("LocalSightings",e),footfall:(e,t,n)=>I("Footfall",e,t,n),sites:()=>I("Sites"),visitorHistory:(e,t)=>I("VisitorHistory",e,t),visitorPhoto:e=>I("VisitorPhoto",e),forgetCustomer:e=>I("ForgetCustomer",e),sales:(e,t)=>I("Sales",e,t),customers:(e,t)=>I("Customers",e,t),saveProfile:e=>I("SaveProfile",e),recordPurchase:(e,t,n,r)=>I("RecordPurchase",e,t,n,r)};function Te(e){return e?typeof e=="string"?e:e.message||String(e):"Something went wrong."}function Dt(e,t,n=[]){const[r,l]=P.useState(null),[i,o]=P.useState(null),[u,a]=P.useState(!0),c=P.useRef(!0),p=P.useRef(!1),v=P.useCallback(async()=>{if(!p.current){p.current=!0;try{const m=await e();if(!c.current)return;l(m),o(null)}catch(m){c.current&&o(Te(m))}finally{p.current=!1,c.current&&a(!1)}}},n);return P.useEffect(()=>{if(c.current=!0,v(),!t)return()=>{c.current=!1};const m=setInterval(v,t);return()=>{c.current=!1,clearInterval(m)}},[v,t]),{data:r,error:i,loading:u,reload:v}}function Qf(e){if(!e)return"—";const t=typeof e=="number"?new Date(e*1e3):new Date(e);return isNaN(t)?"—":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Zs(e){if(!e)return"—";const t=typeof e=="number"?new Date(e*1e3):new Date(e);return isNaN(t)?"—":t.toLocaleDateString([],{day:"numeric",month:"short"})}function Kf({onDone:e}){const[t,n]=P.useState(""),[r,l]=P.useState(""),[i,o]=P.useState(!1),[u,a]=P.useState(null);async function c(p){p.preventDefault(),o(!0),a(null);try{e(await A.login(t.trim(),r))}catch(v){a(Te(v))}finally{o(!1)}}return s.jsx("div",{className:"login",children:s.jsxs("div",{className:"box",children:[s.jsx("h1",{children:"Behavision"}),s.jsx("p",{className:"lead",children:"Sign in to connect this PC to your store."}),s.jsxs("form",{onSubmit:c,children:[u&&s.jsx("div",{className:"err",children:u}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Email"}),s.jsx("input",{type:"email",value:t,autoComplete:"username",required:!0,autoFocus:!0,onChange:p=>n(p.target.value)})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:r,autoComplete:"current-password",required:!0,onChange:p=>l(p.target.value)})]}),s.jsx("button",{className:"btn primary",disabled:i||!t||!r,children:i?"Signing in…":"Sign in"})]}),s.jsx("p",{className:"foot",children:"Signing in downloads this store's recognition models and connects it to your account. Nothing is sent until a camera is set up."})]})})}function Js({onDone:e,onCancel:t}){const[n,r]=P.useState(""),[l,i]=P.useState(null),[o,u]=P.useState(null),[a,c]=P.useState(!1);async function p(m){m.preventDefault(),i("claim"),u(null);try{e(await A.claim(n))}catch(g){u(Te(g))}finally{i(null)}}async function v(){i("alone"),u(null);try{e(await A.runStandalone())}catch(m){u(Te(m))}finally{i(null)}}return s.jsx("div",{className:"login",children:s.jsxs("div",{className:"box",children:[s.jsx("h1",{children:t?"Link to head office":"Set up this PC"}),s.jsx("p",{className:"lead",children:"Type the installation code for this shop. You only do this once."}),s.jsxs("form",{onSubmit:p,children:[o&&s.jsx("div",{className:"err",children:o}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Installation code"}),s.jsx("input",{value:n,autoFocus:!0,required:!0,placeholder:"ABCDEF-123456-GHIJKL-789012",autoComplete:"off",spellCheck:"false",style:{textTransform:"uppercase",letterSpacing:".06em"},onChange:m=>r(m.target.value)})]}),s.jsx("button",{className:"btn primary",disabled:!!l||n.trim().length<6,children:l==="claim"?"Linking…":"Link this PC"})]}),s.jsx("p",{className:"foot",children:"The code works once. Ask whoever manages your shops for it — they can create one from the Behavision platform, under the shop."}),s.jsx("div",{className:"alt",children:t?s.jsx("button",{type:"button",className:"linkbtn",onClick:t,children:"Not now — go back"}):a?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"note",children:"This PC will watch its cameras and recognise returning customers on its own. Nothing is sent anywhere. You can link it to head office later without losing anything recorded here."}),s.jsx("button",{type:"button",className:"btn",disabled:!!l,onClick:v,children:l==="alone"?"Setting up…":"Use this PC on its own"})]}):s.jsx("button",{type:"button",className:"linkbtn",onClick:()=>c(!0),children:"No head office — set this PC up on its own"})})]})})}function fc(){var a,c;const{data:e,error:t}=Dt(()=>A.live(),3e3),{data:n}=Dt(()=>A.pipelineStatus(),5e3),r=Zf(),l=((a=e==null?void 0:e.stats)==null?void 0:a.cameras)??[],i=((c=e==null?void 0:e.stats)==null?void 0:c.gallery)??{},o=(e==null?void 0:e.events)??[],u=l.reduce((p,v)=>{var g,x;const m=(x=(g=v==null?void 0:v.pipeline)==null?void 0:g.best_quality)==null?void 0:x.fraction_below_gate;return typeof m=="number"&&m>p?m:p},0);return s.jsxs("div",{className:"page",children:[s.jsxs("header",{children:[s.jsx("h2",{children:"Live"}),s.jsx("p",{children:"Cameras, recent detections, and whether this site is recognising people."})]}),t&&s.jsx("div",{className:"err",children:t}),s.jsxs("div",{className:"grid cols-4",style:{marginBottom:16},children:[s.jsx(jr,{label:"People known",value:i.identities??"—"}),s.jsx(jr,{label:"Sightings",value:i.sightings??"—"}),s.jsx(jr,{label:"Cameras live",value:`${l.filter(p=>p.connected).length}/${l.length||0}`}),s.jsx(jr,{label:"Below quality gate",value:l.length?`${Math.round(u*100)}%`:"—",tone:u>.5?"bad":u>.2?"warn":"ok",sub:u>.5?"Most visitors are being missed — check camera placement":"Share of faces too poor to enrol"})]}),s.jsx(Yf,{pipe:n}),s.jsxs("div",{className:"grid cols-2",children:[s.jsx("div",{children:s.jsxs("div",{className:"card",children:[s.jsx("h3",{children:"Cameras"}),l.length===0?s.jsx("div",{className:"empty",children:"No cameras yet. Add one in Cameras."}):s.jsx("div",{className:"feeds",children:l.map(p=>s.jsxs("div",{className:"feed",children:[r[p.camera_id]?s.jsx("img",{src:r[p.camera_id],alt:p.camera_id}):s.jsx("div",{style:{aspectRatio:"16/9"}}),s.jsxs("div",{className:"cap",children:[s.jsx("span",{children:p.camera_id}),s.jsxs("span",{className:`pill ${p.connected?"ok":"bad"}`,children:[s.jsx("i",{className:`dot ${p.connected?"ok":"bad"}`}),p.connected?"live":"offline"]})]})]},p.camera_id))})]})}),s.jsxs("div",{className:"card",children:[s.jsx("h3",{children:"Recent detections"}),o.length===0?s.jsx("div",{className:"empty",children:"Nothing detected yet."}):s.jsx("ul",{className:"events",children:o.map((p,v)=>s.jsx(Xf,{e:p},v))})]})]})]})}function Yf({pipe:e}){if(!e)return null;if(e.standalone)return s.jsxs("div",{className:"card",style:{marginBottom:16,display:"flex",gap:10,alignItems:"center"},children:[s.jsx("i",{className:"dot ok"}),s.jsx("strong",{style:{fontSize:13},children:"Running on this PC only"}),s.jsx("span",{className:"note",children:"Recognition and customers stay here."})]});const t=e.claimed&&!e.broker_up;return s.jsxs("div",{className:"card",style:{marginBottom:16,display:"flex",gap:22,alignItems:"center",flexWrap:"wrap"},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("i",{className:`dot ${e.claimed?e.broker_up?"ok":"bad":"idle"}`}),s.jsx("strong",{style:{fontSize:13},children:e.claimed?e.broker_up?"Sending to head office":"Offline — saving locally":"Not linked to head office"})]}),s.jsxs("span",{className:"note",children:[e.accepted," recorded today"]}),e.queued>0&&s.jsxs("span",{className:"note",style:t?{color:"var(--warn)"}:void 0,children:[e.queued," waiting to send"]}),e.dropped>0&&s.jsxs("span",{className:"note",style:{color:"var(--bad)"},children:[e.dropped," lost — this PC was offline too long"]})]})}function Xf({e}){var l,i,o,u,a;const t=e.type==="person.new"?"new":e.type==="person.seen"?"seen":e.type==="person.missed"?"miss":"",n=((l=e.data)==null?void 0:l.age)??((i=e.data)==null?void 0:i.age_range),r=[(o=e.data)==null?void 0:o.gender,n,(u=e.data)==null?void 0:u.emotion].filter(Boolean).join(", ");return s.jsxs("li",{children:[s.jsx("span",{className:"when",children:Qf(e.ts)}),s.jsx("span",{className:`tag ${t}`,children:Gf(e.type)}),s.jsxs("span",{style:{flex:1,minWidth:0},children:[((a=e.data)==null?void 0:a.label)||e.camera_id,r&&s.jsxs("span",{className:"note",children:[" · ",r]})]})]})}function Gf(e){return{"person.new":"new","person.seen":"returning","person.missed":"missed","camera.up":"camera up","camera.down":"camera down","identity.merged":"merged"}[e]??e}function jr({label:e,value:t,sub:n,tone:r}){return s.jsxs("div",{className:"card stat",children:[s.jsx("h3",{children:e}),s.jsx("div",{className:"value",style:r?{color:`var(--${r})`}:void 0,children:t}),n&&s.jsx("div",{className:"sub",children:n})]})}function Zf(){const[e,t]=P.useState({}),{data:n}=Dt(()=>A.cameras(),1e4);return P.useEffect(()=>{let r=!1;return(async()=>{const l={};for(const o of n??[]){if(e[o.id]){l[o.id]=e[o.id];continue}try{l[o.id]=await A.streamURL(o.id)}catch{}}const i=Object.keys(l).length!==Object.keys(e).length||Object.keys(l).some(o=>l[o]!==e[o]);!r&&i&&t(l)})(),()=>{r=!0}},[n]),e}function Jf(e){const[t,n]=P.useState(null);return P.useEffect(()=>{let r=!0;return n(null),A.visitorPhoto(e).then(l=>{r&&n(l)}).catch(()=>{r&&n({available:!1,reason:""})}),()=>{r=!1}},[e]),t}function qf({photo:e,name:t,onBroken:n}){if(e!=null&&e.available)return s.jsx("img",{className:"avatar",src:e.url,alt:`Photo of ${t}`,onError:n});const r=String(t||"").split(/\s+/).filter(Boolean).slice(0,2).map(l=>l[0].toUpperCase()).join("")||"?";return s.jsx("div",{className:"avatar none",role:"img","aria-label":`No photo of ${t}`,children:s.jsx("span",{children:r})})}function bf({customer:e}){const{data:t,error:n,loading:r}=Dt(()=>A.visitorHistory(e.id,50),0,[e.id]);if(r)return s.jsx("p",{className:"note",children:"Loading visits…"});if(n)return s.jsxs("p",{className:"note",children:["Could not load visits: ",n]});const l=t??[];return l.length===0?s.jsx("p",{className:"note",children:"No recorded visits yet."}):s.jsx("ul",{className:"timeline",children:l.map(i=>s.jsxs("li",{children:[s.jsx("span",{className:"when",children:ep(i.occurred_at)}),s.jsxs("span",{className:"where",children:[i.site||"this store",i.camera_id?s.jsxs("span",{className:"note",children:[" · ",i.camera_id]}):null]}),i.is_new_visitor&&s.jsx("span",{className:"tag new",children:"first visit"})]},i.id))})}function ep(e){const t=new Date(e);return isNaN(t)?"—":t.toLocaleString([],{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}function tp({customer:e,onCancel:t,onDone:n}){const r=e.full_name||e.label,[l,i]=P.useState(""),[o,u]=P.useState(!1),[a,c]=P.useState(null),p=l.trim().toLowerCase()===r.trim().toLowerCase();async function v(){u(!0),c(null);try{await A.forgetCustomer(e.id),n()}catch(m){c(Te(m)),u(!1)}}return s.jsxs("div",{className:"confirm",children:[s.jsxs("h4",{children:["Erase ",r,"?"]}),s.jsxs("div",{className:"cols",children:[s.jsxs("div",{children:[s.jsx("p",{className:"lbl bad",children:"Deleted for good"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Their face data — they will not be recognised again"}),s.jsx("li",{children:"Their photo"}),s.jsx("li",{children:"Their name, phone, email and notes"})]})]}),s.jsxs("div",{children:[s.jsx("p",{className:"lbl",children:"Kept"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Past visits, with their name removed — your footfall figures do not change"}),s.jsx("li",{children:"The consent record, marked withdrawn, as proof of what was agreed"})]})]})]}),s.jsx("p",{className:"note",children:"This cannot be undone. If they come back they will be recorded as a new customer."}),a&&s.jsx("div",{className:"err",children:a}),s.jsxs("label",{className:"field",children:[s.jsxs("span",{children:["Type ",s.jsx("b",{children:r})," to confirm"]}),s.jsx("input",{value:l,onChange:m=>i(m.target.value),autoFocus:!0,autoComplete:"off",spellCheck:"false","aria-label":`Type ${r} to confirm erasure`})]}),s.jsxs("div",{className:"row",children:[s.jsx("button",{type:"button",className:"btn danger",disabled:!p||o,onClick:v,children:o?"Erasing…":"Erase permanently"}),s.jsx("button",{type:"button",className:"btn",onClick:t,disabled:o,children:"Cancel"})]})]})}function np({customer:e,session:t,onClose:n,onSaved:r}){var _;const[l,i]=P.useState({full_name:e.full_name??"",phone:e.phone??"",email:e.email??"",gender:"",date_of_birth:"",notes:"",consent:e.has_consent??!1}),[o,u]=P.useState({amount:"",items:"",notes:""}),[a,c]=P.useState(!1),[p,v]=P.useState(null),[m,g]=P.useState(!1),[x,k]=P.useState(null),O=Jf(e.id),h=x??O,d=(_=t==null?void 0:t.user)==null?void 0:_.role,f=["admin","owner","manager"].includes(d),y=j=>E=>i({...l,[j]:E.target.value});async function S(j){j.preventDefault(),c(!0),v(null);try{await A.saveProfile({visitor_id:e.id,...l});const E=parseFloat(o.amount);if(!isNaN(E)&&E>0){const V=o.items.split(",").map(L=>L.trim()).filter(Boolean);await A.recordPurchase(e.id,E,V,o.notes)}r()}catch(E){v(Te(E))}finally{c(!1)}}return s.jsx("div",{className:"drawer",onMouseDown:j=>j.target===j.currentTarget&&n(),children:s.jsxs("div",{className:"panel",children:[s.jsxs("div",{className:"who",children:[s.jsx(qf,{photo:h,name:e.full_name||e.label,onBroken:()=>k({available:!1,reason:"The photo could not be loaded."})}),s.jsxs("div",{className:"grow",children:[s.jsx("h3",{children:e.full_name||e.label}),s.jsxs("p",{className:"note",children:[e.visit_count," visit",e.visit_count===1?"":"s",e.last_seen_at&&` · last seen ${new Date(e.last_seen_at).toLocaleDateString()}`]}),h&&!h.available&&h.reason&&s.jsx("p",{className:"note",children:h.reason})]}),s.jsx("button",{type:"button",className:"btn sm",onClick:n,children:"Close"})]}),s.jsxs("form",{onSubmit:S,children:[p&&s.jsx("div",{className:"err",children:p}),s.jsxs("div",{className:"card",style:{marginBottom:14},children:[s.jsx("h3",{children:"Customer details"}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Full name"}),s.jsx("input",{value:l.full_name,onChange:y("full_name"),autoFocus:!0})]}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Phone"}),s.jsx("input",{value:l.phone,onChange:y("phone"),inputMode:"tel"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Email"}),s.jsx("input",{value:l.email,onChange:y("email"),type:"email"})]})]}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Gender"}),s.jsxs("select",{value:l.gender,onChange:y("gender"),children:[s.jsx("option",{value:"",children:"Not recorded"}),s.jsx("option",{children:"Female"}),s.jsx("option",{children:"Male"}),s.jsx("option",{children:"Other"})]})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Date of birth"}),s.jsx("input",{type:"date",value:l.date_of_birth,onChange:y("date_of_birth")})]})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Notes"}),s.jsx("textarea",{value:l.notes,onChange:y("notes"),placeholder:"Preferences, sizes, anything worth remembering"})]})]}),s.jsxs("div",{className:"card",style:{marginBottom:14},children:[s.jsx("h3",{children:"Purchase (optional)"}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Amount"}),s.jsx("input",{value:o.amount,inputMode:"decimal",placeholder:"0.00",onChange:j=>u({...o,amount:j.target.value})})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Items"}),s.jsx("input",{value:o.items,placeholder:"shirt, belt",onChange:j=>u({...o,items:j.target.value})})]})]}),s.jsx("p",{className:"note",children:"Leave the amount blank if they did not buy anything — a visit without a sale is still worth recording."})]}),s.jsxs("div",{className:"card",style:{marginBottom:16},children:[s.jsx("h3",{children:"Consent"}),s.jsxs("label",{style:{display:"flex",gap:10,alignItems:"flex-start",fontSize:13,cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:l.consent,style:{marginTop:3},onChange:j=>i({...l,consent:j.target.checked})}),s.jsx("span",{children:"This customer agreed to us keeping their details and recognising them on future visits."})]}),s.jsx("p",{className:"note",style:{marginTop:10},children:"Recorded with the date and who collected it. They can withdraw it at any time, which erases their face data."})]}),s.jsxs("div",{className:"card",style:{marginBottom:14},children:[s.jsx("h3",{children:"Visits"}),s.jsx(bf,{customer:e})]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{className:"btn primary",disabled:a,children:a?"Saving…":"Save"}),s.jsx("button",{type:"button",className:"btn",onClick:n,children:"Cancel"})]}),f&&s.jsxs("div",{className:"card danger-zone",children:[s.jsx("h3",{children:"At the customer's request"}),m?s.jsx(tp,{customer:e,onCancel:()=>g(!1),onDone:r}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"note",children:"Erase this person's face data, photo and details. Their past visits stay in your footfall figures, without their name."}),s.jsx("button",{type:"button",className:"btn danger",onClick:()=>g(!0),children:"Erase this customer…"})]})]})]})]})})}function rp({session:e}){const[t,n]=P.useState(""),[r,l]=P.useState(null),{data:i,error:o,reload:u}=Dt(()=>A.customers(t,200),3e4,[t]),a=i??[],c=a.filter(p=>p.has_profile).length;return s.jsxs("div",{className:"page",children:[s.jsxs("header",{children:[s.jsx("h2",{children:"Customers"}),s.jsx("p",{children:"Everyone this business has recognised. Fill in details once and they are known at every store."})]}),o&&s.jsx("div",{className:"err",children:o}),s.jsxs("div",{className:"grid cols-4",style:{marginBottom:16},children:[s.jsx(Nr,{label:"Known people",value:a.length||"—"}),s.jsx(Nr,{label:"With details",value:c||"—",sub:a.length?`${Math.round(100*c/a.length)}% captured`:null}),s.jsx(Nr,{label:"Returning",value:a.filter(p=>p.visit_count>1).length||"—"}),s.jsx(Nr,{label:"With consent",value:a.filter(p=>p.has_consent).length||"—"})]}),s.jsxs("div",{className:"card",children:[s.jsxs("div",{style:{display:"flex",gap:10,marginBottom:12},children:[s.jsx("input",{className:"field",style:{flex:1,margin:0,background:"var(--ground)",border:"1px solid var(--line)",borderRadius:6,padding:"8px 10px"},placeholder:"Search by name or phone",value:t,onChange:p=>n(p.target.value)}),s.jsx("button",{className:"btn",onClick:u,children:"Refresh"})]}),a.length===0?s.jsx("div",{className:"empty",children:"No customers yet. They appear here the first time a camera sees them."}):s.jsx("div",{className:"tablewrap",children:s.jsxs("table",{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Customer"}),s.jsx("th",{children:"Phone"}),s.jsx("th",{className:"num",children:"Visits"}),s.jsx("th",{children:"First seen"}),s.jsx("th",{children:"Last seen"}),s.jsx("th",{children:"Details"})]})}),s.jsx("tbody",{children:a.map(p=>s.jsxs("tr",{className:"click",onClick:()=>l(p),children:[s.jsxs("td",{children:[p.full_name||s.jsx("span",{className:"note",children:p.label}),p.full_name&&p.ref&&s.jsxs("span",{className:"note",children:[" · ",p.ref]})]}),s.jsx("td",{className:"mono",children:p.phone||"—"}),s.jsx("td",{className:"num",children:p.visit_count}),s.jsx("td",{children:Zs(p.first_seen_at)}),s.jsx("td",{children:Zs(p.last_seen_at)}),s.jsx("td",{children:p.has_profile?s.jsxs("span",{className:"pill ok",children:[s.jsx("i",{className:"dot ok"}),"captured"]}):s.jsxs("span",{className:"pill warn",children:[s.jsx("i",{className:"dot warn"}),"needed"]})})]},p.id))})]})})]}),r&&s.jsx(np,{customer:r,session:e,onClose:()=>l(null),onSaved:()=>{l(null),u()}})]})}function Nr({label:e,value:t,sub:n}){return s.jsxs("div",{className:"card stat",children:[s.jsx("h3",{children:e}),s.jsx("div",{className:"value",children:t}),n&&s.jsx("div",{className:"sub",children:n})]})}const tn=[{id:"hikvision",label:"Hikvision",path:"/Streaming/Channels/101",note:"Channel 1, main stream. Use /Streaming/Channels/102 for the lower-quality sub stream."},{id:"dahua",label:"Dahua",path:"/cam/realmonitor?channel=1&subtype=0",note:"Channel 1, main stream. subtype=1 is the sub stream."},{id:"cpplus",label:"CP Plus",path:"/cam/realmonitor?channel=1&subtype=0",note:"CP Plus cameras use the Dahua stream path."},{id:"uniview",label:"Uniview",path:"/media/video1",note:"Some older Uniview models use /video1 instead."},{id:"tplink",label:"TP-Link / Tapo",path:"/stream1",note:"Tapo cameras need a separate camera account created in the Tapo app — your Tapo login will not work."},{id:"reolink",label:"Reolink",path:"/h264Preview_01_main",note:"Use /h264Preview_01_sub for the lower-quality stream."},{id:"amcrest",label:"Amcrest",path:"/cam/realmonitor?channel=1&subtype=0",note:"Amcrest cameras use the Dahua stream path."},{id:"axis",label:"Axis",path:"/axis-media/media.amp",note:""},{id:"onvif",label:"Other (ONVIF)",path:"/onvif1",note:"Many generic cameras answer here. If it does not work, look for “RTSP” in the camera’s own app."},{id:"manual",label:"I know the path",path:"",note:""}],ql=e=>tn.find(t=>t.id===e)||tn[tn.length-1],pc={id:"",host:"",port:554,path:"",username:"",password:"",max_width:1280};function lp(){const{data:e,error:t,reload:n}=Dt(()=>A.cameras(),8e3),[r,l]=P.useState(null),[i,o]=P.useState(null),u=e??[];async function a(c){if(confirm(`Remove camera "${c}"? Recognition from it stops immediately.`))try{await A.deleteCamera(c),n()}catch(p){alert(Te(p))}}return s.jsxs("div",{className:"page",children:[s.jsxs("header",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-end"},children:[s.jsxs("div",{children:[s.jsx("h2",{children:"Cameras"}),s.jsx("p",{children:"Add a camera, check it can see faces properly, then it starts working."})]}),s.jsx("button",{className:"btn primary",onClick:()=>l({...pc}),children:"Add camera"})]}),t&&s.jsx("div",{className:"err",children:t}),s.jsx("div",{className:"card",children:u.length===0?s.jsx("div",{className:"empty",children:"No cameras yet."}):s.jsx("div",{className:"tablewrap",children:s.jsxs("table",{children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Address"}),s.jsx("th",{children:"Status"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:u.map(c=>s.jsxs("tr",{children:[s.jsx("td",{children:c.id}),s.jsx("td",{className:"mono",children:c.url}),s.jsx("td",{children:c.connected===void 0?s.jsxs("span",{className:"pill",children:[s.jsx("i",{className:"dot idle"}),"stopped"]}):c.connected?s.jsxs("span",{className:"pill ok",children:[s.jsx("i",{className:"dot ok"}),"live"]}):s.jsxs("span",{className:"pill bad",children:[s.jsx("i",{className:"dot bad"}),"offline"]})}),s.jsxs("td",{style:{textAlign:"right",whiteSpace:"nowrap"},children:[s.jsx("button",{className:"btn sm",onClick:()=>o(c.id),children:"Check placement"})," ",s.jsx("button",{className:"btn sm",onClick:()=>l(c),children:"Edit"})," ",s.jsx("button",{className:"btn sm danger",onClick:()=>a(c.id),children:"Remove"})]})]},c.id))})]})})}),r&&s.jsx(ip,{cam:r,onClose:()=>l(null),onSaved:()=>{l(null),n()}}),i&&s.jsx(op,{id:i,onClose:()=>o(null)})]})}function ip({cam:e,onClose:t,onSaved:n}){const r=!e.id,[l,i]=P.useState({...pc,...e,password:"",path:e.path||(r?tn[0].path:"")}),[o,u]=P.useState(r?tn[0].id:"manual"),[a,c]=P.useState(null),[p,v]=P.useState(null),[m,g]=P.useState(null),x=f=>y=>i({...l,[f]:y.target.value});function k(f){const y=ql(f.target.value);u(y.id),i(S=>({...S,path:y.path||S.path}))}function O(){const f={};for(const[y,S]of Object.entries(l))S===""||S===null||S===void 0||(f[y]=y==="port"||y==="max_width"?Number(S):S);return f}async function h(){v("test"),g(null),c(null);try{c(await A.testCamera(O()))}catch(f){g(Te(f))}finally{v(null)}}async function d(f){f.preventDefault(),v("save"),g(null);try{await A.saveCamera(r?"":e.id,O()),n()}catch(y){g(Te(y))}finally{v(null)}}return s.jsx("div",{className:"drawer",onMouseDown:f=>f.target===f.currentTarget&&t(),children:s.jsxs("div",{className:"panel",children:[s.jsx("button",{className:"btn sm close",onClick:t,children:"Close"}),s.jsx("h3",{children:r?"Add camera":e.id}),s.jsx("p",{className:"note",style:{marginBottom:18},children:"Test the connection before saving — a wrong address is the most common mistake."}),s.jsxs("form",{onSubmit:d,children:[m&&s.jsx("div",{className:"err",children:m}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Name"}),s.jsx("input",{value:l.id,onChange:x("id"),disabled:!r,placeholder:"entrance",required:!0,autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Make of camera"}),s.jsx("select",{value:o,onChange:k,children:tn.map(f=>s.jsx("option",{value:f.id,children:f.label},f.id))})]}),ql(o).note&&s.jsx("p",{className:"note",style:{marginTop:-8,marginBottom:12},children:ql(o).note}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Camera address"}),s.jsx("input",{value:l.host,onChange:x("host"),placeholder:"192.168.0.138",autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Port"}),s.jsx("input",{value:l.port,onChange:x("port"),inputMode:"numeric",autoComplete:"off"})]})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Stream path"}),s.jsx("input",{value:l.path,onChange:x("path"),placeholder:"/ch0_0.264",autoComplete:"off"})]}),s.jsxs("div",{className:"fieldrow",children:[s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Username"}),s.jsx("input",{value:l.username,onChange:x("username"),name:"camera-account",autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:l.password,onChange:x("password"),name:"camera-secret",autoComplete:"new-password",placeholder:e.has_password?"(unchanged)":""})]})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{type:"button",className:"btn",onClick:h,disabled:!!p,children:p==="test"?"Connecting…":"Test connection"}),s.jsx("button",{className:"btn primary",disabled:!!p||!l.id,children:p==="save"?"Saving…":"Save"})]}),a&&s.jsx("div",{style:{marginTop:14},children:a.ok?s.jsxs(s.Fragment,{children:[s.jsxs("p",{style:{color:"var(--ok)",fontSize:13},children:["Connected — ",a.width,"×",a.height]}),a.snapshot&&s.jsx("img",{alt:"Camera preview",style:{width:"100%",marginTop:8,borderRadius:6,border:"1px solid var(--line)"},src:`data:image/jpeg;base64,${a.snapshot}`})]}):s.jsx("div",{className:"err",children:a.error})})]})]})})}function op({id:e,onClose:t}){var c,p;const[n,r]=P.useState({verdict:"starting",advice:[]}),[l,i]=P.useState(null),o=P.useRef(null);P.useEffect(()=>{let v=!0;return(async()=>{try{r(await A.startPlacement(e,25)),o.current=setInterval(async()=>{try{const m=await A.placementResult(e);if(!v)return;r(m),m.running||clearInterval(o.current)}catch(m){v&&i(Te(m))}},1e3)}catch(m){v&&i(Te(m))}})(),()=>{v=!1,clearInterval(o.current)}},[e]);const u={good:"ok",marginal:"warn",poor:"bad",artifact:"bad",no_faces:"warn",inconclusive:"warn"}[n.verdict],a=n.seconds?Math.min(100,n.elapsed/n.seconds*100):0;return s.jsx("div",{className:"drawer",onMouseDown:v=>v.target===v.currentTarget&&t(),children:s.jsxs("div",{className:"panel",children:[s.jsx("button",{className:"btn sm close",onClick:t,children:"Close"}),s.jsxs("h3",{children:["Placement check — ",e]}),s.jsx("p",{className:"note",style:{marginBottom:18},children:"Walk past the camera the way a customer would, a few times."}),l&&s.jsx("div",{className:"err",children:l}),s.jsxs("div",{className:"card",children:[s.jsx("div",{style:{fontSize:15,fontWeight:600,color:u?`var(--${u})`:"var(--ink)"},children:n.headline||"Starting…"}),n.running&&s.jsx("div",{style:{height:5,background:"var(--surface-2)",borderRadius:3,overflow:"hidden",margin:"12px 0"},children:s.jsx("div",{style:{height:"100%",width:`${a}%`,background:"var(--accent)",transition:"width .4s linear"}})}),((c=n.advice)==null?void 0:c.length)>0&&s.jsx("ul",{style:{margin:"12px 0 0 18px",fontSize:13,color:"var(--ink-2)"},children:n.advice.map((v,m)=>s.jsx("li",{style:{marginBottom:5},children:v},m))}),((p=n.quality)==null?void 0:p.n)>0&&s.jsxs("p",{className:"note",style:{marginTop:12},children:[n.quality.n," face",n.quality.n===1?"":"s"," seen · median quality ",n.quality.p50," · gate ",n.gate," ·"," ",Math.round((n.quality.fraction_below_gate??0)*100),"% below it"]})]})]})})}const sp=[{id:"live",label:"Live",glyph:"◉",View:fc},{id:"customers",label:"Customers",glyph:"☺",View:rp,cloud:!0},{id:"cameras",label:"Cameras",glyph:"▢",View:lp}];function up(){var p,v,m;const[e,t]=P.useState(null),[n,r]=P.useState("live"),[l,i]=P.useState(!0),[o,u]=P.useState(!1);if(P.useEffect(()=>{(async()=>{try{t(await A.session())}catch{t(null)}i(!1)})()},[]),!Wf())return s.jsx("div",{className:"login",children:s.jsxs("div",{className:"box",children:[s.jsx("h1",{children:"Behavision"}),s.jsx("p",{className:"lead",children:"This is the Behavision window running outside the app, so it has no connection to the recognition engine. Launch the Behavision application instead."})]})});if(l)return s.jsx("div",{className:"login",children:s.jsx("p",{className:"note",children:"Starting…"})});if(!(e!=null&&e.claimed)&&!(e!=null&&e.standalone))return s.jsx(Js,{onDone:t});if(!(e!=null&&e.standalone)&&!(e!=null&&e.logged_in))return s.jsx(Kf,{onDone:t});const a=sp.filter(g=>!g.cloud||!e.standalone),c=((p=a.find(g=>g.id===n))==null?void 0:p.View)??fc;return o?s.jsx(Js,{onDone:g=>{u(!1),t(g)},onCancel:()=>u(!1)}):s.jsxs("div",{className:"shell",children:[s.jsxs("aside",{className:"side",children:[s.jsxs("div",{className:"brand",children:[s.jsx("h1",{children:"Behavision"}),s.jsx("p",{children:e.site_name||((v=e.user)==null?void 0:v.client_name)||"Store"})]}),s.jsx("nav",{className:"nav",children:a.map(g=>s.jsxs("button",{onClick:()=>r(g.id),"aria-current":g.id===n?"page":void 0,children:[s.jsx("span",{className:"glyph",children:g.glyph}),g.label]},g.id))}),s.jsx(ap,{}),s.jsx("div",{style:{padding:"10px 12px 14px",borderTop:"1px solid var(--line-soft)"},children:e.standalone?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"note",style:{marginBottom:8},children:"Running on its own"}),s.jsx("button",{className:"btn sm",style:{width:"100%"},onClick:()=>u(!0),children:"Link to head office"})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"note",style:{marginBottom:8},children:(m=e.user)==null?void 0:m.email}),s.jsx("button",{className:"btn sm",style:{width:"100%"},onClick:async()=>t(await A.logout()),children:"Sign out"})]})})]}),s.jsx("main",{className:"main",children:s.jsx(c,{session:e})})]})}function ap(){const{data:e,reload:t}=Dt(()=>A.engineStatus(),5e3),[n,r]=P.useState(!1),l=e??{state:"stopped"},i=P.useCallback(async v=>{r(!0);try{await v()}catch(m){alert(Te(m))}finally{r(!1),t()}},[t]),o=l.state==="running",u=Object.values(l.cameras??{}),a=u.filter(Boolean).length;let c="idle",p="Stopped";return l.state==="failed"||l.state==="backoff"?(c="bad",p="Not running"):o&&!l.reachable?(c="warn",p="Starting…"):o&&u.length===0?(c="warn",p="No cameras"):o&&a===0?(c="bad",p="No camera connected"):o&&ai(A.startEngine),children:"Start"}),s.jsx("button",{className:"btn sm",disabled:n||!o,onClick:()=>i(A.stopEngine),children:"Stop"})]})]})}cc(document.getElementById("root")).render(s.jsx(Lc.StrictMode,{children:s.jsx(up,{})})); diff --git a/desktop/frontend/dist/index.html b/desktop/frontend/dist/index.html index 5a5a59b..c867ba2 100644 --- a/desktop/frontend/dist/index.html +++ b/desktop/frontend/dist/index.html @@ -4,7 +4,7 @@ Behavision - + diff --git a/desktop/frontend/src/views/Customers.jsx b/desktop/frontend/src/views/Customers.jsx index f3110a2..c5e04e6 100644 --- a/desktop/frontend/src/views/Customers.jsx +++ b/desktop/frontend/src/views/Customers.jsx @@ -56,7 +56,14 @@ export default function Customers({ session }) { {rows.map(c => ( setSelected(c)}> - {c.full_name || {c.label}} + + {c.full_name || {c.label}} + {/* Only beside a name a human typed: the auto label + already IS the number ("Visitor 13"), so showing + both reads as two identifiers for one person. */} + {c.full_name && c.ref && + · {c.ref}} + {c.phone || '—'} {c.visit_count} {fmtDate(c.first_seen_at)} diff --git a/desktop/internal/cloud/client.go b/desktop/internal/cloud/client.go index dbb7caf..d2591c6 100644 --- a/desktop/internal/cloud/client.go +++ b/desktop/internal/cloud/client.go @@ -545,7 +545,10 @@ func (c *Client) Sales(ctx context.Context, from, to string) (SalesReport, error } type Customer struct { - ID string `json:"id"` + ID string `json:"id"` + // Ref is the customer number - "V-42" - and is what staff say to each + // other. It is accepted anywhere this customer's id is. + Ref string `json:"ref"` Label string `json:"label"` FullName string `json:"full_name"` Phone string `json:"phone"` diff --git a/server/internal/api/api.go b/server/internal/api/api.go index 45552d0..7899d19 100644 --- a/server/internal/api/api.go +++ b/server/internal/api/api.go @@ -64,6 +64,14 @@ type Store interface { Team(ctx context.Context, clientID string) ([]TeamMember, error) UpdateTeamMember(ctx context.Context, clientID, userID string, up TeamUpdate) (TeamMember, error) + // --- public references --- + // Resolving the names people actually use to the uuids the schema stores. + // All three answer "" with a nil error when nothing matches; a found id is + // never empty, so a miss cannot be confused with a fault. See refs.go. + SiteIDBySlug(ctx context.Context, clientID, slug string) (string, error) + CameraIDByRef(ctx context.Context, clientID, ref string) (string, error) + VisitorIDByNumber(ctx context.Context, clientID string, number int64) (string, error) + // --- reports --- Footfall(ctx context.Context, q ReportQuery) ([]FootfallPoint, Totals, error) Conversion(ctx context.Context, q ReportQuery) (SalesReport, error) diff --git a/server/internal/api/fake_test.go b/server/internal/api/fake_test.go index 7c0a7ae..62d5e81 100644 --- a/server/internal/api/fake_test.go +++ b/server/internal/api/fake_test.go @@ -179,7 +179,7 @@ func (f *fakeStore) CreateSession(_ context.Context, n NewSession) error { FullName: rec.FullName, Role: rec.Role, }, accessExp: n.AccessExpiry, refreshExp: n.RefreshExp, - device: n.Device, + device: n.Device, } f.sessions[id] = s f.byAccess[hex.EncodeToString(n.AccessHash)] = id @@ -913,3 +913,85 @@ func (f *fakeStore) DeleteVisitFaces(_ context.Context, clientID string, keys [] } return nil } + +// ============================================ public reference resolution === +// +// These behave rather than merely satisfy the interface. The properties the +// handlers are trusted for - a reference resolves only within the caller's own +// tenant, and an ambiguous camera name resolves to nothing rather than to +// whichever row came first - are exactly what a fake that always said yes would +// stop any test from checking. + +func (f *fakeStore) SiteIDBySlug(_ context.Context, clientID, slug string) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + for _, s := range f.sites { + // An owner of "" is a site the fake was not told about, which is the + // ordinary case: SiteHealth carries no client id, and most tests seed + // one tenant. Tests that assert cross-tenant resolution seed a camera, + // which is what gives a site an owner here. + if owner := f.siteClient(s.Slug, s.SiteID); s.Slug == slug && + (owner == "" || owner == clientID) { + return s.SiteID, nil + } + } + return "", nil +} + +// siteClient answers which tenant a site belongs to. SiteHealth carries no +// client id of its own - it is already scoped by the query that returns it - so +// the fake reads ownership from the cameras it was seeded with. +func (f *fakeStore) siteClient(_, siteID string) string { + for _, ref := range f.cameraRefs { + if ref.site == siteID { + return ref.client + } + } + for _, c := range f.cameras { + if c.SiteID == siteID { + return f.cameraOwner(c.ID) + } + } + return "" +} + +func (f *fakeStore) cameraOwner(id string) string { + if ref, ok := f.cameraRefs[id]; ok { + return ref.client + } + return "" +} + +func (f *fakeStore) CameraIDByRef(_ context.Context, clientID, ref string) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + var found []string + for _, c := range f.cameras { + if c.CameraID != ref { + continue + } + if owner := f.cameraOwner(c.ID); owner != "" && owner != clientID { + continue + } + found = append(found, c.ID) + } + // A camera id is unique per site, not per tenant. Two shops may each have + // an "Office1", and acting on whichever sorted first would edit the wrong + // shop's camera, so ambiguity is no match. + if len(found) != 1 { + return "", nil + } + return found[0], nil +} + +func (f *fakeStore) VisitorIDByNumber(_ context.Context, clientID string, number int64) (string, error) { + f.mu.Lock() + defer f.mu.Unlock() + want := VisitorRef(number) + for _, v := range f.visitors { + if v.Ref == want { + return v.ID, nil + } + } + return "", nil +} diff --git a/server/internal/api/handlers_arrivals.go b/server/internal/api/handlers_arrivals.go index 9cae58a..9e45fc1 100644 --- a/server/internal/api/handlers_arrivals.go +++ b/server/internal/api/handlers_arrivals.go @@ -41,12 +41,14 @@ func (s *Server) handleArrivals(w http.ResponseWriter, r *http.Request) { q := ArrivalQuery{ ClientID: p.ClientID, - SiteID: trim(r.URL.Query().Get("site_id")), + SiteID: siteParam(r), Limit: queryInt(r, "limit", defaultArrivals, maxArrivals), } - if q.SiteID != "" && !looksLikeUUID(q.SiteID) { - badRequest(w, "site_id must be a site identifier") - return + if q.SiteID != "" { + var ok bool + if q.SiteID, ok = s.resolveSiteFilter(w, r, q.SiteID); !ok { + return + } } // The site is still filtered by client_id in SQL as well. A site_id from // the query string is caller-controlled, and this is a read of other @@ -157,12 +159,14 @@ func (s *Server) handleArrivalStream(w http.ResponseWriter, r *http.Request) { q := ArrivalQuery{ ClientID: p.ClientID, - SiteID: trim(r.URL.Query().Get("site_id")), + SiteID: siteParam(r), Limit: queryInt(r, "limit", defaultArrivals, maxArrivals), } - if q.SiteID != "" && !looksLikeUUID(q.SiteID) { - badRequest(w, "site_id must be a site identifier") - return + if q.SiteID != "" { + var ok bool + if q.SiteID, ok = s.resolveSiteFilter(w, r, q.SiteID); !ok { + return + } } // Last-Event-ID is what the browser's EventSource resends automatically on // a dropped connection, so honouring it is what makes a reconnect lossless diff --git a/server/internal/api/handlers_cameras.go b/server/internal/api/handlers_cameras.go index 4174207..dcd92ff 100644 --- a/server/internal/api/handlers_cameras.go +++ b/server/internal/api/handlers_cameras.go @@ -22,9 +22,11 @@ const snapshotTTL = 5 * time.Minute func (s *Server) handleCameras(w http.ResponseWriter, r *http.Request) { p := PrincipalFrom(r.Context()) siteID := trim(r.URL.Query().Get("site_id")) - if siteID != "" && !looksLikeUUID(siteID) { - badRequest(w, "site_id must be a site identifier") - return + if siteID != "" { + var ok bool + if siteID, ok = s.resolveSiteFilter(w, r, siteID); !ok { + return + } } cams, err := s.Store.Cameras(r.Context(), p.ClientID, siteID) if err != nil { @@ -91,9 +93,8 @@ func (s *Server) handleCreateCamera(w http.ResponseWriter, r *http.Request) { "Your account cannot change camera settings.") return } - siteID := r.PathValue("site") - if !looksLikeUUID(siteID) { - writeErr(w, http.StatusNotFound, "not_found", "That shop no longer exists.") + siteID, ok := s.resolveSite(w, r, r.PathValue("site")) + if !ok { return } var in CameraInput @@ -129,9 +130,8 @@ func (s *Server) handleUpdateCamera(w http.ResponseWriter, r *http.Request) { "Your account cannot change camera settings.") return } - id := r.PathValue("id") - if !looksLikeUUID(id) { - writeErr(w, http.StatusNotFound, "not_found", "That camera no longer exists.") + id, ok := s.resolveCamera(w, r, r.PathValue("id")) + if !ok { return } existing, err := s.Store.CameraByID(r.Context(), p.ClientID, id) @@ -192,9 +192,8 @@ func (s *Server) handleDeleteCamera(w http.ResponseWriter, r *http.Request) { "Your account cannot change camera settings.") return } - id := r.PathValue("id") - if !looksLikeUUID(id) { - writeErr(w, http.StatusNotFound, "not_found", "That camera no longer exists.") + id, ok := s.resolveCamera(w, r, r.PathValue("id")) + if !ok { return } cam, err := s.Store.DeleteCamera(r.Context(), p.ClientID, id) diff --git a/server/internal/api/handlers_checks.go b/server/internal/api/handlers_checks.go index d1ae10c..05fd5f6 100644 --- a/server/internal/api/handlers_checks.go +++ b/server/internal/api/handlers_checks.go @@ -33,9 +33,8 @@ func (s *Server) handleRequestCheck(w http.ResponseWriter, r *http.Request) { "Your account cannot run camera checks.") return } - id := r.PathValue("id") - if !looksLikeUUID(id) { - writeErr(w, http.StatusNotFound, "not_found", "That camera no longer exists.") + id, ok := s.resolveCamera(w, r, r.PathValue("id")) + if !ok { return } var req CheckRequest @@ -129,9 +128,8 @@ func (s *Server) handleAgentCheckResult(w http.ResponseWriter, r *http.Request, // and printing it next to a real failure buries the real failure. func (s *Server) handleSiteCheck(w http.ResponseWriter, r *http.Request) { p := PrincipalFrom(r.Context()) - siteID := r.PathValue("site") - if !looksLikeUUID(siteID) { - writeErr(w, http.StatusNotFound, "not_found", "That shop no longer exists.") + siteID, ok := s.resolveSite(w, r, r.PathValue("site")) + if !ok { return } sites, err := s.Store.SiteHealth(r.Context(), p.ClientID) diff --git a/server/internal/api/handlers_enrolment.go b/server/internal/api/handlers_enrolment.go index 1e2c8f7..8c21878 100644 --- a/server/internal/api/handlers_enrolment.go +++ b/server/internal/api/handlers_enrolment.go @@ -25,9 +25,8 @@ func (s *Server) handleIssueEnrolmentCode(w http.ResponseWriter, r *http.Request "Your account cannot set up shop computers. Ask a manager or the owner.") return } - site := r.PathValue("site") - if !looksLikeUUID(site) { - writeErr(w, http.StatusNotFound, "not_found", "No such shop.") + site, ok := s.resolveSite(w, r, r.PathValue("site")) + if !ok { return } var in NewEnrolmentCodeInput diff --git a/server/internal/api/handlers_images.go b/server/internal/api/handlers_images.go index fa58f41..60809c9 100644 --- a/server/internal/api/handlers_images.go +++ b/server/internal/api/handlers_images.go @@ -86,9 +86,8 @@ const ( // link stops working, not that we stop publishing it. func (s *Server) handleVisitorImage(w http.ResponseWriter, r *http.Request) { p := PrincipalFrom(r.Context()) - id := r.PathValue("id") - if !looksLikeUUID(id) { - writeErr(w, http.StatusNotFound, "not_found", "That customer no longer exists.") + id, ok := s.resolveVisitor(w, r, r.PathValue("id")) + if !ok { return } key, err := s.Store.VisitorImageKey(r.Context(), p.ClientID, id) @@ -140,9 +139,8 @@ func (s *Server) handleForgetVisitor(w http.ResponseWriter, r *http.Request) { "Your account cannot delete customer records.") return } - id := r.PathValue("id") - if !looksLikeUUID(id) { - writeErr(w, http.StatusNotFound, "not_found", "That customer no longer exists.") + id, ok := s.resolveVisitor(w, r, r.PathValue("id")) + if !ok { return } diff --git a/server/internal/api/handlers_live.go b/server/internal/api/handlers_live.go index d0e5ce9..73bf343 100644 --- a/server/internal/api/handlers_live.go +++ b/server/internal/api/handlers_live.go @@ -32,9 +32,8 @@ const ( // - would be a much worse trade than the 33% base64 costs. func (s *Server) handleWatchLive(w http.ResponseWriter, r *http.Request) { p := PrincipalFrom(r.Context()) - id := r.PathValue("id") - if !looksLikeUUID(id) { - writeErr(w, http.StatusNotFound, "not_found", "No such camera.") + id, ok := s.resolveCamera(w, r, r.PathValue("id")) + if !ok { return } // Ownership is checked HERE, once, before anything is streamed. Everything diff --git a/server/internal/api/handlers_people.go b/server/internal/api/handlers_people.go index c93f3de..410c217 100644 --- a/server/internal/api/handlers_people.go +++ b/server/internal/api/handlers_people.go @@ -26,11 +26,10 @@ func (s *Server) handleVisitors(w http.ResponseWriter, r *http.Request) { func (s *Server) handleVisitorHistory(w http.ResponseWriter, r *http.Request) { p := PrincipalFrom(r.Context()) - id := r.PathValue("id") - if !looksLikeUUID(id) { - // 404, not 400: to the caller a malformed id and an id that does not - // exist are the same thing - the customer is not there. - writeErr(w, http.StatusNotFound, "not_found", "That customer no longer exists.") + // 404, not 400: to the caller a reference that is malformed and one that + // names nobody are the same thing - the customer is not there. + id, ok := s.resolveVisitor(w, r, r.PathValue("id")) + if !ok { return } rows, err := s.Store.VisitorHistory(r.Context(), p.ClientID, id, @@ -65,11 +64,11 @@ func (s *Server) handleSaveProfile(w http.ResponseWriter, r *http.Request) { } // The path wins over the body. Trusting the body would let a client PUT to // one customer's URL and write to another's record. - body.VisitorID = r.PathValue("id") - if !looksLikeUUID(body.VisitorID) { - writeErr(w, http.StatusNotFound, "not_found", "That customer no longer exists.") + visitorID, ok := s.resolveVisitor(w, r, r.PathValue("id")) + if !ok { return } + body.VisitorID = visitorID body.FullName = clip(trim(body.FullName), 200) body.Phone = clip(trim(body.Phone), 40) body.Email = auth.NormalizeEmail(body.Email) @@ -124,10 +123,11 @@ func (s *Server) handlePurchase(w http.ResponseWriter, r *http.Request) { badRequest(w, "visitor_id is required") return } - if !looksLikeUUID(body.VisitorID) { - writeErr(w, http.StatusNotFound, "not_found", "That customer no longer exists.") + visitorID, ok := s.resolveVisitor(w, r, body.VisitorID) + if !ok { return } + body.VisitorID = visitorID if body.Amount < 0 { // A refund is a different record with a different meaning, not a // negative sale. Allowing it here would quietly deflate the revenue diff --git a/server/internal/api/handlers_reports.go b/server/internal/api/handlers_reports.go index 4c415b0..a1da502 100644 --- a/server/internal/api/handlers_reports.go +++ b/server/internal/api/handlers_reports.go @@ -25,7 +25,21 @@ func (s *Server) reportQuery(r *http.Request) (ReportQuery, error) { // The tenant comes from the session. A client_id parameter would be a // cross-tenant read waiting for somebody to try it. - out := ReportQuery{ClientID: p.ClientID, SiteID: trim(q.Get("site"))} + out := ReportQuery{ClientID: p.ClientID} + + // A shop may be named by uuid or by its slug. Resolved here, where an + // unknown one is a 400 the caller can read, rather than in Postgres where + // a malformed uuid is a cast error and surfaces as a 500. + if raw := siteParam(r); raw != "" { + id, err := s.siteIDFor(r.Context(), p.ClientID, raw) + if err != nil { + return out, fmt.Errorf("could not look up that shop: %w", err) + } + if id == "" { + return out, fmt.Errorf("no shop called %q", raw) + } + out.SiteID = id + } now := s.now() from, err := parseDay(q.Get("from"), now.AddDate(0, 0, -29)) diff --git a/server/internal/api/refs.go b/server/internal/api/refs.go new file mode 100644 index 0000000..d184325 --- /dev/null +++ b/server/internal/api/refs.go @@ -0,0 +1,192 @@ +package api + +import ( + "context" + "net/http" + "strconv" + "strings" +) + +// Public references: the names people use for the things this API addresses. +// +// Every id in the schema is a uuid and stays one. A uuid is the right primary +// key here - ids are minted in places that cannot ask a database for the next +// value, and eleven tables reference them - but it is the wrong thing to put in +// front of a person. "Which customer?" "3446ec35-2c1f-4c8e-9a77-0d1e2f3a4b5c." +// Nobody says that, writes it on a card, or reads it back down a phone without +// getting it wrong. +// +// The fix is not a new key. Three of the four things anyone addresses by URL +// ALREADY had a human name that this API simply refused to accept: +// +// site slug "chennai" - in the schema since 001 +// camera camera_id "Office1" - and it is what visits.camera_id holds +// visitor V- "V-42" - added in 012 +// user email - already the login +// +// So a caller may use either form anywhere an id is taken. A uuid resolves with +// no lookup at all, exactly as before; only a non-uuid costs a query. That +// keeps this additive: nothing that worked yesterday changes, including every +// URL a client has already stored. +// +// The visitor number is per TENANT, which is what makes it safe to show. A +// global sequence would tell any customer who signs up how many people the +// whole platform has ever seen, from their own first visitor number. + +// VisitorRefPrefix is deliberately a letter and a dash rather than bare digits. +// It is what makes "V-42" recognisable as a customer rather than an order, a +// till or a visit, and it is why a reference pasted into the wrong route fails +// to parse instead of quietly matching a different record with that number. +const VisitorRefPrefix = "V-" + +// VisitorRef renders a customer number for display and for URLs. +func VisitorRef(number int64) string { + if number <= 0 { + return "" + } + return VisitorRefPrefix + strconv.FormatInt(number, 10) +} + +// ParseVisitorRef accepts "V-42", "v-42" and bare "42". +// +// Bare digits are accepted because a shop assistant reading a number off a +// screen will type the number, and refusing it teaches them to distrust the +// field. There is nothing for it to collide with: a uuid is checked first and +// is never all digits. +func ParseVisitorRef(s string) (int64, bool) { + s = strings.TrimSpace(s) + if s == "" { + return 0, false + } + if len(s) > 2 && (s[0] == 'V' || s[0] == 'v') && s[1] == '-' { + s = s[2:] + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n <= 0 { + return 0, false + } + return n, true +} + +// looksLikeName bounds a slug or camera id before it reaches SQL. Not a +// validity check - the lookup decides that - only a guard so a path segment +// full of junk is answered as "no such thing" without a round trip. +func looksLikeName(s string) bool { + if s == "" || len(s) > 64 { + return false + } + for _, c := range s { + ok := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' + if !ok { + return false + } + } + return true +} + +// Each reference has two resolvers: an inner one that answers ("", nil) for +// "no such thing", and an outer one that writes the response itself so a call +// site stays the same three lines the uuid check was. Both exist because a +// query parameter is validated where a 400 is the right answer and a path +// segment where a 404 is - splitting them lets one implementation serve both. +// +// A reference that does not resolve is 404 on a path, never 400, for the reason +// the old shape check gave: to the caller, a malformed reference and one that +// names nothing are the same thing - it is not there. + +func (s *Server) visitorIDFor(ctx context.Context, clientID, raw string) (string, error) { + if looksLikeUUID(raw) { + return raw, nil + } + number, ok := ParseVisitorRef(raw) + if !ok { + return "", nil + } + return s.Store.VisitorIDByNumber(ctx, clientID, number) +} + +func (s *Server) siteIDFor(ctx context.Context, clientID, raw string) (string, error) { + if looksLikeUUID(raw) { + return raw, nil + } + if !looksLikeName(raw) { + return "", nil + } + return s.Store.SiteIDBySlug(ctx, clientID, strings.ToLower(raw)) +} + +func (s *Server) cameraIDFor(ctx context.Context, clientID, raw string) (string, error) { + if looksLikeUUID(raw) { + return raw, nil + } + if !looksLikeName(raw) { + return "", nil + } + return s.Store.CameraIDByRef(ctx, clientID, raw) +} + +func (s *Server) resolveVisitor(w http.ResponseWriter, r *http.Request, raw string) (string, bool) { + return s.resolve(w, r, raw, s.visitorIDFor, "customer", + "That customer no longer exists.") +} + +func (s *Server) resolveSite(w http.ResponseWriter, r *http.Request, raw string) (string, bool) { + return s.resolve(w, r, raw, s.siteIDFor, "site", + "That shop no longer exists.") +} + +func (s *Server) resolveCamera(w http.ResponseWriter, r *http.Request, raw string) (string, bool) { + return s.resolve(w, r, raw, s.cameraIDFor, "camera", + "That camera no longer exists.") +} + +// resolveSiteFilter is the query-string form: 400, not 404. +// +// The distinction is not pedantry. `/api/visits` exists and answered - what was +// wrong was the filter the caller attached to it, and a 404 there reads as "the +// arrivals feed is gone", which is a very different thing to go and investigate. +// A path segment names the resource itself, so an unknown one IS a 404. +func (s *Server) resolveSiteFilter(w http.ResponseWriter, r *http.Request, raw string) (string, bool) { + p := PrincipalFrom(r.Context()) + id, err := s.siteIDFor(r.Context(), p.ClientID, raw) + if err != nil { + s.serverError(w, "resolve site", err) + return "", false + } + if id == "" { + badRequest(w, "no shop called "+strconv.Quote(raw)) + return "", false + } + return id, true +} + +func (s *Server) resolve(w http.ResponseWriter, r *http.Request, raw string, + lookup func(context.Context, string, string) (string, error), + what, gone string) (string, bool) { + + p := PrincipalFrom(r.Context()) + id, err := lookup(r.Context(), p.ClientID, raw) + if err != nil { + s.serverError(w, "resolve "+what, err) + return "", false + } + if id == "" { + writeErr(w, http.StatusNotFound, "not_found", gone) + return "", false + } + return id, true +} + +// siteParam reads "which shop" off a query string. +// +// Reports have always taken `site` and the arrivals feed `site_id`, which is a +// wart rather than a rule - and an unknown query parameter is silently ignored, +// so getting it the wrong way round returns the whole estate instead of an +// error. Both names are accepted everywhere now; `site` is the documented one. +func siteParam(r *http.Request) string { + if v := trim(r.URL.Query().Get("site")); v != "" { + return v + } + return trim(r.URL.Query().Get("site_id")) +} diff --git a/server/internal/api/refs_test.go b/server/internal/api/refs_test.go new file mode 100644 index 0000000..8f92b2f --- /dev/null +++ b/server/internal/api/refs_test.go @@ -0,0 +1,110 @@ +package api + +import ( + "net/http" + "testing" +) + +func TestVisitorRefRoundTrips(t *testing.T) { + for _, n := range []int64{1, 42, 999999} { + ref := VisitorRef(n) + got, ok := ParseVisitorRef(ref) + if !ok || got != n { + t.Fatalf("VisitorRef(%d) = %q, parsed back as (%d, %v)", n, ref, got, ok) + } + } + if got := VisitorRef(0); got != "" { + t.Fatalf("an unnumbered visitor must render as no reference, got %q", got) + } +} + +// A shop assistant reading "Visitor 42" off a screen types 42. Refusing that +// teaches them the field is unreliable, so bare digits are accepted - and there +// is nothing for them to collide with, because a uuid is checked first and is +// never all digits. +func TestVisitorRefAcceptsWhatSomebodyWouldActuallyType(t *testing.T) { + for _, in := range []string{"V-42", "v-42", "42", " V-42 "} { + n, ok := ParseVisitorRef(in) + if !ok || n != 42 { + t.Fatalf("ParseVisitorRef(%q) = (%d, %v), want 42", in, n, ok) + } + } + for _, in := range []string{"", "V-", "V-0", "-1", "V-x", "abc", "4 2", + "3446ec35-2c1f-4c8e-9a77-0d1e2f3a4b5c"} { + if _, ok := ParseVisitorRef(in); ok { + t.Fatalf("ParseVisitorRef(%q) accepted a reference it should not", in) + } + } +} + +func TestLooksLikeNameRejectsJunkBeforeItReachesSQL(t *testing.T) { + for _, ok := range []string{"chennai", "Office1", "cam_2", "a.b-c"} { + if !looksLikeName(ok) { + t.Fatalf("%q should be a usable name", ok) + } + } + for _, bad := range []string{"", "a b", "a/b", "a'b", "../etc", "%", string(make([]byte, 65))} { + if looksLikeName(bad) { + t.Fatalf("%q should not reach a query", bad) + } + } +} + +// The point of the whole scheme: a customer is addressable by the number staff +// read on screen, and the uuid that clients already stored keeps working. +func TestACustomerIsReachableByNumberAndByUUID(t *testing.T) { + const id = "3446ec35-2c1f-4c8e-9a77-0d1e2f3a4b5c" + srv, fs := newServer(t) + seedUser(fs) + fs.visitors = []Customer{{ID: id, Ref: "V-42", Label: "Visitor 42"}} + fs.history = []VisitRow{{Site: "Chennai"}} + tok := login(t, srv, "manager@acme.com", "correct horse battery").Token + + for _, path := range []string{"/api/visitors/" + id + "/history", + "/api/visitors/V-42/history", "/api/visitors/42/history"} { + rec := do(t, srv, http.MethodGet, path, tok, nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET %s = %d, want 200", path, rec.Code) + } + } +} + +// A reference that names nobody is 404 on a path, and a filter that names no +// shop is 400 on a query string. The difference matters: `/api/visits` answered +// fine and what was wrong was the filter, so a 404 there would send somebody +// looking for a missing arrivals feed. +func TestAnUnknownReferenceIs404OnAPathAnd400OnAFilter(t *testing.T) { + srv, fs := newServer(t) + seedUser(fs) + tok := login(t, srv, "manager@acme.com", "correct horse battery").Token + + rec := do(t, srv, http.MethodGet, "/api/visitors/V-999/history", tok, nil) + if rec.Code != http.StatusNotFound { + t.Fatalf("unknown customer = %d, want 404", rec.Code) + } + rec = do(t, srv, http.MethodGet, "/api/visits?site=nowhere", tok, nil) + if rec.Code != http.StatusBadRequest { + t.Fatalf("unknown shop filter = %d, want 400", rec.Code) + } +} + +// Reports have always taken `site` and the arrivals feed `site_id`. Both work +// everywhere now, because an unknown query parameter is silently ignored - so +// getting it the wrong way round returned the whole estate rather than an +// error, which is a wrong number nobody would question. +func TestBothSiteParameterNamesAreAccepted(t *testing.T) { + srv, fs := newServer(t) + seedUser(fs) + fs.sites = []SiteHealth{{SiteID: "11111111-1111-4111-8111-111111111111", Slug: "chennai"}} + tok := login(t, srv, "manager@acme.com", "correct horse battery").Token + + for _, q := range []string{"site=chennai", "site_id=chennai"} { + fs.arrivalQ = ArrivalQuery{} + if rec := do(t, srv, http.MethodGet, "/api/visits?"+q, tok, nil); rec.Code != http.StatusOK { + t.Fatalf("GET /api/visits?%s = %d", q, rec.Code) + } + if got := fs.arrivalQ.SiteID; got != "11111111-1111-4111-8111-111111111111" { + t.Fatalf("%s resolved to %q", q, got) + } + } +} diff --git a/server/internal/api/types.go b/server/internal/api/types.go index f58537d..b1aec70 100644 --- a/server/internal/api/types.go +++ b/server/internal/api/types.go @@ -109,7 +109,11 @@ type SalesReport struct { } type Customer struct { - ID string `json:"id"` + ID string `json:"id"` + // Ref is the customer number - "V-42" - and is accepted anywhere this + // customer's id is. It ships alongside the uuid rather than replacing it + // because a client that stored a uuid must keep working; see refs.go. + Ref string `json:"ref,omitempty"` Label string `json:"label"` FullName string `json:"full_name"` Phone string `json:"phone"` @@ -252,6 +256,9 @@ type Arrival struct { // appear in the feed - a shop watching arrivals would otherwise see fewer // people than walked in. VisitorID string `json:"visitor_id,omitempty"` + // VisitorRef is the same person as "V-42": what staff read on screen and + // type into a search box. Empty exactly when VisitorID is. + VisitorRef string `json:"visitor_ref,omitempty"` // Label is the system's own name ("Visitor 12"); Name is what a human // typed. Both are sent so the client does not have to guess which is // present, and so a screen can show the real name and still let staff diff --git a/server/internal/store/api_arrivals.go b/server/internal/store/api_arrivals.go index d606429..fc748f6 100644 --- a/server/internal/store/api_arrivals.go +++ b/server/internal/store/api_arrivals.go @@ -15,6 +15,7 @@ const arrivalColumns = ` vi.id::text, vi.seq, vi.occurred_at, vi.site_id::text, si.name, vi.camera_id, vi.is_new_visitor, vi.similarity, vi.quality, vi.attributes, vi.image_key, COALESCE(vi.visitor_id::text, ''), + COALESCE(vs.number, 0), COALESCE(vs.label, ''), COALESCE(p.full_name, '')` @@ -111,11 +112,13 @@ func (s *Store) Arrivals(ctx context.Context, q api.ArrivalQuery) ([]api.Arrival var at time.Time var sim, qual *float64 var imageKey string + var number int64 if err := rows.Scan(&a.VisitID, &a.Seq, &at, &a.SiteID, &a.Site, &a.CameraID, &a.IsNew, &sim, &qual, &a.Attributes, &imageKey, - &a.VisitorID, &a.Label, &a.Name); err != nil { + &a.VisitorID, &number, &a.Label, &a.Name); err != nil { return nil, err } + a.VisitorRef = api.VisitorRef(number) a.OccurredAt = at.UTC().Format(time.RFC3339Nano) if sim != nil { a.Similarity = *sim diff --git a/server/internal/store/api_arrivals_live_test.go b/server/internal/store/api_arrivals_live_test.go index f9a2a6d..5f994f2 100644 --- a/server/internal/store/api_arrivals_live_test.go +++ b/server/internal/store/api_arrivals_live_test.go @@ -63,9 +63,9 @@ func seedTenant(t *testing.T, st *Store, name string, n int, withImages bool) (c for i := 0; i < n; i++ { var visitorID string if err := st.pool.QueryRow(ctx, ` - INSERT INTO visitors (client_id, label, first_seen_at) - VALUES ($1::uuid, $2, $3) RETURNING id::text`, - clientID, fmt.Sprintf("Visitor %d", i), start).Scan(&visitorID); err != nil { + INSERT INTO visitors (client_id, number, label, first_seen_at) + VALUES ($1::uuid, $2, $3, $4) RETURNING id::text`, + clientID, i+1, fmt.Sprintf("Visitor %d", i+1), start).Scan(&visitorID); err != nil { t.Fatalf("seed visitor: %v", err) } key := "" diff --git a/server/internal/store/api_people.go b/server/internal/store/api_people.go index 08e2ab0..20f5dba 100644 --- a/server/internal/store/api_people.go +++ b/server/internal/store/api_people.go @@ -25,11 +25,27 @@ func likePattern(q string) string { return "%" + r.Replace(q) + "%" } +// searchNumber is the customer number behind a query, or 0 for a query that is +// not one. +// +// The reference is what staff now READ on screen - "V-13" - so it is what they +// paste into the search box, and matching only `label ILIKE '%V-13%'` finds +// nothing at all, because the stored label says "Visitor 13". A search that +// comes back empty for the identifier the product just showed you is worse +// than no search at all. +func searchNumber(query string) int64 { + n, ok := api.ParseVisitorRef(query) + if !ok { + return 0 + } + return n +} + func (s *Store) SearchVisitors(ctx context.Context, clientID, query string, limit int) ( []api.Customer, error) { rows, err := s.pool.Query(ctx, ` - SELECT v.id::text, v.label, + SELECT v.id::text, v.number, v.label, COALESCE(p.full_name, ''), COALESCE(p.phone, ''), COALESCE(p.email, ''), v.visit_count, v.first_seen_at, v.last_seen_at, (p.id IS NOT NULL), @@ -39,13 +55,15 @@ func (s *Store) SearchVisitors(ctx context.Context, clientID, query string, limi LEFT JOIN visitor_profiles p ON p.visitor_id = v.id AND p.client_id = v.client_id WHERE v.client_id = $1 AND v.deleted_at IS NULL - AND ($2 = '' OR v.label ILIKE $3 ESCAPE '\' + AND ($2 = '' OR v.number = $5 + OR v.label ILIKE $3 ESCAPE '\' OR p.full_name ILIKE $3 ESCAPE '\' OR p.phone ILIKE $3 ESCAPE '\' OR p.email ILIKE $3 ESCAPE '\') ORDER BY v.last_seen_at DESC NULLS LAST, v.first_seen_at DESC LIMIT $4`, - clientID, strings.TrimSpace(query), likePattern(strings.TrimSpace(query)), limit) + clientID, strings.TrimSpace(query), likePattern(strings.TrimSpace(query)), + limit, searchNumber(query)) if err != nil { return nil, err } @@ -56,10 +74,12 @@ func (s *Store) SearchVisitors(ctx context.Context, clientID, query string, limi var c api.Customer var first time.Time var last *time.Time - if err := rows.Scan(&c.ID, &c.Label, &c.FullName, &c.Phone, &c.Email, + var number int64 + if err := rows.Scan(&c.ID, &number, &c.Label, &c.FullName, &c.Phone, &c.Email, &c.VisitCount, &first, &last, &c.HasProfile, &c.HasConsent); err != nil { return nil, err } + c.Ref = api.VisitorRef(number) c.FirstSeenAt = first.UTC().Format(time.RFC3339) if last != nil { c.LastSeenAt = last.UTC().Format(time.RFC3339) diff --git a/server/internal/store/api_refs.go b/server/internal/store/api_refs.go new file mode 100644 index 0000000..6fcf168 --- /dev/null +++ b/server/internal/store/api_refs.go @@ -0,0 +1,81 @@ +package store + +import ( + "context" + "errors" + + "github.com/jackc/pgx/v5" +) + +// Resolving a public reference to the uuid it names. +// +// Every id in this schema is a uuid and stays one. These three exist because a +// uuid is not something a person can say, type or recognise, and three of the +// four things anyone addresses by URL already HAD a human name that the API +// simply refused to accept: a site has a slug, a camera has the id the engine +// knows it by (and the one that lands in `visits.camera_id`), and a visitor now +// has a per-tenant number. See api/refs.go for the formats. +// +// All three answer "" with a nil error when nothing matches. A found id is +// never empty, so the two cases cannot be confused, and a mistyped reference is +// a 404 rather than an error the handler has to classify. + +// SiteIDBySlug resolves a site slug within one tenant. +func (s *Store) SiteIDBySlug(ctx context.Context, clientID, slug string) (string, error) { + var id string + err := s.pool.QueryRow(ctx, ` + SELECT id::text FROM sites + WHERE client_id = $1::uuid AND slug = $2`, + clientID, slug).Scan(&id) + if errors.Is(err, pgx.ErrNoRows) { + return "", nil + } + return id, err +} + +// CameraIDByRef resolves the engine's own camera id - "Office1" - to the row +// uuid, within one tenant. +// +// A camera id is unique per SITE, not per tenant, so two shops may each have an +// "Office1". Ambiguity is resolved as no match rather than by picking one: +// silently acting on whichever row sorted first would edit or delete the wrong +// shop's camera. A caller in that position has the uuid, or can scope by site. +func (s *Store) CameraIDByRef(ctx context.Context, clientID, ref string) (string, error) { + rows, err := s.pool.Query(ctx, ` + SELECT id::text FROM site_cameras + WHERE client_id = $1::uuid AND camera_id = $2 AND deleted_at IS NULL + LIMIT 2`, clientID, ref) + if err != nil { + return "", err + } + defer rows.Close() + + var found []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return "", err + } + found = append(found, id) + } + if err := rows.Err(); err != nil { + return "", err + } + if len(found) != 1 { + return "", nil + } + return found[0], nil +} + +// VisitorIDByNumber resolves the number behind "V-42" within one tenant. +func (s *Store) VisitorIDByNumber(ctx context.Context, clientID string, number int64) (string, error) { + var id string + err := s.pool.QueryRow(ctx, ` + SELECT id::text FROM visitors + WHERE client_id = $1::uuid AND number = $2`, + clientID, number).Scan(&id) + if errors.Is(err, pgx.ErrNoRows) { + return "", nil + } + return id, err +} diff --git a/server/internal/store/api_refs_live_test.go b/server/internal/store/api_refs_live_test.go new file mode 100644 index 0000000..4ff1770 --- /dev/null +++ b/server/internal/store/api_refs_live_test.go @@ -0,0 +1,182 @@ +package store + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/loyaly/behavision-server/internal/contract" + "github.com/loyaly/behavision-server/internal/ingest" +) + +// The name a shop assistant actually reads. +// +// Before 012 this was `'Visitor ' || left(id::text, 8)`, so the arrivals feed +// said "Visitor 3446ec35" - a string nobody can say out loud, write on a card +// or type into a search box. The number is what fixes that, and it has to be +// right at the point it is WRITTEN: `label` is a stored column that staff can +// overwrite and that SearchVisitors matches on, so formatting around it in the +// front end would have left the stored data wrong on three surfaces. +// +// Only a real database proves this. The counter lives on `clients` and is taken +// with UPDATE ... RETURNING inside the visit transaction - the same semantics +// that silently broke the face prune in 011 by returning the value it had just +// written. Here that is exactly what is wanted, and an in-memory fake would +// agree with any implementation. +// distinctFace returns a vector pointing along its own axis, so any two of them +// are orthogonal - cosine 0, far below any match threshold. +// +// `embedding(seed)` fills every dimension with one value, so after L2 +// normalisation 0.31 and 0.62 are the SAME direction and the matcher correctly +// calls them one person. That is right for the face tests it was written for +// and useless here, where the whole point is several different people. +func distinctFace(i int) []float32 { + v := make([]float32, contract.EmbeddingDim) + v[i%contract.EmbeddingDim] = 1 + return v +} + +func TestLiveVisitorNumbersStartAtOneForEveryTenant(t *testing.T) { + st := liveStore(t) + ctx := context.Background() + + // Two tenants, so a number that leaked across them would show up as a gap. + for _, tenant := range []string{"num-a-" + stamp(), "num-b-" + stamp()} { + site := seedAgentSite(t, st, tenant) + + for i := 0; i < 3; i++ { + // A different face each time, so each becomes its own visitor. + ok, err := st.RecordVisit(ctx, site, &contract.Visit{ + EventID: fmt.Sprintf("%s-%d", tenant, i), + OccurredAt: time.Now().UTC().Add(time.Duration(i) * time.Second), + CameraID: "door", + IsNew: true, + Quality: 0.8, + Embedding: distinctFace(i), + }) + if err != nil || !ok { + t.Fatalf("%s visit %d: ok=%v err=%v", tenant, i, ok, err) + } + } + + rows, err := st.pool.Query(ctx, ` + SELECT number, label FROM visitors + WHERE client_id = $1::uuid ORDER BY number`, site.ClientID) + if err != nil { + t.Fatal(err) + } + var got []string + for rows.Next() { + var n int64 + var label string + if err := rows.Scan(&n, &label); err != nil { + t.Fatal(err) + } + got = append(got, fmt.Sprintf("%d=%s", n, label)) + } + rows.Close() + + want := []string{"1=Visitor 1", "2=Visitor 2", "3=Visitor 3"} + if len(got) != len(want) { + t.Fatalf("%s: got %v, want %v", tenant, got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("%s: got %v, want %v", tenant, got, want) + } + } + } +} + +// A number is a public reference, so it must resolve only within the tenant it +// belongs to. Both tenants have a V-1; asking as one must never return the +// other's customer. +func TestLiveAVisitorNumberResolvesOnlyWithinItsOwnTenant(t *testing.T) { + st := liveStore(t) + ctx := context.Background() + + mine := seedAgentSite(t, st, "ref-mine-"+stamp()) + theirs := seedAgentSite(t, st, "ref-theirs-"+stamp()) + + for i, s := range []ingest.Site{mine, theirs} { + if ok, err := st.RecordVisit(ctx, s, &contract.Visit{ + EventID: s.Slug + "-1", + OccurredAt: time.Now().UTC(), + CameraID: "door", + IsNew: true, + Quality: 0.8, + Embedding: distinctFace(i), + }); err != nil || !ok { + t.Fatalf("seed visit: ok=%v err=%v", ok, err) + } + } + + mineID, err := st.VisitorIDByNumber(ctx, mine.ClientID, 1) + if err != nil || mineID == "" { + t.Fatalf("V-1 in my own tenant: %q %v", mineID, err) + } + theirsID, err := st.VisitorIDByNumber(ctx, theirs.ClientID, 1) + if err != nil || theirsID == "" { + t.Fatalf("V-1 in the other tenant: %q %v", theirsID, err) + } + if mineID == theirsID { + t.Fatal("V-1 resolved to the same customer for two different tenants") + } + + // And a number nobody has is a miss, not an error - which is what lets the + // handler answer 404 without classifying an error first. + got, err := st.VisitorIDByNumber(ctx, mine.ClientID, 999999) + if err != nil || got != "" { + t.Fatalf("unknown number: got %q, err %v - want an empty miss", got, err) + } +} + +// A site slug and a camera id are the other two references, and both already +// existed in the schema; only the API refused to accept them. +func TestLiveSiteAndCameraResolveByTheirOwnNames(t *testing.T) { + st := liveStore(t) + ctx := context.Background() + site := seedAgentSite(t, st, "names-"+stamp()) + + id, err := st.SiteIDBySlug(ctx, site.ClientID, site.Slug) + if err != nil || id != site.SiteID { + t.Fatalf("slug %q resolved to %q (want %q), err %v", + site.Slug, id, site.SiteID, err) + } + if got, err := st.SiteIDBySlug(ctx, site.ClientID, "no-such-shop"); err != nil || got != "" { + t.Fatalf("unknown slug: got %q, err %v", got, err) + } + + var camUUID string + if err := st.pool.QueryRow(ctx, ` + INSERT INTO site_cameras (client_id, site_id, camera_id, label, host) + VALUES ($1::uuid, $2::uuid, 'Office1', 'Front door', '10.0.0.5') + RETURNING id::text`, site.ClientID, site.SiteID).Scan(&camUUID); err != nil { + t.Fatal(err) + } + got, err := st.CameraIDByRef(ctx, site.ClientID, "Office1") + if err != nil || got != camUUID { + t.Fatalf("camera by name: got %q (want %q), err %v", got, camUUID, err) + } + + // Two shops in one tenant may each have an "Office1". Acting on whichever + // row sorted first would edit the wrong shop's camera, so ambiguity must + // resolve to nothing rather than to a guess. + var secondSite string + if err := st.pool.QueryRow(ctx, ` + INSERT INTO sites (client_id, name, slug) VALUES ($1::uuid, 'Second', $2) + RETURNING id::text`, site.ClientID, site.Slug+"-2").Scan(&secondSite); err != nil { + t.Fatal(err) + } + if _, err := st.pool.Exec(ctx, ` + INSERT INTO site_cameras (client_id, site_id, camera_id, label, host) + VALUES ($1::uuid, $2::uuid, 'Office1', 'Other door', '10.0.0.6')`, + site.ClientID, secondSite); err != nil { + t.Fatal(err) + } + if got, err := st.CameraIDByRef(ctx, site.ClientID, "Office1"); err != nil || got != "" { + t.Fatalf("an ambiguous camera name resolved to %q - it must resolve to "+ + "nothing rather than pick one", got) + } +} diff --git a/server/internal/store/store.go b/server/internal/store/store.go index b33b21d..17a509d 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -222,18 +222,34 @@ func (s *Store) matchOrCreateVisitor(ctx context.Context, tx pgx.Tx, } // New person for this client. + // + // The number comes off the tenant's own counter rather than being derived + // from the uuid, because it is what a human will read, say and search for: + // "Visitor 42", not "Visitor 3446ec35". UPDATE ... RETURNING yields the + // value AFTER the update, which is what is wanted here, and it row-locks + // the client for the length of the insert so two shops cannot take the + // same number. That lock is free - this runs only for a face nobody in the + // estate has ever seen, not once per visit. + var number int64 + if err := tx.QueryRow(ctx, ` + UPDATE clients SET visitor_seq = visitor_seq + 1 + WHERE id = $1 RETURNING visitor_seq`, + site.ClientID).Scan(&number); err != nil { + return "", fmt.Errorf("next visitor number: %w", err) + } + // The label is formatted here rather than as `'Visitor ' || $2::text` in + // the statement: reusing one parameter as a bigint and as a string operand + // makes Postgres deduce two types for it and refuse the whole insert + // ("inconsistent types deduced for parameter $2"). It compiled, it passed + // every in-memory test, and it failed on the first real database. var newID string if err := tx.QueryRow(ctx, ` - INSERT INTO visitors (client_id, label, first_seen_at) - VALUES ($1, '', $2) RETURNING id::text`, - site.ClientID, v.OccurredAt).Scan(&newID); err != nil { + INSERT INTO visitors (client_id, number, label, first_seen_at) + VALUES ($1, $2, $3, $4) RETURNING id::text`, + site.ClientID, number, fmt.Sprintf("Visitor %d", number), + v.OccurredAt).Scan(&newID); err != nil { return "", fmt.Errorf("create visitor: %w", err) } - if _, err := tx.Exec(ctx, ` - UPDATE visitors SET label = 'Visitor ' || left(id::text, 8) - WHERE id = $1 AND label = ''`, newID); err != nil { - return "", err - } if _, err := tx.Exec(ctx, ` INSERT INTO visitor_embeddings (visitor_id, client_id, model, embedding, quality, source_site_id) diff --git a/server/internal/web/dist/assets/index-Dv7hKDIX.js b/server/internal/web/dist/assets/index-BI5JLIeo.js similarity index 85% rename from server/internal/web/dist/assets/index-Dv7hKDIX.js rename to server/internal/web/dist/assets/index-BI5JLIeo.js index 61f46c3..4e3e7a1 100644 --- a/server/internal/web/dist/assets/index-Dv7hKDIX.js +++ b/server/internal/web/dist/assets/index-BI5JLIeo.js @@ -43,4 +43,4 @@ Error generating stack: `+s.message+` `))if(p.startsWith("id: "))i=p.slice(4).trim();else if(p.startsWith("data: "))try{n(JSON.parse(p.slice(6)))}catch{}}}}catch(u){if(s||l!=null&&l.aborted)return;r==null||r(u)}if(s)return;await new Promise(u=>setTimeout(u,3e3))}})(),()=>{s=!0}}function np({cameraId:e,img:t,onState:n,signal:r}){let l=!1;return(async()=>{for(;!l;){try{const{access:i}=ir(),a=await fetch(`/api/cameras/${e}/live`,{headers:{Authorization:"Bearer "+i,Accept:"text/event-stream"},signal:r});if(a.status===401){await Tl();continue}if(!a.ok||!a.body)throw new Error("live view unavailable");const u=a.body.getReader(),c=new TextDecoder;let v="";for(;!l;){const{value:m,done:h}=await u.read();if(h)break;v+=c.decode(m,{stream:!0});let y;for(;(y=v.indexOf(` `))!==-1;){const x=v.slice(0,y);v=v.slice(y+2);let g="message",T="";for(const p of x.split(` -`))p.startsWith("event: ")?g=p.slice(7).trim():p.startsWith("data: ")&&(T=p.slice(6));g==="frame"&&T?(t.current&&(t.current.src="data:image/jpeg;base64,"+T),n==null||n("live")):g==="waiting"&&(n==null||n("waiting"))}}}catch{if(l||r!=null&&r.aborted)return;n==null||n("reconnecting")}if(l)return;await new Promise(i=>setTimeout(i,1500))}})(),()=>{l=!0}}function rp({onSignedIn:e}){const[t,n]=j.useState(!1);return t?o.jsx(sp,{onSignedIn:e,onCancel:()=>n(!1)}):o.jsx(lp,{onSignedIn:e,onJoin:()=>n(!0)})}function lp({onSignedIn:e,onJoin:t}){const[n,r]=j.useState(""),[l,s]=j.useState(""),[i,a]=j.useState(""),[u,c]=j.useState(!1),v=async m=>{m.preventDefault(),c(!0),a("");try{await $.login(n.trim(),l),e(await $.me())}catch(h){a(h.message),c(!1)}};return o.jsx("div",{className:"signin",children:o.jsxs("form",{className:"card",onSubmit:v,children:[o.jsx("span",{className:"mark big","aria-hidden":"true"}),o.jsx("h1",{children:"Behavision"}),o.jsx("p",{className:"sub",children:"Sign in to your company account."}),o.jsxs("label",{children:["Email",o.jsx("input",{type:"email",value:n,autoComplete:"username",autoFocus:!0,required:!0,onChange:m=>r(m.target.value),placeholder:"you@company.com"})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"password",value:l,autoComplete:"current-password",required:!0,onChange:m=>s(m.target.value)})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"primary",disabled:u||!n||!l,children:u?"Signing in…":"Sign in"}),o.jsxs("p",{className:"foot",children:["Been invited? ",o.jsx("button",{type:"button",className:"linkish",onClick:t,children:"Use your invitation code"})]})]})})}function sp({onSignedIn:e,onCancel:t}){const[n,r]=j.useState(""),[l,s]=j.useState(null),[i,a]=j.useState(""),[u,c]=j.useState(""),[v,m]=j.useState(""),[h,y]=j.useState(""),[x,g]=j.useState(!1),T=async d=>{d.preventDefault(),g(!0),y("");try{const f=await $.previewInvitation(n.trim());s(f),a(f.full_name||"")}catch(f){y(f.message)}finally{g(!1)}},p=async d=>{if(d.preventDefault(),u!==v){y("Those two passwords are not the same.");return}g(!0),y("");try{const f=await $.register({code:n.trim(),full_name:i,password:u});e(f)}catch(f){y(f.message),g(!1)}};return o.jsx("div",{className:"signin",children:o.jsxs("form",{className:"card",onSubmit:l?p:T,children:[o.jsx("span",{className:"mark big","aria-hidden":"true"}),o.jsx("h1",{children:l?`Join ${l.client_name}`:"Behavision"}),l?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"sub",children:["You are joining as ",o.jsx("b",{children:l.role}),", signing in with"," ",o.jsx("code",{children:l.email}),". Choose a password only you know."]}),o.jsxs("label",{children:["Your name",o.jsx("input",{value:i,onChange:d=>a(d.target.value),autoFocus:!0,autoComplete:"name"})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"password",value:u,required:!0,minLength:8,autoComplete:"new-password",onChange:d=>c(d.target.value)}),o.jsx("span",{className:"hint",children:"At least 8 characters. Longer is the only thing that helps."})]}),o.jsxs("label",{children:["Password again",o.jsx("input",{type:"password",value:v,required:!0,autoComplete:"new-password",onChange:d=>m(d.target.value)})]}),h&&o.jsx("p",{className:"error",role:"alert",children:h}),o.jsx("button",{className:"primary",disabled:x||!u||!v,children:x?"Creating your account…":"Create account and sign in"})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Enter the invitation code you were given."}),o.jsxs("label",{children:["Invitation code",o.jsx("input",{value:n,onChange:d=>r(d.target.value),autoFocus:!0,required:!0,autoComplete:"off",spellCheck:"false",placeholder:"ABCDEF-123456-GHIJKL-789012",className:"codefield"}),o.jsx("span",{className:"hint",children:"Dashes and capitals do not matter."})]}),h&&o.jsx("p",{className:"error",role:"alert",children:h}),o.jsx("button",{className:"primary",disabled:x||!n.trim(),children:x?"Checking…":"Continue"})]}),o.jsx("p",{className:"foot",children:o.jsx("button",{type:"button",className:"linkish",onClick:t,children:"Back to sign in"})})]})})}function It(e,t,n=[]){const[r,l]=j.useState(null),[s,i]=j.useState(null),[a,u]=j.useState(!0),c=j.useRef(!1),v=j.useRef(!0),m=j.useCallback(async()=>{if(!c.current){c.current=!0;try{const h=await e();if(!v.current)return;l(h),i(null)}catch(h){if(!v.current)return;i(h)}finally{c.current=!1,v.current&&u(!1)}}},n);return j.useEffect(()=>{if(v.current=!0,m(),!t)return()=>{v.current=!1};const h=setInterval(m,t);return()=>{v.current=!1,clearInterval(h)}},[m,t]),{data:r,error:s,loading:a,reload:m}}function ip(e){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!e){n(null);return}let r=!0,l=null;return $.cameraSnapshot(e).then(s=>{if(!r){URL.revokeObjectURL(s);return}l=s,n(s)}).catch(()=>{r&&n(null)}),()=>{r=!1,l&&URL.revokeObjectURL(l)}},[e]),t}function Xi({image:e,url:t,alt:n}){const r=e?e.url:t,l=e&&!!e.auth||typeof r=="string"&&r.startsWith("/"),s=ip(l?r:null),i=l?s:r;return i?o.jsx("img",{src:i,alt:n,loading:"lazy"}):null}function op({site:e,onClose:t}){const[n,r]=j.useState(null),[l,s]=j.useState(!1),[i,a]=j.useState(""),u=async()=>{s(!0),a(""),r(null);try{r(await $.siteCheck(e.site_id))}catch(c){a(c.message)}finally{s(!1)}};return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsxs("h2",{children:["Is ",e.name," working?"]}),o.jsx("p",{className:"sub",children:"Checks the whole chain, from the shop’s PC to head office."})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[!n&&!l&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Nothing is changed and no one is disturbed — this reads what the shop has already reported."}),o.jsx("button",{className:"primary",onClick:u,children:"Run the check"})]}),l&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsx("b",{children:"Checking…"})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"banner "+(n.ok?"ok":"warn"),children:o.jsxs("div",{children:[o.jsx("b",{children:n.ok?"This shop is working.":"This shop needs attention."}),!n.ok&&o.jsx(o.Fragment,{children:" Work down the list — the first failure usually explains the rest."})]})}),o.jsx("ol",{className:"checklist",children:n.steps.map(c=>o.jsxs("li",{className:c.status,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:c.status==="pass"?"✓":c.status==="fail"?"✕":c.status==="warn"?"!":"–"}),o.jsxs("div",{children:[o.jsx("b",{children:c.name}),o.jsx("span",{className:"sub",children:c.detail}),c.advice&&o.jsx("span",{className:"advice-line",children:c.advice})]})]},c.name))}),o.jsx("button",{className:"ghost",onClick:u,children:"Check again"})]}),o.jsx(ap,{site:e})]})]})})}function ap({site:e}){const[t,n]=j.useState(null),[r,l]=j.useState(!1),[s,i]=j.useState(""),[a,u]=j.useState(""),c=async()=>{l(!0),i("");try{n(await $.enrolmentCode(e.site_id,{label:a.trim()}))}catch(v){i(v.message)}finally{l(!1)}};return o.jsxs("section",{className:"claim",children:[o.jsx("h3",{children:"Set up a shop PC"}),t?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"code","aria-live":"polite",children:t.code}),o.jsxs("p",{className:"sub",children:["Copy this now — it cannot be shown again. It works once, and stops working ",cp(t.expires_at),"."]}),o.jsxs("div",{className:"row",children:[o.jsx("button",{className:"ghost",onClick:()=>up(t.code),children:"Copy"}),o.jsx("button",{className:"ghost",onClick:()=>n(null),children:"Done"})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Creates a one-time code to type into Behavision on the shop’s computer. Use one for a new shop, a replacement PC, or a reinstall."}),o.jsxs("label",{className:"field",children:[o.jsx("span",{children:"What is this PC? (optional)"}),o.jsx("input",{value:a,placeholder:"counter PC",onChange:v=>u(v.target.value)})]}),s&&o.jsx("p",{className:"error",role:"alert",children:s}),o.jsx("button",{className:"ghost",onClick:c,disabled:r,children:r?"Creating…":"Create an installation code"})]})]})}function up(e){var t;try{(t=navigator.clipboard)==null||t.writeText(e)}catch{}}function cp(e){const t=new Date(e).getTime();if(Number.isNaN(t))return"shortly";const n=Math.round((t-Date.now())/864e5);return n<=0?"today":n===1?"tomorrow":`in ${n} days`}function dp(){const{data:e,error:t,loading:n}=It(()=>$.sites(),2e4,[]),{data:r}=It(()=>$.cameras(),6e4,[]),[l,s]=j.useState(null),i=e||[];if(n&&!e)return o.jsx(ar,{});if(t)return o.jsx(ur,{error:t});if(!i.length)return o.jsx(gp,{});const a=i.map(h=>{const y=(r||[]).filter(x=>x.site_id===h.site_id);return{site:h,cams:y,verdict:fp(h,y)}}),u=h=>a.filter(y=>y.verdict.tone===h).length,c=u("bad"),v=u("warn"),m=u("idle");return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Shops"}),o.jsxs("p",{className:"sub",children:[i.length," ",i.length===1?"shop":"shops",c>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[c," not working"]})]}),v>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"warn",children:[v," needing attention"]})]}),m>0&&o.jsxs(o.Fragment,{children:[" · ",m," not set up yet"]}),!c&&!v&&!m&&o.jsxs(o.Fragment,{children:[" · ",o.jsx("b",{className:"ok",children:"all working"})]})]})]}),o.jsx("div",{className:"grid sites",children:a.map(h=>o.jsx(hp,{site:h.site,cams:h.cams,verdict:h.verdict,onCheck:()=>s(h.site)},h.site.site_id))}),l&&o.jsx(op,{site:l,onClose:()=>s(null)})]})}function fp(e,t){const n=e.fraction_below_gate,r=e.cameras_total||t.length;return e.online?e.dropped>0?{tone:"bad",mark:"✕",words:`${e.dropped} visits lost and unrecoverable`}:r===0?{tone:"idle",mark:"+",headline:"Not set up",words:"No cameras set up yet"}:e.cameras_up===0?{tone:"bad",mark:"✕",words:"No cameras connected"}:e.cameras_up.5?{tone:"bad",mark:"✕",words:`${bs(n)} of faces too poor to recognise`}:n>.2?{tone:"warn",mark:"!",words:`${bs(n)} of faces too poor to recognise`}:e.queued>0?{tone:"warn",mark:"!",words:`${e.queued} visits waiting to upload`}:{tone:"ok",mark:"✓",words:`Working — ${r} ${r===1?"camera":"cameras"} connected`}:{tone:"bad",mark:"✕",headline:"Offline",words:`Offline — last heard from ${Ft(e.last_heartbeat_at)}`}}const pp={ok:"Working",warn:"Needs attention",bad:"Not working",idle:"Not set up"};function hp({site:e,cams:t,verdict:n,onCheck:r}){const l=e.fraction_below_gate,s=n.tone,i=n.headline||pp[s],a=mp(t),u=e.cameras_total||t.length;return o.jsxs("article",{className:"card site state-"+s,onClick:r,role:"button",tabIndex:0,onKeyDown:c=>c.key==="Enter"&&r(),children:[o.jsxs("div",{className:"shot",children:[a.url?o.jsx(Xi,{image:a,alt:`View inside ${e.name}`}):o.jsxs("div",{className:"noshot",children:[o.jsx(vp,{}),a.reason&&o.jsx("span",{children:a.reason})]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.name}),o.jsx("span",{children:u>0?`${u} ${u===1?"camera":"cameras"}`:"No cameras yet"})]}),o.jsxs("span",{className:"status "+s,children:[o.jsx("i",{"aria-hidden":"true"}),i]})]}),a.at&&o.jsx("span",{className:"shot-age",children:Ft(a.at)})]}),o.jsxs("div",{className:"metrics",children:[o.jsx(ss,{label:"Cameras",value:u?`${e.cameras_up}/${u}`:"—",tone:u?e.cameras_up0?bs(1-l):"—",tone:l?l>.5?"bad":l>.2?"warn":"ok":"idle"}),o.jsx(ss,{label:"Last seen",value:Ft(e.last_heartbeat_at),tone:e.online?"ok":"bad"})]}),o.jsxs("div",{className:"verdict "+n.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:n.mark}),o.jsx("span",{className:"words",children:n.words}),o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}function ss({label:e,value:t,tone:n}){return o.jsxs("div",{className:"metric",children:[o.jsx("b",{className:n,children:t}),o.jsx("span",{children:e})]})}function mp(e){var r;if(!e.length)return{};let t=null;for(const l of e)!((r=l.snapshot)!=null&&r.available)||!l.snapshot.url||(!t||(l.snapshot_at||"")>(t.snapshot_at||""))&&(t=l);return t?{...t.snapshot,at:t.snapshot_at}:{reason:e.map(l=>{var s;return(s=l.snapshot)==null?void 0:s.reason}).find(Boolean)||"No picture from this shop yet."}}function vp(){return o.jsxs("svg",{className:"shopmark",viewBox:"0 0 40 32","aria-hidden":"true",children:[o.jsx("path",{d:"M4 12h32v18H4z"}),o.jsx("path",{d:"M2 12l4-8h28l4 8"}),o.jsx("path",{d:"M15 30v-9h10v9"})]})}function bs(e){return`${Math.round(e*100)}%`}function Ft(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const n=Math.max(0,(Date.now()-t)/1e3);if(n<90)return"just now";const r=Math.round(n/60);if(r<60)return`${r} min ago`;const l=Math.round(r/60);return l<48?`${l} h ago`:`${Math.round(l/24)} days ago`}function yp(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const n=(t-Date.now())/1e3;if(n<=0)return"expired";const r=Math.round(n/60);if(r<60)return`in ${r} min`;const l=Math.round(r/60);return l<48?`in ${l} h`:`in ${Math.round(l/24)} days`}function ar(){return o.jsxs("div",{className:"state",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]})}function ur({error:e}){return o.jsx("div",{className:"state",children:o.jsx("p",{className:"error",role:"alert",children:e.message})})}function gp(){return o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No shops yet"}),o.jsx("p",{className:"sub",children:"A shop appears here once its PC has been claimed with an enrolment code."})]})}const ua=60;function wp(){const[e,t]=j.useState([]),[n,r]=j.useState("connecting"),[l,s]=j.useState(null),i=j.useRef(new Set);return j.useEffect(()=>{const a=new AbortController;let u=()=>{};return(async()=>{try{const c=await $.arrivals({limit:30}),v=c.arrivals||[];v.forEach(m=>i.current.add(m.visit_id)),t(v.slice().reverse()),r("live"),u=tp({cursor:c.cursor,signal:a.signal,onPage:m=>{const h=(m.arrivals||[]).filter(y=>!i.current.has(y.visit_id));h.length&&(h.forEach(y=>i.current.add(y.visit_id)),r("live"),t(y=>[...h.reverse(),...y].slice(0,ua)))},onError:()=>r("reconnecting")})}catch(c){s(c)}})(),()=>{a.abort(),u()}},[]),l?o.jsx(ur,{error:l}):n==="connecting"&&!e.length?o.jsx(ar,{}):o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Live"}),o.jsxs("p",{className:"sub",children:[o.jsx("span",{className:"dot "+(n==="live"?"ok":"warn"),"aria-hidden":"true"}),n==="live"?"Connected":"Reconnecting…"," · ","last ",ua," arrivals"]})]}),e.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"Nobody yet"}),o.jsx("p",{className:"sub",children:"Arrivals appear here the moment a camera recognises someone."})]}):o.jsx("ul",{className:"arrivals",children:e.map(a=>o.jsx(xp,{a},a.visit_id))})]})}function xp({a:e}){const t=e.name||e.label||"Unidentified";return o.jsxs("li",{className:"card arrival",children:[o.jsx(kp,{image:e.image,name:t}),o.jsxs("div",{className:"who-col",children:[o.jsx("strong",{children:t}),o.jsxs("span",{className:"sub",children:[e.site,e.camera_id?` · ${e.camera_id}`:""," · ",Ft(e.occurred_at)]}),e.attributes&&o.jsx(Sp,{attrs:e.attributes})]}),e.is_new_visitor?o.jsx("span",{className:"pill new",children:"New"}):o.jsx("span",{className:"pill",children:"Returning"})]})}function kp({image:e,name:t}){return e!=null&&e.available?o.jsx("span",{className:"face",children:o.jsx(Xi,{image:e,alt:""})}):o.jsx("span",{className:"face initials",title:(e==null?void 0:e.reason)||"","aria-hidden":"true",children:jp(t)})}function jp(e){const t=String(e).trim().split(/\s+/).filter(Boolean);return t.length?t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[t.length-1][0]).toUpperCase():"?"}function Sp({attrs:e}){const t=[];return e.gender&&t.push(e.gender),e.age&&t.push(`~${Math.round(e.age)}`),e.emotion&&t.push(e.emotion),t.length?o.jsx("span",{className:"attrs",children:t.join(" · ")}):null}function Np({camera:e,onClose:t}){const n=j.useRef(null),[r,l]=j.useState("waiting"),[s,i]=j.useState(!1);j.useEffect(()=>{const c=new AbortController,v=np({cameraId:e.id,img:n,onState:h=>{l(h),h==="live"&&i(!1)},signal:c.signal}),m=setTimeout(()=>i(!0),12e3);return()=>{v(),c.abort(),clearTimeout(m)}},[e.id]);const a=e.connected===!1?"This camera was not connecting when the shop PC last reported. Check it is powered on and reachable on the shop’s network.":e.connected==null?"The shop PC has not reported on this camera yet. It may still be starting up.":"The shop PC is not sending frames. It may be offline, or its Behavision app may not be running.",u=s&&r!=="live"?a:{waiting:"Asking the shop PC…",live:"Live",reconnecting:"Reconnecting…"}[r];return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer live",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:e.label}),o.jsx("p",{className:"sub",children:e.site})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[o.jsxs("div",{className:"liveshot",children:[o.jsx("img",{ref:n,alt:`Live view from ${e.label}`}),r!=="live"&&o.jsx("div",{className:"livewait",children:o.jsx("span",{children:s?"No picture yet":u})})]}),o.jsx("p",{className:"hint",style:{marginTop:10},children:r==="live"?"Live. The shop only uploads while this view is open.":u})]})]})})}const Br=[{id:"hikvision",label:"Hikvision",path:"/Streaming/Channels/101",note:"Channel 1, main stream. Use /Streaming/Channels/102 for the lower-quality sub stream."},{id:"dahua",label:"Dahua",path:"/cam/realmonitor?channel=1&subtype=0",note:"Channel 1, main stream. subtype=1 is the sub stream."},{id:"cpplus",label:"CP Plus",path:"/cam/realmonitor?channel=1&subtype=0",note:"CP Plus cameras use the Dahua stream path."},{id:"uniview",label:"Uniview",path:"/media/video1",note:"Some older Uniview models use /video1 instead."},{id:"tplink",label:"TP-Link / Tapo",path:"/stream1",note:"Tapo cameras need a separate camera account created in the Tapo app — your Tapo login will not work."},{id:"reolink",label:"Reolink",path:"/h264Preview_01_main",note:"Use /h264Preview_01_sub for the lower-quality stream."},{id:"amcrest",label:"Amcrest",path:"/cam/realmonitor?channel=1&subtype=0",note:"Amcrest cameras use the Dahua stream path."},{id:"axis",label:"Axis",path:"/axis-media/media.amp",note:""},{id:"onvif",label:"Other (ONVIF)",path:"/onvif1",note:"Many generic cameras answer here. If it does not work, look for “RTSP” in the camera’s own app."},{id:"manual",label:"I know the path",path:"",note:""}],ca=e=>Br.find(t=>t.id===e)||Br[Br.length-1],Cp=["Camera","Connection","Test","Walk past"];function Ep({sites:e,existing:t,onClose:n,onSaved:r}){var d;const l=!(t!=null&&t.id),[s,i]=j.useState(l?0:2),[a,u]=j.useState(t!=null&&t.id?t:null),[c,v]=j.useState({site_id:(t==null?void 0:t.site_id)||((d=e[0])==null?void 0:d.site_id)||"",make:"hikvision",label:(t==null?void 0:t.label)||"",host:(t==null?void 0:t.host)||"",port:(t==null?void 0:t.port)||554,path:(t==null?void 0:t.path)||"/Streaming/Channels/101",username:(t==null?void 0:t.username)||"",password:""}),[m,h]=j.useState(!1),[y,x]=j.useState(""),g=f=>w=>v(S=>({...S,[f]:w.target.value})),T=f=>{const w=ca(f.target.value);v(S=>({...S,make:w.id,path:w.path||S.path}))},p=async()=>{h(!0),x("");const f={};for(const[w,S]of Object.entries(c))w==="site_id"||w==="make"||S===""||S==null||(f[w]=w==="port"?Number(S):S);try{const w=a!=null&&a.id?await $.updateCamera(a.id,f):await $.createCamera(c.site_id,f);u(w),i(2),r==null||r(w,{keepOpen:!0})}catch(w){x(w.message)}finally{h(!1)}};return o.jsx("div",{className:"overlay",onClick:n,children:o.jsxs("aside",{className:"drawer wizard",onClick:f=>f.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:l?"Set up a camera":(a==null?void 0:a.label)||(t==null?void 0:t.label)}),o.jsx("p",{className:"sub",children:s<2?"The shop’s PC connects to the camera — nothing needs opening to the internet.":"Prove it works before you rely on it."})]}),o.jsx("button",{className:"ghost",onClick:n,children:"Close"})]}),o.jsx("ol",{className:"steps",children:Cp.map((f,w)=>o.jsxs("li",{className:w===s?"now":wo.jsx("option",{value:f.site_id,children:f.name},f.site_id))})]}),o.jsxs("label",{children:["What should staff call it?",o.jsx("input",{value:c.label,onChange:g("label"),placeholder:"Entrance",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Visits are recorded against this name, so it cannot be changed later."})]}),o.jsxs("label",{children:["Make of camera",o.jsx("select",{value:c.make,onChange:T,children:Br.map(f=>o.jsx("option",{value:f.id,children:f.label},f.id))}),o.jsx("span",{className:"hint",children:ca(c.make).note||"This only fills in the stream path for you. You can change it on the next step."})]}),o.jsx("button",{className:"primary",disabled:!c.label.trim(),onClick:()=>i(1),children:"Next"})]}),s===1&&o.jsxs("div",{className:"drawer-body",children:[o.jsxs("label",{children:["Camera’s address on the shop’s network",o.jsx("input",{value:c.host,onChange:g("host"),placeholder:"192.168.0.138",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Not a website address. It usually starts 192.168. — look in the camera’s own app, on its label, or in your router’s device list."})]}),o.jsxs("div",{className:"pair",children:[o.jsxs("label",{children:["Port",o.jsx("input",{type:"number",value:c.port,onChange:g("port")})]}),o.jsxs("label",{children:["Stream path",o.jsx("input",{value:c.path,onChange:g("path")})]})]}),o.jsxs("label",{children:["Camera username",o.jsx("input",{value:c.username,onChange:g("username"),placeholder:"admin",name:"camera-account",autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:"false"}),o.jsx("span",{className:"hint",children:"The camera’s own login, not your Behavision one."})]}),o.jsxs("label",{children:["Camera password",o.jsx("input",{type:"password",value:c.password,onChange:g("password"),name:"camera-secret",autoComplete:"new-password",placeholder:a!=null&&a.has_password?"(unchanged)":""})]}),y&&o.jsx("p",{className:"error",role:"alert",children:y}),o.jsxs("div",{className:"pair",children:[o.jsx("button",{className:"ghost",onClick:()=>i(0),children:"Back"}),o.jsx("button",{className:"primary",disabled:m||!c.host.trim(),onClick:p,children:m?"Saving…":"Save and test"})]})]}),s>=2&&a&&o.jsx(_p,{camera:a,step:s,onStep:i,onUpdated:f=>{u(f),r==null||r(f,{keepOpen:!0})},onEdit:()=>i(1),onDone:n})]})})}function _p({camera:e,step:t,onStep:n,onUpdated:r,onEdit:l,onDone:s}){const[i,a]=j.useState(e),[u,c]=j.useState(!1),[v,m]=j.useState(""),h=j.useRef(null);j.useEffect(()=>a(e),[e]);const y=i.check||{},x=y.state==="requested"||y.state==="running";j.useEffect(()=>{if(!x)return;let p=!0;const d=async()=>{try{const w=(await $.cameras()).find(S=>S.id===i.id);p&&w&&(a(w),r==null||r(w))}catch{}};return h.current=setInterval(d,4e3),()=>{p=!1,clearInterval(h.current)}},[x,i.id]);const g=async(p,d)=>{c(!0),m("");try{const f=await $.checkCamera(i.id,p,d);a(f),r==null||r(f),n(p==="placement"?3:2)}catch(f){m(f.message)}finally{c(!1)}},T=y.kind==="connection"&&y.state==="done"&&y.ok;return o.jsx(o.Fragment,{children:o.jsxs("div",{className:"drawer-body",children:[t===2?o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can the shop’s PC reach this camera?"}),o.jsx("p",{className:"sub",children:"The PC opens the stream once and takes a single picture. Nothing is recorded."})]}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can it actually recognise a face?"}),o.jsxs("p",{className:"sub",children:["Someone needs to ",o.jsx("b",{children:"walk through the camera’s view and out of it"}),", the way a customer would. Standing still measures nothing — the check scores the best view of each person as they leave the frame, which is what recognition really uses."]})]}),x&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("b",{children:y.state==="running"?"Running on the shop’s PC…":"Waiting for the shop’s PC…"}),o.jsx("span",{className:"sub",children:y.state==="running"?"This takes about "+(y.seconds||25)+" seconds.":"It picks up the request within a couple of minutes."})]})]}),y.state==="done"&&o.jsx(Pp,{check:y}),v&&o.jsx("p",{className:"error",role:"alert",children:v}),o.jsx("div",{className:"pair",children:t===2?o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:l,children:"Change details"}),o.jsx("button",{className:"primary",disabled:u||x,onClick:()=>g("connection"),children:y.state==="done"?"Test again":"Test connection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:()=>n(2),children:"Back"}),o.jsx("button",{className:"primary",disabled:u||x,onClick:()=>g("placement",25),children:y.state==="done"?"Check again":"Start walk-past check"})]})}),t===2&&T&&!x&&o.jsx("button",{className:"primary",onClick:()=>n(3),children:"Next: prove it can recognise faces"}),t===3&&y.state==="done"&&!x&&o.jsx("button",{className:"ghost",onClick:s,children:"Finish"})]})})}function Pp({check:e}){var n,r,l;const t=e.ok?"ok":e.verdict==="marginal"?"warn":"bad";return o.jsxs("div",{className:"outcome "+t,children:[o.jsxs("div",{className:"outcome-head",children:[o.jsx("span",{className:"pill "+t,children:e.ok?"Working":"Not ready"}),o.jsx("b",{children:e.headline||(e.ok?"Working":"Could not be verified")})]}),((n=e.image)==null?void 0:n.available)&&o.jsx("img",{className:"proof",src:e.image.url,alt:"The view from this camera",loading:"lazy"}),((r=e.advice)==null?void 0:r.length)>0&&o.jsx("ul",{className:"advice",children:e.advice.map((s,i)=>o.jsx("li",{children:s},i))}),((l=e.detail)==null?void 0:l.faces)!=null&&o.jsxs("p",{className:"sub",children:[e.detail.faces," ",e.detail.faces===1?"person":"people"," walked past during the check."]})]})}function Tp(e){const t=e.check||{};return t.state==="requested"||t.state==="running"?{tone:"idle",mark:"…",words:"Checking now"}:t.state!=="done"?{tone:"idle",mark:"?",words:"Not checked yet"}:t.kind==="placement"?t.ok?{tone:"ok",mark:"✓",words:"Recognises faces here"}:{tone:"bad",mark:"✕",words:t.headline||"Cannot recognise faces here"}:t.ok?{tone:"warn",mark:"!",words:"Stream works — faces not checked yet"}:{tone:"bad",mark:"✕",words:t.headline||"Could not reach the camera"}}function zp({user:e}){const{data:t,error:n,loading:r,reload:l}=It(()=>$.cameras(),2e4,[]),{data:s}=It(()=>$.sites(),0,[]),[i,a]=j.useState(null),[u,c]=j.useState(null),v=["admin","owner","manager"].includes(e.role),m=t||[],h=m.filter(g=>g.connected).length,y=m.filter(g=>g.connected===!1).length,x=m.filter(g=>g.connected==null).length;return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Cameras"}),o.jsxs("p",{className:"sub",children:[m.length," ",m.length===1?"camera":"cameras",h>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"ok",children:[h," connected"]})]}),y>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[y," down"]})]}),x>0&&o.jsxs(o.Fragment,{children:[" · ",x," waiting for the shop PC"]})]}),v&&o.jsx("button",{className:"primary",onClick:()=>a({}),children:"Set up a camera"})]}),r&&!t?o.jsx(ar,{}):n?o.jsx(ur,{error:n}):m.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No cameras yet"}),o.jsx("p",{className:"sub",children:"Add one here and the shop’s PC will pick it up within a couple of minutes. Cameras already set up on a shop PC appear here on their own."})]}):o.jsx("div",{className:"grid cams",children:m.map(g=>o.jsx(Lp,{cam:g,canEdit:v,onEdit:()=>a(g),onWatch:()=>c(g)},g.id))}),i&&o.jsx(Ep,{existing:i.id?i:null,sites:s||[],onClose:()=>{a(null),l()},onSaved:(g,T)=>{T!=null&&T.keepOpen||a(null),l()}}),u&&o.jsx(Np,{camera:u,onClose:()=>c(null)})]})}function Lp({cam:e,canEdit:t,onEdit:n,onWatch:r}){var a,u;const l=e.connected==null?"idle":e.connected?"ok":"bad",s=e.connected==null?"Waiting for the shop PC":e.connected?"Connected":"Not connecting",i=Tp(e);return o.jsxs("article",{className:"card cam state-"+l,onClick:t?n:void 0,role:t?"button":void 0,tabIndex:t?0:void 0,onKeyDown:c=>t&&c.key==="Enter"&&n(),children:[o.jsxs("div",{className:"shot",children:[(a=e.snapshot)!=null&&a.available?o.jsx(Xi,{image:e.snapshot,alt:`View from ${e.label}`}):o.jsxs("div",{className:"noshot",children:[o.jsx("span",{className:"lens","aria-hidden":"true"}),((u=e.snapshot)==null?void 0:u.reason)||"No picture yet."]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.label||e.camera_id}),o.jsx("span",{children:e.site})]}),o.jsxs("span",{className:"status "+l,children:[o.jsx("i",{"aria-hidden":"true"}),s]})]}),e.snapshot_at&&o.jsx("span",{className:"shot-age",children:Ft(e.snapshot_at)}),o.jsxs("button",{className:"watch",title:"Watch this camera now",onClick:c=>{c.stopPropagation(),r()},children:[o.jsx("i",{"aria-hidden":"true"}),"Live"]})]}),o.jsxs("div",{className:"verdict "+i.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:i.mark}),o.jsx("span",{className:"words",children:i.words}),t&&o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}const Rp=["Is everything working today?","Why is footfall low at Chennai?","How many people came in last week?","Which cameras still need checking?"];function Op({open:e,onClose:t}){const[n,r]=j.useState([]),[l,s]=j.useState(""),[i,a]=j.useState(!1),[u,c]=j.useState(!1),v=j.useRef(null),m=j.useRef(null);j.useEffect(()=>{var y;e&&((y=m.current)==null||y.focus())},[e]),j.useEffect(()=>{var y;(y=v.current)==null||y.scrollIntoView({behavior:"smooth",block:"end"})},[n,i]);const h=async y=>{const x=(y??l).trim();if(!x||i)return;const g=[...n,{role:"user",text:x}];r(g),s(""),a(!0);try{const T=await $.ask(g);r(p=>[...p,{role:"assistant",text:T.text,used:T.used}])}catch(T){T.code==="assistant_off"?c(!0):r(p=>[...p,{role:"assistant",text:T.message,failed:!0}])}finally{a(!1)}};return e?o.jsxs("aside",{className:"assistant",role:"complementary","aria-label":"Assistant",children:[o.jsxs("header",{className:"assistant-head",children:[o.jsxs("div",{children:[o.jsx("b",{children:"Ask Behavision"}),o.jsx("span",{className:"sub",children:"It reads your shops’ own data to answer."})]}),o.jsx("button",{className:"ghost",onClick:t,"aria-label":"Close assistant",children:"✕"})]}),o.jsxs("div",{className:"assistant-body",children:[u?o.jsx("p",{className:"sub pad",children:"The assistant is not switched on for this server."}):n.length===0?o.jsxs("div",{className:"suggest",children:[o.jsx("p",{className:"sub",children:"Try asking:"}),Rp.map(y=>o.jsx("button",{className:"chip",onClick:()=>h(y),children:y},y))]}):n.map((y,x)=>{var g;return o.jsxs("div",{className:"bubble "+y.role+(y.failed?" failed":""),children:[y.text,((g=y.used)==null?void 0:g.length)>0&&o.jsxs("span",{className:"used",children:["looked at: ",y.used.map(Ip).join(", ")]})]},x)}),i&&o.jsxs("div",{className:"bubble assistant-thinking",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"})," Looking…"]}),o.jsx("div",{ref:v})]}),!u&&o.jsxs("form",{className:"assistant-ask",onSubmit:y=>{y.preventDefault(),h()},children:[o.jsx("input",{ref:m,value:l,onChange:y=>s(y.target.value),placeholder:"Ask about your shops…",disabled:i}),o.jsx("button",{className:"primary",disabled:i||!l.trim(),children:"Ask"})]})]}):null}function Ip(e){return{list_shops:"your shops",check_shop:"a shop check",list_cameras:"your cameras",check_camera:"a camera check",footfall:"footfall",sales:"sales",find_customer:"customer records"}[e]||e}function Fp(){const{data:e,error:t,loading:n,reload:r}=It(()=>$.clients(),0,[]),[l,s]=j.useState(!1),[i,a]=j.useState(null),u=e||[];return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Companies"}),o.jsx("button",{className:"primary",onClick:()=>{a(null),s(!0)},children:"New company"})]}),i&&o.jsx(Mp,{result:i,onDismiss:()=>a(null)}),n&&!e?o.jsx(ar,{}):t?o.jsx(ur,{error:t}):u.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No companies yet"}),o.jsx("p",{className:"sub",children:"Create one, and its owner can sign in straight away."})]}):o.jsx("div",{className:"tablewrap",children:o.jsxs("table",{className:"rows",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Company"}),o.jsx("th",{children:"Short name"}),o.jsx("th",{children:"Sites"}),o.jsx("th",{children:"People"}),o.jsx("th",{children:"Created"})]})}),o.jsx("tbody",{children:u.map(c=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("strong",{children:c.name})}),o.jsx("td",{children:o.jsx("code",{children:c.slug})}),o.jsx("td",{className:"num",children:c.sites}),o.jsx("td",{className:"num",children:c.users}),o.jsx("td",{className:"sub",children:Ft(c.created_at)})]},c.id))})]})}),l&&o.jsx(Dp,{onClose:()=>s(!1),onCreated:c=>{s(!1),a(c),r()}})]})}function Dp({onClose:e,onCreated:t}){const[n,r]=j.useState({company_name:"",owner_name:"",owner_email:"",password:""}),[l,s]=j.useState(!1),[i,a]=j.useState(""),u=v=>m=>r({...n,[v]:m.target.value}),c=async v=>{v.preventDefault(),s(!0),a("");try{t(await $.createClient(n))}catch(m){a(m.message),s(!1)}};return o.jsx("div",{className:"overlay",onClick:e,children:o.jsxs("aside",{className:"drawer narrow",onClick:v=>v.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsx("h2",{children:"New company"}),o.jsx("button",{className:"ghost",onClick:e,children:"Close"})]}),o.jsxs("form",{className:"drawer-body",onSubmit:c,children:[o.jsxs("label",{children:["Company name",o.jsx("input",{value:n.company_name,onChange:u("company_name"),required:!0,autoFocus:!0})]}),o.jsxs("label",{children:["Owner’s name",o.jsx("input",{value:n.owner_name,onChange:u("owner_name")})]}),o.jsxs("label",{children:["Owner’s email",o.jsx("input",{type:"email",value:n.owner_email,onChange:u("owner_email"),required:!0})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"text",value:n.password,onChange:u("password"),placeholder:"Leave empty to generate one"}),o.jsx("span",{className:"hint",children:"Generated is better — a password you invent for someone else ends up weak and sent over chat."})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"primary",disabled:l,children:l?"Creating…":"Create company"})]})]})})}function Mp({result:e,onDismiss:t}){return o.jsxs("div",{className:"banner ok credentials",children:[o.jsxs("div",{children:[o.jsxs("b",{children:[e.slug," created."]})," These sign-in details are shown once and cannot be recovered. Send them to the owner now.",o.jsxs("dl",{className:"creds",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Email"}),o.jsx("dd",{children:o.jsx("code",{children:e.owner_email})})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Password"}),o.jsx("dd",{children:o.jsx("code",{children:e.password})})]})]})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Done"})]})}function $p({user:e}){const t=It(()=>$.team(),0,[]),n=It(()=>$.invitations(),0,[]),[r,l]=j.useState(!1),[s,i]=j.useState(null),[a,u]=j.useState(""),[c,v]=j.useState(""),m=e.role==="owner"||e.role==="manager",h=t.data||[],y=n.data||[],x=async(g,T)=>{u(g),v("");try{await $.updateMember(g,T),t.reload()}catch(p){v(p.message)}finally{u("")}};return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Team"}),m&&o.jsx("button",{className:"primary",onClick:()=>{i(null),l(!0)},children:"Invite someone"})]}),s&&o.jsx(Ap,{invite:s,onDismiss:()=>i(null)}),c&&o.jsx("p",{className:"error",role:"alert",children:c}),t.loading&&!t.data?o.jsx(ar,{}):t.error?o.jsx(ur,{error:t.error}):o.jsx("div",{className:"tablewrap",children:o.jsxs("table",{className:"rows",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Name"}),o.jsx("th",{children:"Email"}),o.jsx("th",{children:"Role"}),o.jsx("th",{children:"Last signed in"}),m&&o.jsx("th",{})]})}),o.jsx("tbody",{children:h.map(g=>o.jsxs("tr",{className:g.active?"":"inactive",children:[o.jsxs("td",{children:[o.jsx("strong",{children:g.full_name||"—"}),!g.active&&o.jsx("span",{className:"pill muted",children:"No access"})]}),o.jsx("td",{children:o.jsx("code",{children:g.email})}),o.jsx("td",{children:m&&g.id!==e.id?o.jsxs("select",{value:g.role,disabled:a===g.id,onChange:T=>x(g.id,{role:T.target.value}),children:[o.jsx("option",{value:"staff",children:"Staff"}),o.jsx("option",{value:"manager",children:"Manager"}),e.role==="owner"&&o.jsx("option",{value:"owner",children:"Owner"})]}):o.jsx("span",{className:"role",children:g.role})}),o.jsx("td",{className:"sub",children:g.last_login_at?Ft(g.last_login_at):"Never"}),m&&o.jsx("td",{className:"right",children:g.id===e.id?null:g.active?o.jsx("button",{className:"ghost danger",disabled:a===g.id,onClick:()=>x(g.id,{active:!1}),children:"Remove access"}):o.jsx("button",{className:"ghost",disabled:a===g.id,onClick:()=>x(g.id,{active:!0}),children:"Restore"})})]},g.id))})]})}),m&&y.length>0&&o.jsxs("section",{className:"pending",children:[o.jsx("h2",{children:"Waiting to join"}),o.jsx("ul",{className:"invites",children:y.map(g=>o.jsxs("li",{className:"card invite",children:[o.jsxs("div",{children:[o.jsx("strong",{children:g.email}),o.jsxs("span",{className:"sub",children:["invited as ",g.role,g.invited_by?` by ${g.invited_by}`:""," · expires ",yp(g.expires_at)]})]}),o.jsx("button",{className:"ghost danger",onClick:async()=>{await $.revokeInvitation(g.id),n.reload()},children:"Withdraw"})]},g.id))})]}),r&&o.jsx(Up,{canMintOwner:e.role==="owner",onClose:()=>l(!1),onDone:g=>{l(!1),i(g),n.reload()}})]})}function Up({canMintOwner:e,onClose:t,onDone:n}){const[r,l]=j.useState({email:"",full_name:"",role:"staff"}),[s,i]=j.useState(!1),[a,u]=j.useState(""),c=m=>h=>l({...r,[m]:h.target.value}),v=async m=>{m.preventDefault(),i(!0),u("");try{n(await $.invite(r))}catch(h){u(h.message),i(!1)}};return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer narrow",onClick:m=>m.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsx("h2",{children:"Invite someone"}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("form",{className:"drawer-body",onSubmit:v,children:[o.jsxs("label",{children:["Their email",o.jsx("input",{type:"email",value:r.email,onChange:c("email"),required:!0,autoFocus:!0,autoComplete:"off",name:"invitee"}),o.jsx("span",{className:"hint",children:"This is the address they will sign in with, and it is fixed by the invitation — passing the code on cannot make it somebody else’s account."})]}),o.jsxs("label",{children:["Their name",o.jsx("input",{value:r.full_name,onChange:c("full_name"),autoComplete:"off",name:"invitee-name"})]}),o.jsxs("label",{children:["Role",o.jsxs("select",{value:r.role,onChange:c("role"),children:[o.jsx("option",{value:"staff",children:"Staff — see customers and shops"}),o.jsx("option",{value:"manager",children:"Manager — also set up cameras and invite people"}),e&&o.jsx("option",{value:"owner",children:"Owner — full control"})]})]}),a&&o.jsx("p",{className:"error",role:"alert",children:a}),o.jsx("button",{className:"primary",disabled:s,children:s?"Creating…":"Create invitation"})]})]})})}function Ap({invite:e,onDismiss:t}){return o.jsxs("div",{className:"banner ok credentials",children:[o.jsxs("div",{children:[o.jsxs("b",{children:["Invitation for ",e.email,"."]})," Give them this code. It is shown once, works once, and cannot be recovered.",o.jsxs("dl",{className:"creds",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Code"}),o.jsx("dd",{children:o.jsx("code",{className:"big",children:e.code})})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Role"}),o.jsx("dd",{children:e.role})]})]}),o.jsx("p",{className:"sub",children:"They open the app, choose “I have an invitation code”, and pick their own password. Nobody else ever sees it."})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Done"})]})}const Bp=[{id:"sites",label:"Shops",View:dp},{id:"live",label:"Live",View:wp},{id:"cameras",label:"Cameras",View:zp},{id:"team",label:"Team",View:$p}],Vp=[{id:"clients",label:"Companies",View:Fp}];function Wp(){const[e,t]=j.useState(null),[n,r]=j.useState(!0),[l,s]=j.useState("sites"),[i,a]=j.useState(!1);if(j.useEffect(()=>{(async()=>{if(ep())try{t(await $.me())}catch{or()}r(!1)})()},[]),n)return o.jsxs("div",{className:"boot",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]});if(!e)return o.jsx(rp,{onSignedIn:t});const u=e.role==="admin"&&!e.client_id,c=u?Vp:Bp,v=c.find(y=>y.id===l)||c[0],m=v.View,h=async()=>{await $.logout(),t(null)};return o.jsxs("div",{className:"app",children:[o.jsxs("header",{className:"topbar",children:[o.jsxs("div",{className:"brand",children:[o.jsx("span",{className:"mark","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("strong",{children:"Behavision"}),o.jsx("span",{className:"org",children:e.client_name||"Loyaly platform"})]})]}),o.jsx("nav",{className:"tabs",children:c.map(y=>o.jsx("button",{onClick:()=>s(y.id),"aria-current":v.id===y.id?"page":void 0,children:y.label},y.id))}),o.jsxs("div",{className:"who",children:[o.jsxs("button",{className:"ask-btn"+(i?" on":""),onClick:()=>a(y=>!y),children:[o.jsx("span",{"aria-hidden":"true",children:"✳"})," Ask"]}),o.jsx("span",{className:"name",children:e.full_name||e.email}),o.jsx("span",{className:"role",children:u?"platform admin":e.role}),o.jsx("button",{className:"ghost",onClick:h,children:"Sign out"})]})]}),o.jsxs("div",{className:"with-assistant"+(i?" open":""),children:[o.jsx("main",{className:"page",children:o.jsx(m,{user:e})}),o.jsx(Op,{open:i,onClose:()=>a(!1)})]})]})}Sc(document.getElementById("root")).render(o.jsx(Wp,{})); +`))p.startsWith("event: ")?g=p.slice(7).trim():p.startsWith("data: ")&&(T=p.slice(6));g==="frame"&&T?(t.current&&(t.current.src="data:image/jpeg;base64,"+T),n==null||n("live")):g==="waiting"&&(n==null||n("waiting"))}}}catch{if(l||r!=null&&r.aborted)return;n==null||n("reconnecting")}if(l)return;await new Promise(i=>setTimeout(i,1500))}})(),()=>{l=!0}}function rp({onSignedIn:e}){const[t,n]=j.useState(!1);return t?o.jsx(sp,{onSignedIn:e,onCancel:()=>n(!1)}):o.jsx(lp,{onSignedIn:e,onJoin:()=>n(!0)})}function lp({onSignedIn:e,onJoin:t}){const[n,r]=j.useState(""),[l,s]=j.useState(""),[i,a]=j.useState(""),[u,c]=j.useState(!1),v=async m=>{m.preventDefault(),c(!0),a("");try{await $.login(n.trim(),l),e(await $.me())}catch(h){a(h.message),c(!1)}};return o.jsx("div",{className:"signin",children:o.jsxs("form",{className:"card",onSubmit:v,children:[o.jsx("span",{className:"mark big","aria-hidden":"true"}),o.jsx("h1",{children:"Behavision"}),o.jsx("p",{className:"sub",children:"Sign in to your company account."}),o.jsxs("label",{children:["Email",o.jsx("input",{type:"email",value:n,autoComplete:"username",autoFocus:!0,required:!0,onChange:m=>r(m.target.value),placeholder:"you@company.com"})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"password",value:l,autoComplete:"current-password",required:!0,onChange:m=>s(m.target.value)})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"primary",disabled:u||!n||!l,children:u?"Signing in…":"Sign in"}),o.jsxs("p",{className:"foot",children:["Been invited? ",o.jsx("button",{type:"button",className:"linkish",onClick:t,children:"Use your invitation code"})]})]})})}function sp({onSignedIn:e,onCancel:t}){const[n,r]=j.useState(""),[l,s]=j.useState(null),[i,a]=j.useState(""),[u,c]=j.useState(""),[v,m]=j.useState(""),[h,y]=j.useState(""),[x,g]=j.useState(!1),T=async d=>{d.preventDefault(),g(!0),y("");try{const f=await $.previewInvitation(n.trim());s(f),a(f.full_name||"")}catch(f){y(f.message)}finally{g(!1)}},p=async d=>{if(d.preventDefault(),u!==v){y("Those two passwords are not the same.");return}g(!0),y("");try{const f=await $.register({code:n.trim(),full_name:i,password:u});e(f)}catch(f){y(f.message),g(!1)}};return o.jsx("div",{className:"signin",children:o.jsxs("form",{className:"card",onSubmit:l?p:T,children:[o.jsx("span",{className:"mark big","aria-hidden":"true"}),o.jsx("h1",{children:l?`Join ${l.client_name}`:"Behavision"}),l?o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"sub",children:["You are joining as ",o.jsx("b",{children:l.role}),", signing in with"," ",o.jsx("code",{children:l.email}),". Choose a password only you know."]}),o.jsxs("label",{children:["Your name",o.jsx("input",{value:i,onChange:d=>a(d.target.value),autoFocus:!0,autoComplete:"name"})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"password",value:u,required:!0,minLength:8,autoComplete:"new-password",onChange:d=>c(d.target.value)}),o.jsx("span",{className:"hint",children:"At least 8 characters. Longer is the only thing that helps."})]}),o.jsxs("label",{children:["Password again",o.jsx("input",{type:"password",value:v,required:!0,autoComplete:"new-password",onChange:d=>m(d.target.value)})]}),h&&o.jsx("p",{className:"error",role:"alert",children:h}),o.jsx("button",{className:"primary",disabled:x||!u||!v,children:x?"Creating your account…":"Create account and sign in"})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Enter the invitation code you were given."}),o.jsxs("label",{children:["Invitation code",o.jsx("input",{value:n,onChange:d=>r(d.target.value),autoFocus:!0,required:!0,autoComplete:"off",spellCheck:"false",placeholder:"ABCDEF-123456-GHIJKL-789012",className:"codefield"}),o.jsx("span",{className:"hint",children:"Dashes and capitals do not matter."})]}),h&&o.jsx("p",{className:"error",role:"alert",children:h}),o.jsx("button",{className:"primary",disabled:x||!n.trim(),children:x?"Checking…":"Continue"})]}),o.jsx("p",{className:"foot",children:o.jsx("button",{type:"button",className:"linkish",onClick:t,children:"Back to sign in"})})]})})}function It(e,t,n=[]){const[r,l]=j.useState(null),[s,i]=j.useState(null),[a,u]=j.useState(!0),c=j.useRef(!1),v=j.useRef(!0),m=j.useCallback(async()=>{if(!c.current){c.current=!0;try{const h=await e();if(!v.current)return;l(h),i(null)}catch(h){if(!v.current)return;i(h)}finally{c.current=!1,v.current&&u(!1)}}},n);return j.useEffect(()=>{if(v.current=!0,m(),!t)return()=>{v.current=!1};const h=setInterval(m,t);return()=>{v.current=!1,clearInterval(h)}},[m,t]),{data:r,error:s,loading:a,reload:m}}function ip(e){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!e){n(null);return}let r=!0,l=null;return $.cameraSnapshot(e).then(s=>{if(!r){URL.revokeObjectURL(s);return}l=s,n(s)}).catch(()=>{r&&n(null)}),()=>{r=!1,l&&URL.revokeObjectURL(l)}},[e]),t}function Xi({image:e,url:t,alt:n}){const r=e?e.url:t,l=e&&!!e.auth||typeof r=="string"&&r.startsWith("/"),s=ip(l?r:null),i=l?s:r;return i?o.jsx("img",{src:i,alt:n,loading:"lazy"}):null}function op({site:e,onClose:t}){const[n,r]=j.useState(null),[l,s]=j.useState(!1),[i,a]=j.useState(""),u=async()=>{s(!0),a(""),r(null);try{r(await $.siteCheck(e.site_id))}catch(c){a(c.message)}finally{s(!1)}};return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsxs("h2",{children:["Is ",e.name," working?"]}),o.jsx("p",{className:"sub",children:"Checks the whole chain, from the shop’s PC to head office."})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[!n&&!l&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Nothing is changed and no one is disturbed — this reads what the shop has already reported."}),o.jsx("button",{className:"primary",onClick:u,children:"Run the check"})]}),l&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsx("b",{children:"Checking…"})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"banner "+(n.ok?"ok":"warn"),children:o.jsxs("div",{children:[o.jsx("b",{children:n.ok?"This shop is working.":"This shop needs attention."}),!n.ok&&o.jsx(o.Fragment,{children:" Work down the list — the first failure usually explains the rest."})]})}),o.jsx("ol",{className:"checklist",children:n.steps.map(c=>o.jsxs("li",{className:c.status,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:c.status==="pass"?"✓":c.status==="fail"?"✕":c.status==="warn"?"!":"–"}),o.jsxs("div",{children:[o.jsx("b",{children:c.name}),o.jsx("span",{className:"sub",children:c.detail}),c.advice&&o.jsx("span",{className:"advice-line",children:c.advice})]})]},c.name))}),o.jsx("button",{className:"ghost",onClick:u,children:"Check again"})]}),o.jsx(ap,{site:e})]})]})})}function ap({site:e}){const[t,n]=j.useState(null),[r,l]=j.useState(!1),[s,i]=j.useState(""),[a,u]=j.useState(""),c=async()=>{l(!0),i("");try{n(await $.enrolmentCode(e.site_id,{label:a.trim()}))}catch(v){i(v.message)}finally{l(!1)}};return o.jsxs("section",{className:"claim",children:[o.jsx("h3",{children:"Set up a shop PC"}),t?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"code","aria-live":"polite",children:t.code}),o.jsxs("p",{className:"sub",children:["Copy this now — it cannot be shown again. It works once, and stops working ",cp(t.expires_at),"."]}),o.jsxs("div",{className:"row",children:[o.jsx("button",{className:"ghost",onClick:()=>up(t.code),children:"Copy"}),o.jsx("button",{className:"ghost",onClick:()=>n(null),children:"Done"})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"sub",children:"Creates a one-time code to type into Behavision on the shop’s computer. Use one for a new shop, a replacement PC, or a reinstall."}),o.jsxs("label",{className:"field",children:[o.jsx("span",{children:"What is this PC? (optional)"}),o.jsx("input",{value:a,placeholder:"counter PC",onChange:v=>u(v.target.value)})]}),s&&o.jsx("p",{className:"error",role:"alert",children:s}),o.jsx("button",{className:"ghost",onClick:c,disabled:r,children:r?"Creating…":"Create an installation code"})]})]})}function up(e){var t;try{(t=navigator.clipboard)==null||t.writeText(e)}catch{}}function cp(e){const t=new Date(e).getTime();if(Number.isNaN(t))return"shortly";const n=Math.round((t-Date.now())/864e5);return n<=0?"today":n===1?"tomorrow":`in ${n} days`}function dp(){const{data:e,error:t,loading:n}=It(()=>$.sites(),2e4,[]),{data:r}=It(()=>$.cameras(),6e4,[]),[l,s]=j.useState(null),i=e||[];if(n&&!e)return o.jsx(ar,{});if(t)return o.jsx(ur,{error:t});if(!i.length)return o.jsx(gp,{});const a=i.map(h=>{const y=(r||[]).filter(x=>x.site_id===h.site_id);return{site:h,cams:y,verdict:fp(h,y)}}),u=h=>a.filter(y=>y.verdict.tone===h).length,c=u("bad"),v=u("warn"),m=u("idle");return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Shops"}),o.jsxs("p",{className:"sub",children:[i.length," ",i.length===1?"shop":"shops",c>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[c," not working"]})]}),v>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"warn",children:[v," needing attention"]})]}),m>0&&o.jsxs(o.Fragment,{children:[" · ",m," not set up yet"]}),!c&&!v&&!m&&o.jsxs(o.Fragment,{children:[" · ",o.jsx("b",{className:"ok",children:"all working"})]})]})]}),o.jsx("div",{className:"grid sites",children:a.map(h=>o.jsx(hp,{site:h.site,cams:h.cams,verdict:h.verdict,onCheck:()=>s(h.site)},h.site.site_id))}),l&&o.jsx(op,{site:l,onClose:()=>s(null)})]})}function fp(e,t){const n=e.fraction_below_gate,r=e.cameras_total||t.length;return e.online?e.dropped>0?{tone:"bad",mark:"✕",words:`${e.dropped} visits lost and unrecoverable`}:r===0?{tone:"idle",mark:"+",headline:"Not set up",words:"No cameras set up yet"}:e.cameras_up===0?{tone:"bad",mark:"✕",words:"No cameras connected"}:e.cameras_up.5?{tone:"bad",mark:"✕",words:`${bs(n)} of faces too poor to recognise`}:n>.2?{tone:"warn",mark:"!",words:`${bs(n)} of faces too poor to recognise`}:e.queued>0?{tone:"warn",mark:"!",words:`${e.queued} visits waiting to upload`}:{tone:"ok",mark:"✓",words:`Working — ${r} ${r===1?"camera":"cameras"} connected`}:{tone:"bad",mark:"✕",headline:"Offline",words:`Offline — last heard from ${Ft(e.last_heartbeat_at)}`}}const pp={ok:"Working",warn:"Needs attention",bad:"Not working",idle:"Not set up"};function hp({site:e,cams:t,verdict:n,onCheck:r}){const l=e.fraction_below_gate,s=n.tone,i=n.headline||pp[s],a=mp(t),u=e.cameras_total||t.length;return o.jsxs("article",{className:"card site state-"+s,onClick:r,role:"button",tabIndex:0,onKeyDown:c=>c.key==="Enter"&&r(),children:[o.jsxs("div",{className:"shot",children:[a.url?o.jsx(Xi,{image:a,alt:`View inside ${e.name}`}):o.jsxs("div",{className:"noshot",children:[o.jsx(vp,{}),a.reason&&o.jsx("span",{children:a.reason})]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.name}),o.jsx("span",{children:u>0?`${u} ${u===1?"camera":"cameras"}`:"No cameras yet"})]}),o.jsxs("span",{className:"status "+s,children:[o.jsx("i",{"aria-hidden":"true"}),i]})]}),a.at&&o.jsx("span",{className:"shot-age",children:Ft(a.at)})]}),o.jsxs("div",{className:"metrics",children:[o.jsx(ss,{label:"Cameras",value:u?`${e.cameras_up}/${u}`:"—",tone:u?e.cameras_up0?bs(1-l):"—",tone:l?l>.5?"bad":l>.2?"warn":"ok":"idle"}),o.jsx(ss,{label:"Last seen",value:Ft(e.last_heartbeat_at),tone:e.online?"ok":"bad"})]}),o.jsxs("div",{className:"verdict "+n.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:n.mark}),o.jsx("span",{className:"words",children:n.words}),o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}function ss({label:e,value:t,tone:n}){return o.jsxs("div",{className:"metric",children:[o.jsx("b",{className:n,children:t}),o.jsx("span",{children:e})]})}function mp(e){var r;if(!e.length)return{};let t=null;for(const l of e)!((r=l.snapshot)!=null&&r.available)||!l.snapshot.url||(!t||(l.snapshot_at||"")>(t.snapshot_at||""))&&(t=l);return t?{...t.snapshot,at:t.snapshot_at}:{reason:e.map(l=>{var s;return(s=l.snapshot)==null?void 0:s.reason}).find(Boolean)||"No picture from this shop yet."}}function vp(){return o.jsxs("svg",{className:"shopmark",viewBox:"0 0 40 32","aria-hidden":"true",children:[o.jsx("path",{d:"M4 12h32v18H4z"}),o.jsx("path",{d:"M2 12l4-8h28l4 8"}),o.jsx("path",{d:"M15 30v-9h10v9"})]})}function bs(e){return`${Math.round(e*100)}%`}function Ft(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const n=Math.max(0,(Date.now()-t)/1e3);if(n<90)return"just now";const r=Math.round(n/60);if(r<60)return`${r} min ago`;const l=Math.round(r/60);return l<48?`${l} h ago`:`${Math.round(l/24)} days ago`}function yp(e){if(!e)return"never";const t=new Date(e).getTime();if(Number.isNaN(t))return"—";const n=(t-Date.now())/1e3;if(n<=0)return"expired";const r=Math.round(n/60);if(r<60)return`in ${r} min`;const l=Math.round(r/60);return l<48?`in ${l} h`:`in ${Math.round(l/24)} days`}function ar(){return o.jsxs("div",{className:"state",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]})}function ur({error:e}){return o.jsx("div",{className:"state",children:o.jsx("p",{className:"error",role:"alert",children:e.message})})}function gp(){return o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No shops yet"}),o.jsx("p",{className:"sub",children:"A shop appears here once its PC has been claimed with an enrolment code."})]})}const ua=60;function wp(){const[e,t]=j.useState([]),[n,r]=j.useState("connecting"),[l,s]=j.useState(null),i=j.useRef(new Set);return j.useEffect(()=>{const a=new AbortController;let u=()=>{};return(async()=>{try{const c=await $.arrivals({limit:30}),v=c.arrivals||[];v.forEach(m=>i.current.add(m.visit_id)),t(v.slice().reverse()),r("live"),u=tp({cursor:c.cursor,signal:a.signal,onPage:m=>{const h=(m.arrivals||[]).filter(y=>!i.current.has(y.visit_id));h.length&&(h.forEach(y=>i.current.add(y.visit_id)),r("live"),t(y=>[...h.reverse(),...y].slice(0,ua)))},onError:()=>r("reconnecting")})}catch(c){s(c)}})(),()=>{a.abort(),u()}},[]),l?o.jsx(ur,{error:l}):n==="connecting"&&!e.length?o.jsx(ar,{}):o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Live"}),o.jsxs("p",{className:"sub",children:[o.jsx("span",{className:"dot "+(n==="live"?"ok":"warn"),"aria-hidden":"true"}),n==="live"?"Connected":"Reconnecting…"," · ","last ",ua," arrivals"]})]}),e.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"Nobody yet"}),o.jsx("p",{className:"sub",children:"Arrivals appear here the moment a camera recognises someone."})]}):o.jsx("ul",{className:"arrivals",children:e.map(a=>o.jsx(xp,{a},a.visit_id))})]})}function xp({a:e}){const t=e.name||e.label||"Unidentified";return o.jsxs("li",{className:"card arrival",children:[o.jsx(kp,{image:e.image,name:t,customerRef:e.visitor_ref}),o.jsxs("div",{className:"who-col",children:[o.jsx("strong",{children:t}),o.jsxs("span",{className:"sub",children:[e.name&&e.visitor_ref?`${e.visitor_ref} · `:"",e.site,e.camera_id?` · ${e.camera_id}`:""," · ",Ft(e.occurred_at)]}),e.attributes&&o.jsx(Np,{attrs:e.attributes})]}),e.is_new_visitor?o.jsx("span",{className:"pill new",children:"New"}):o.jsx("span",{className:"pill",children:"Returning"})]})}function kp({image:e,name:t,customerRef:n}){return e!=null&&e.available?o.jsx("span",{className:"face",children:o.jsx(Xi,{image:e,alt:""})}):o.jsx("span",{className:"face initials",title:(e==null?void 0:e.reason)||"","aria-hidden":"true",children:jp(t,n)})}function jp(e,t){const n=/^Visitor (\d+)$/.exec(String(e).trim());if(n)return n[1];if(t){const r=/^V-(\d+)$/.exec(t);if(r)return r[1]}return Sp(e)}function Sp(e){const t=String(e).trim().split(/\s+/).filter(Boolean);return t.length?t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[t.length-1][0]).toUpperCase():"?"}function Np({attrs:e}){const t=[];return e.gender&&t.push(e.gender),e.age&&t.push(`~${Math.round(e.age)}`),e.emotion&&t.push(e.emotion),t.length?o.jsx("span",{className:"attrs",children:t.join(" · ")}):null}function Cp({camera:e,onClose:t}){const n=j.useRef(null),[r,l]=j.useState("waiting"),[s,i]=j.useState(!1);j.useEffect(()=>{const c=new AbortController,v=np({cameraId:e.id,img:n,onState:h=>{l(h),h==="live"&&i(!1)},signal:c.signal}),m=setTimeout(()=>i(!0),12e3);return()=>{v(),c.abort(),clearTimeout(m)}},[e.id]);const a=e.connected===!1?"This camera was not connecting when the shop PC last reported. Check it is powered on and reachable on the shop’s network.":e.connected==null?"The shop PC has not reported on this camera yet. It may still be starting up.":"The shop PC is not sending frames. It may be offline, or its Behavision app may not be running.",u=s&&r!=="live"?a:{waiting:"Asking the shop PC…",live:"Live",reconnecting:"Reconnecting…"}[r];return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer live",onClick:c=>c.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:e.label}),o.jsx("p",{className:"sub",children:e.site})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("div",{className:"drawer-body",children:[o.jsxs("div",{className:"liveshot",children:[o.jsx("img",{ref:n,alt:`Live view from ${e.label}`}),r!=="live"&&o.jsx("div",{className:"livewait",children:o.jsx("span",{children:s?"No picture yet":u})})]}),o.jsx("p",{className:"hint",style:{marginTop:10},children:r==="live"?"Live. The shop only uploads while this view is open.":u})]})]})})}const Br=[{id:"hikvision",label:"Hikvision",path:"/Streaming/Channels/101",note:"Channel 1, main stream. Use /Streaming/Channels/102 for the lower-quality sub stream."},{id:"dahua",label:"Dahua",path:"/cam/realmonitor?channel=1&subtype=0",note:"Channel 1, main stream. subtype=1 is the sub stream."},{id:"cpplus",label:"CP Plus",path:"/cam/realmonitor?channel=1&subtype=0",note:"CP Plus cameras use the Dahua stream path."},{id:"uniview",label:"Uniview",path:"/media/video1",note:"Some older Uniview models use /video1 instead."},{id:"tplink",label:"TP-Link / Tapo",path:"/stream1",note:"Tapo cameras need a separate camera account created in the Tapo app — your Tapo login will not work."},{id:"reolink",label:"Reolink",path:"/h264Preview_01_main",note:"Use /h264Preview_01_sub for the lower-quality stream."},{id:"amcrest",label:"Amcrest",path:"/cam/realmonitor?channel=1&subtype=0",note:"Amcrest cameras use the Dahua stream path."},{id:"axis",label:"Axis",path:"/axis-media/media.amp",note:""},{id:"onvif",label:"Other (ONVIF)",path:"/onvif1",note:"Many generic cameras answer here. If it does not work, look for “RTSP” in the camera’s own app."},{id:"manual",label:"I know the path",path:"",note:""}],ca=e=>Br.find(t=>t.id===e)||Br[Br.length-1],Ep=["Camera","Connection","Test","Walk past"];function _p({sites:e,existing:t,onClose:n,onSaved:r}){var d;const l=!(t!=null&&t.id),[s,i]=j.useState(l?0:2),[a,u]=j.useState(t!=null&&t.id?t:null),[c,v]=j.useState({site_id:(t==null?void 0:t.site_id)||((d=e[0])==null?void 0:d.site_id)||"",make:"hikvision",label:(t==null?void 0:t.label)||"",host:(t==null?void 0:t.host)||"",port:(t==null?void 0:t.port)||554,path:(t==null?void 0:t.path)||"/Streaming/Channels/101",username:(t==null?void 0:t.username)||"",password:""}),[m,h]=j.useState(!1),[y,x]=j.useState(""),g=f=>w=>v(S=>({...S,[f]:w.target.value})),T=f=>{const w=ca(f.target.value);v(S=>({...S,make:w.id,path:w.path||S.path}))},p=async()=>{h(!0),x("");const f={};for(const[w,S]of Object.entries(c))w==="site_id"||w==="make"||S===""||S==null||(f[w]=w==="port"?Number(S):S);try{const w=a!=null&&a.id?await $.updateCamera(a.id,f):await $.createCamera(c.site_id,f);u(w),i(2),r==null||r(w,{keepOpen:!0})}catch(w){x(w.message)}finally{h(!1)}};return o.jsx("div",{className:"overlay",onClick:n,children:o.jsxs("aside",{className:"drawer wizard",onClick:f=>f.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsxs("div",{children:[o.jsx("h2",{children:l?"Set up a camera":(a==null?void 0:a.label)||(t==null?void 0:t.label)}),o.jsx("p",{className:"sub",children:s<2?"The shop’s PC connects to the camera — nothing needs opening to the internet.":"Prove it works before you rely on it."})]}),o.jsx("button",{className:"ghost",onClick:n,children:"Close"})]}),o.jsx("ol",{className:"steps",children:Ep.map((f,w)=>o.jsxs("li",{className:w===s?"now":wo.jsx("option",{value:f.site_id,children:f.name},f.site_id))})]}),o.jsxs("label",{children:["What should staff call it?",o.jsx("input",{value:c.label,onChange:g("label"),placeholder:"Entrance",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Visits are recorded against this name, so it cannot be changed later."})]}),o.jsxs("label",{children:["Make of camera",o.jsx("select",{value:c.make,onChange:T,children:Br.map(f=>o.jsx("option",{value:f.id,children:f.label},f.id))}),o.jsx("span",{className:"hint",children:ca(c.make).note||"This only fills in the stream path for you. You can change it on the next step."})]}),o.jsx("button",{className:"primary",disabled:!c.label.trim(),onClick:()=>i(1),children:"Next"})]}),s===1&&o.jsxs("div",{className:"drawer-body",children:[o.jsxs("label",{children:["Camera’s address on the shop’s network",o.jsx("input",{value:c.host,onChange:g("host"),placeholder:"192.168.0.138",autoFocus:!0}),o.jsx("span",{className:"hint",children:"Not a website address. It usually starts 192.168. — look in the camera’s own app, on its label, or in your router’s device list."})]}),o.jsxs("div",{className:"pair",children:[o.jsxs("label",{children:["Port",o.jsx("input",{type:"number",value:c.port,onChange:g("port")})]}),o.jsxs("label",{children:["Stream path",o.jsx("input",{value:c.path,onChange:g("path")})]})]}),o.jsxs("label",{children:["Camera username",o.jsx("input",{value:c.username,onChange:g("username"),placeholder:"admin",name:"camera-account",autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:"false"}),o.jsx("span",{className:"hint",children:"The camera’s own login, not your Behavision one."})]}),o.jsxs("label",{children:["Camera password",o.jsx("input",{type:"password",value:c.password,onChange:g("password"),name:"camera-secret",autoComplete:"new-password",placeholder:a!=null&&a.has_password?"(unchanged)":""})]}),y&&o.jsx("p",{className:"error",role:"alert",children:y}),o.jsxs("div",{className:"pair",children:[o.jsx("button",{className:"ghost",onClick:()=>i(0),children:"Back"}),o.jsx("button",{className:"primary",disabled:m||!c.host.trim(),onClick:p,children:m?"Saving…":"Save and test"})]})]}),s>=2&&a&&o.jsx(Pp,{camera:a,step:s,onStep:i,onUpdated:f=>{u(f),r==null||r(f,{keepOpen:!0})},onEdit:()=>i(1),onDone:n})]})})}function Pp({camera:e,step:t,onStep:n,onUpdated:r,onEdit:l,onDone:s}){const[i,a]=j.useState(e),[u,c]=j.useState(!1),[v,m]=j.useState(""),h=j.useRef(null);j.useEffect(()=>a(e),[e]);const y=i.check||{},x=y.state==="requested"||y.state==="running";j.useEffect(()=>{if(!x)return;let p=!0;const d=async()=>{try{const w=(await $.cameras()).find(S=>S.id===i.id);p&&w&&(a(w),r==null||r(w))}catch{}};return h.current=setInterval(d,4e3),()=>{p=!1,clearInterval(h.current)}},[x,i.id]);const g=async(p,d)=>{c(!0),m("");try{const f=await $.checkCamera(i.id,p,d);a(f),r==null||r(f),n(p==="placement"?3:2)}catch(f){m(f.message)}finally{c(!1)}},T=y.kind==="connection"&&y.state==="done"&&y.ok;return o.jsx(o.Fragment,{children:o.jsxs("div",{className:"drawer-body",children:[t===2?o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can the shop’s PC reach this camera?"}),o.jsx("p",{className:"sub",children:"The PC opens the stream once and takes a single picture. Nothing is recorded."})]}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:"Can it actually recognise a face?"}),o.jsxs("p",{className:"sub",children:["Someone needs to ",o.jsx("b",{children:"walk through the camera’s view and out of it"}),", the way a customer would. Standing still measures nothing — the check scores the best view of each person as they leave the frame, which is what recognition really uses."]})]}),x&&o.jsxs("div",{className:"waiting",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("b",{children:y.state==="running"?"Running on the shop’s PC…":"Waiting for the shop’s PC…"}),o.jsx("span",{className:"sub",children:y.state==="running"?"This takes about "+(y.seconds||25)+" seconds.":"It picks up the request within a couple of minutes."})]})]}),y.state==="done"&&o.jsx(Tp,{check:y}),v&&o.jsx("p",{className:"error",role:"alert",children:v}),o.jsx("div",{className:"pair",children:t===2?o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:l,children:"Change details"}),o.jsx("button",{className:"primary",disabled:u||x,onClick:()=>g("connection"),children:y.state==="done"?"Test again":"Test connection"})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"ghost",onClick:()=>n(2),children:"Back"}),o.jsx("button",{className:"primary",disabled:u||x,onClick:()=>g("placement",25),children:y.state==="done"?"Check again":"Start walk-past check"})]})}),t===2&&T&&!x&&o.jsx("button",{className:"primary",onClick:()=>n(3),children:"Next: prove it can recognise faces"}),t===3&&y.state==="done"&&!x&&o.jsx("button",{className:"ghost",onClick:s,children:"Finish"})]})})}function Tp({check:e}){var n,r,l;const t=e.ok?"ok":e.verdict==="marginal"?"warn":"bad";return o.jsxs("div",{className:"outcome "+t,children:[o.jsxs("div",{className:"outcome-head",children:[o.jsx("span",{className:"pill "+t,children:e.ok?"Working":"Not ready"}),o.jsx("b",{children:e.headline||(e.ok?"Working":"Could not be verified")})]}),((n=e.image)==null?void 0:n.available)&&o.jsx("img",{className:"proof",src:e.image.url,alt:"The view from this camera",loading:"lazy"}),((r=e.advice)==null?void 0:r.length)>0&&o.jsx("ul",{className:"advice",children:e.advice.map((s,i)=>o.jsx("li",{children:s},i))}),((l=e.detail)==null?void 0:l.faces)!=null&&o.jsxs("p",{className:"sub",children:[e.detail.faces," ",e.detail.faces===1?"person":"people"," walked past during the check."]})]})}function zp(e){const t=e.check||{};return t.state==="requested"||t.state==="running"?{tone:"idle",mark:"…",words:"Checking now"}:t.state!=="done"?{tone:"idle",mark:"?",words:"Not checked yet"}:t.kind==="placement"?t.ok?{tone:"ok",mark:"✓",words:"Recognises faces here"}:{tone:"bad",mark:"✕",words:t.headline||"Cannot recognise faces here"}:t.ok?{tone:"warn",mark:"!",words:"Stream works — faces not checked yet"}:{tone:"bad",mark:"✕",words:t.headline||"Could not reach the camera"}}function Lp({user:e}){const{data:t,error:n,loading:r,reload:l}=It(()=>$.cameras(),2e4,[]),{data:s}=It(()=>$.sites(),0,[]),[i,a]=j.useState(null),[u,c]=j.useState(null),v=["admin","owner","manager"].includes(e.role),m=t||[],h=m.filter(g=>g.connected).length,y=m.filter(g=>g.connected===!1).length,x=m.filter(g=>g.connected==null).length;return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Cameras"}),o.jsxs("p",{className:"sub",children:[m.length," ",m.length===1?"camera":"cameras",h>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"ok",children:[h," connected"]})]}),y>0&&o.jsxs(o.Fragment,{children:[" · ",o.jsxs("b",{className:"bad",children:[y," down"]})]}),x>0&&o.jsxs(o.Fragment,{children:[" · ",x," waiting for the shop PC"]})]}),v&&o.jsx("button",{className:"primary",onClick:()=>a({}),children:"Set up a camera"})]}),r&&!t?o.jsx(ar,{}):n?o.jsx(ur,{error:n}):m.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No cameras yet"}),o.jsx("p",{className:"sub",children:"Add one here and the shop’s PC will pick it up within a couple of minutes. Cameras already set up on a shop PC appear here on their own."})]}):o.jsx("div",{className:"grid cams",children:m.map(g=>o.jsx(Rp,{cam:g,canEdit:v,onEdit:()=>a(g),onWatch:()=>c(g)},g.id))}),i&&o.jsx(_p,{existing:i.id?i:null,sites:s||[],onClose:()=>{a(null),l()},onSaved:(g,T)=>{T!=null&&T.keepOpen||a(null),l()}}),u&&o.jsx(Cp,{camera:u,onClose:()=>c(null)})]})}function Rp({cam:e,canEdit:t,onEdit:n,onWatch:r}){var a,u;const l=e.connected==null?"idle":e.connected?"ok":"bad",s=e.connected==null?"Waiting for the shop PC":e.connected?"Connected":"Not connecting",i=zp(e);return o.jsxs("article",{className:"card cam state-"+l,onClick:t?n:void 0,role:t?"button":void 0,tabIndex:t?0:void 0,onKeyDown:c=>t&&c.key==="Enter"&&n(),children:[o.jsxs("div",{className:"shot",children:[(a=e.snapshot)!=null&&a.available?o.jsx(Xi,{image:e.snapshot,alt:`View from ${e.label}`}):o.jsxs("div",{className:"noshot",children:[o.jsx("span",{className:"lens","aria-hidden":"true"}),((u=e.snapshot)==null?void 0:u.reason)||"No picture yet."]}),o.jsxs("div",{className:"shot-over",children:[o.jsxs("div",{className:"shot-name",children:[o.jsx("b",{children:e.label||e.camera_id}),o.jsx("span",{children:e.site})]}),o.jsxs("span",{className:"status "+l,children:[o.jsx("i",{"aria-hidden":"true"}),s]})]}),e.snapshot_at&&o.jsx("span",{className:"shot-age",children:Ft(e.snapshot_at)}),o.jsxs("button",{className:"watch",title:"Watch this camera now",onClick:c=>{c.stopPropagation(),r()},children:[o.jsx("i",{"aria-hidden":"true"}),"Live"]})]}),o.jsxs("div",{className:"verdict "+i.tone,children:[o.jsx("span",{className:"mark","aria-hidden":"true",children:i.mark}),o.jsx("span",{className:"words",children:i.words}),t&&o.jsx("span",{className:"go","aria-hidden":"true",children:"→"})]})]})}const Op=["Is everything working today?","Why is footfall low at Chennai?","How many people came in last week?","Which cameras still need checking?"];function Ip({open:e,onClose:t}){const[n,r]=j.useState([]),[l,s]=j.useState(""),[i,a]=j.useState(!1),[u,c]=j.useState(!1),v=j.useRef(null),m=j.useRef(null);j.useEffect(()=>{var y;e&&((y=m.current)==null||y.focus())},[e]),j.useEffect(()=>{var y;(y=v.current)==null||y.scrollIntoView({behavior:"smooth",block:"end"})},[n,i]);const h=async y=>{const x=(y??l).trim();if(!x||i)return;const g=[...n,{role:"user",text:x}];r(g),s(""),a(!0);try{const T=await $.ask(g);r(p=>[...p,{role:"assistant",text:T.text,used:T.used}])}catch(T){T.code==="assistant_off"?c(!0):r(p=>[...p,{role:"assistant",text:T.message,failed:!0}])}finally{a(!1)}};return e?o.jsxs("aside",{className:"assistant",role:"complementary","aria-label":"Assistant",children:[o.jsxs("header",{className:"assistant-head",children:[o.jsxs("div",{children:[o.jsx("b",{children:"Ask Behavision"}),o.jsx("span",{className:"sub",children:"It reads your shops’ own data to answer."})]}),o.jsx("button",{className:"ghost",onClick:t,"aria-label":"Close assistant",children:"✕"})]}),o.jsxs("div",{className:"assistant-body",children:[u?o.jsx("p",{className:"sub pad",children:"The assistant is not switched on for this server."}):n.length===0?o.jsxs("div",{className:"suggest",children:[o.jsx("p",{className:"sub",children:"Try asking:"}),Op.map(y=>o.jsx("button",{className:"chip",onClick:()=>h(y),children:y},y))]}):n.map((y,x)=>{var g;return o.jsxs("div",{className:"bubble "+y.role+(y.failed?" failed":""),children:[y.text,((g=y.used)==null?void 0:g.length)>0&&o.jsxs("span",{className:"used",children:["looked at: ",y.used.map(Fp).join(", ")]})]},x)}),i&&o.jsxs("div",{className:"bubble assistant-thinking",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"})," Looking…"]}),o.jsx("div",{ref:v})]}),!u&&o.jsxs("form",{className:"assistant-ask",onSubmit:y=>{y.preventDefault(),h()},children:[o.jsx("input",{ref:m,value:l,onChange:y=>s(y.target.value),placeholder:"Ask about your shops…",disabled:i}),o.jsx("button",{className:"primary",disabled:i||!l.trim(),children:"Ask"})]})]}):null}function Fp(e){return{list_shops:"your shops",check_shop:"a shop check",list_cameras:"your cameras",check_camera:"a camera check",footfall:"footfall",sales:"sales",find_customer:"customer records"}[e]||e}function Dp(){const{data:e,error:t,loading:n,reload:r}=It(()=>$.clients(),0,[]),[l,s]=j.useState(!1),[i,a]=j.useState(null),u=e||[];return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Companies"}),o.jsx("button",{className:"primary",onClick:()=>{a(null),s(!0)},children:"New company"})]}),i&&o.jsx($p,{result:i,onDismiss:()=>a(null)}),n&&!e?o.jsx(ar,{}):t?o.jsx(ur,{error:t}):u.length===0?o.jsxs("div",{className:"state",children:[o.jsx("h2",{children:"No companies yet"}),o.jsx("p",{className:"sub",children:"Create one, and its owner can sign in straight away."})]}):o.jsx("div",{className:"tablewrap",children:o.jsxs("table",{className:"rows",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Company"}),o.jsx("th",{children:"Short name"}),o.jsx("th",{children:"Sites"}),o.jsx("th",{children:"People"}),o.jsx("th",{children:"Created"})]})}),o.jsx("tbody",{children:u.map(c=>o.jsxs("tr",{children:[o.jsx("td",{children:o.jsx("strong",{children:c.name})}),o.jsx("td",{children:o.jsx("code",{children:c.slug})}),o.jsx("td",{className:"num",children:c.sites}),o.jsx("td",{className:"num",children:c.users}),o.jsx("td",{className:"sub",children:Ft(c.created_at)})]},c.id))})]})}),l&&o.jsx(Mp,{onClose:()=>s(!1),onCreated:c=>{s(!1),a(c),r()}})]})}function Mp({onClose:e,onCreated:t}){const[n,r]=j.useState({company_name:"",owner_name:"",owner_email:"",password:""}),[l,s]=j.useState(!1),[i,a]=j.useState(""),u=v=>m=>r({...n,[v]:m.target.value}),c=async v=>{v.preventDefault(),s(!0),a("");try{t(await $.createClient(n))}catch(m){a(m.message),s(!1)}};return o.jsx("div",{className:"overlay",onClick:e,children:o.jsxs("aside",{className:"drawer narrow",onClick:v=>v.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsx("h2",{children:"New company"}),o.jsx("button",{className:"ghost",onClick:e,children:"Close"})]}),o.jsxs("form",{className:"drawer-body",onSubmit:c,children:[o.jsxs("label",{children:["Company name",o.jsx("input",{value:n.company_name,onChange:u("company_name"),required:!0,autoFocus:!0})]}),o.jsxs("label",{children:["Owner’s name",o.jsx("input",{value:n.owner_name,onChange:u("owner_name")})]}),o.jsxs("label",{children:["Owner’s email",o.jsx("input",{type:"email",value:n.owner_email,onChange:u("owner_email"),required:!0})]}),o.jsxs("label",{children:["Password",o.jsx("input",{type:"text",value:n.password,onChange:u("password"),placeholder:"Leave empty to generate one"}),o.jsx("span",{className:"hint",children:"Generated is better — a password you invent for someone else ends up weak and sent over chat."})]}),i&&o.jsx("p",{className:"error",role:"alert",children:i}),o.jsx("button",{className:"primary",disabled:l,children:l?"Creating…":"Create company"})]})]})})}function $p({result:e,onDismiss:t}){return o.jsxs("div",{className:"banner ok credentials",children:[o.jsxs("div",{children:[o.jsxs("b",{children:[e.slug," created."]})," These sign-in details are shown once and cannot be recovered. Send them to the owner now.",o.jsxs("dl",{className:"creds",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Email"}),o.jsx("dd",{children:o.jsx("code",{children:e.owner_email})})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Password"}),o.jsx("dd",{children:o.jsx("code",{children:e.password})})]})]})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Done"})]})}function Up({user:e}){const t=It(()=>$.team(),0,[]),n=It(()=>$.invitations(),0,[]),[r,l]=j.useState(!1),[s,i]=j.useState(null),[a,u]=j.useState(""),[c,v]=j.useState(""),m=e.role==="owner"||e.role==="manager",h=t.data||[],y=n.data||[],x=async(g,T)=>{u(g),v("");try{await $.updateMember(g,T),t.reload()}catch(p){v(p.message)}finally{u("")}};return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"head",children:[o.jsx("h1",{children:"Team"}),m&&o.jsx("button",{className:"primary",onClick:()=>{i(null),l(!0)},children:"Invite someone"})]}),s&&o.jsx(Bp,{invite:s,onDismiss:()=>i(null)}),c&&o.jsx("p",{className:"error",role:"alert",children:c}),t.loading&&!t.data?o.jsx(ar,{}):t.error?o.jsx(ur,{error:t.error}):o.jsx("div",{className:"tablewrap",children:o.jsxs("table",{className:"rows",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"Name"}),o.jsx("th",{children:"Email"}),o.jsx("th",{children:"Role"}),o.jsx("th",{children:"Last signed in"}),m&&o.jsx("th",{})]})}),o.jsx("tbody",{children:h.map(g=>o.jsxs("tr",{className:g.active?"":"inactive",children:[o.jsxs("td",{children:[o.jsx("strong",{children:g.full_name||"—"}),!g.active&&o.jsx("span",{className:"pill muted",children:"No access"})]}),o.jsx("td",{children:o.jsx("code",{children:g.email})}),o.jsx("td",{children:m&&g.id!==e.id?o.jsxs("select",{value:g.role,disabled:a===g.id,onChange:T=>x(g.id,{role:T.target.value}),children:[o.jsx("option",{value:"staff",children:"Staff"}),o.jsx("option",{value:"manager",children:"Manager"}),e.role==="owner"&&o.jsx("option",{value:"owner",children:"Owner"})]}):o.jsx("span",{className:"role",children:g.role})}),o.jsx("td",{className:"sub",children:g.last_login_at?Ft(g.last_login_at):"Never"}),m&&o.jsx("td",{className:"right",children:g.id===e.id?null:g.active?o.jsx("button",{className:"ghost danger",disabled:a===g.id,onClick:()=>x(g.id,{active:!1}),children:"Remove access"}):o.jsx("button",{className:"ghost",disabled:a===g.id,onClick:()=>x(g.id,{active:!0}),children:"Restore"})})]},g.id))})]})}),m&&y.length>0&&o.jsxs("section",{className:"pending",children:[o.jsx("h2",{children:"Waiting to join"}),o.jsx("ul",{className:"invites",children:y.map(g=>o.jsxs("li",{className:"card invite",children:[o.jsxs("div",{children:[o.jsx("strong",{children:g.email}),o.jsxs("span",{className:"sub",children:["invited as ",g.role,g.invited_by?` by ${g.invited_by}`:""," · expires ",yp(g.expires_at)]})]}),o.jsx("button",{className:"ghost danger",onClick:async()=>{await $.revokeInvitation(g.id),n.reload()},children:"Withdraw"})]},g.id))})]}),r&&o.jsx(Ap,{canMintOwner:e.role==="owner",onClose:()=>l(!1),onDone:g=>{l(!1),i(g),n.reload()}})]})}function Ap({canMintOwner:e,onClose:t,onDone:n}){const[r,l]=j.useState({email:"",full_name:"",role:"staff"}),[s,i]=j.useState(!1),[a,u]=j.useState(""),c=m=>h=>l({...r,[m]:h.target.value}),v=async m=>{m.preventDefault(),i(!0),u("");try{n(await $.invite(r))}catch(h){u(h.message),i(!1)}};return o.jsx("div",{className:"overlay",onClick:t,children:o.jsxs("aside",{className:"drawer narrow",onClick:m=>m.stopPropagation(),children:[o.jsxs("header",{className:"drawer-head",children:[o.jsx("h2",{children:"Invite someone"}),o.jsx("button",{className:"ghost",onClick:t,children:"Close"})]}),o.jsxs("form",{className:"drawer-body",onSubmit:v,children:[o.jsxs("label",{children:["Their email",o.jsx("input",{type:"email",value:r.email,onChange:c("email"),required:!0,autoFocus:!0,autoComplete:"off",name:"invitee"}),o.jsx("span",{className:"hint",children:"This is the address they will sign in with, and it is fixed by the invitation — passing the code on cannot make it somebody else’s account."})]}),o.jsxs("label",{children:["Their name",o.jsx("input",{value:r.full_name,onChange:c("full_name"),autoComplete:"off",name:"invitee-name"})]}),o.jsxs("label",{children:["Role",o.jsxs("select",{value:r.role,onChange:c("role"),children:[o.jsx("option",{value:"staff",children:"Staff — see customers and shops"}),o.jsx("option",{value:"manager",children:"Manager — also set up cameras and invite people"}),e&&o.jsx("option",{value:"owner",children:"Owner — full control"})]})]}),a&&o.jsx("p",{className:"error",role:"alert",children:a}),o.jsx("button",{className:"primary",disabled:s,children:s?"Creating…":"Create invitation"})]})]})})}function Bp({invite:e,onDismiss:t}){return o.jsxs("div",{className:"banner ok credentials",children:[o.jsxs("div",{children:[o.jsxs("b",{children:["Invitation for ",e.email,"."]})," Give them this code. It is shown once, works once, and cannot be recovered.",o.jsxs("dl",{className:"creds",children:[o.jsxs("div",{children:[o.jsx("dt",{children:"Code"}),o.jsx("dd",{children:o.jsx("code",{className:"big",children:e.code})})]}),o.jsxs("div",{children:[o.jsx("dt",{children:"Role"}),o.jsx("dd",{children:e.role})]})]}),o.jsx("p",{className:"sub",children:"They open the app, choose “I have an invitation code”, and pick their own password. Nobody else ever sees it."})]}),o.jsx("button",{className:"ghost",onClick:t,children:"Done"})]})}const Vp=[{id:"sites",label:"Shops",View:dp},{id:"live",label:"Live",View:wp},{id:"cameras",label:"Cameras",View:Lp},{id:"team",label:"Team",View:Up}],Wp=[{id:"clients",label:"Companies",View:Dp}];function Hp(){const[e,t]=j.useState(null),[n,r]=j.useState(!0),[l,s]=j.useState("sites"),[i,a]=j.useState(!1);if(j.useEffect(()=>{(async()=>{if(ep())try{t(await $.me())}catch{or()}r(!1)})()},[]),n)return o.jsxs("div",{className:"boot",children:[o.jsx("span",{className:"spinner","aria-hidden":"true"}),"Loading…"]});if(!e)return o.jsx(rp,{onSignedIn:t});const u=e.role==="admin"&&!e.client_id,c=u?Wp:Vp,v=c.find(y=>y.id===l)||c[0],m=v.View,h=async()=>{await $.logout(),t(null)};return o.jsxs("div",{className:"app",children:[o.jsxs("header",{className:"topbar",children:[o.jsxs("div",{className:"brand",children:[o.jsx("span",{className:"mark","aria-hidden":"true"}),o.jsxs("div",{children:[o.jsx("strong",{children:"Behavision"}),o.jsx("span",{className:"org",children:e.client_name||"Loyaly platform"})]})]}),o.jsx("nav",{className:"tabs",children:c.map(y=>o.jsx("button",{onClick:()=>s(y.id),"aria-current":v.id===y.id?"page":void 0,children:y.label},y.id))}),o.jsxs("div",{className:"who",children:[o.jsxs("button",{className:"ask-btn"+(i?" on":""),onClick:()=>a(y=>!y),children:[o.jsx("span",{"aria-hidden":"true",children:"✳"})," Ask"]}),o.jsx("span",{className:"name",children:e.full_name||e.email}),o.jsx("span",{className:"role",children:u?"platform admin":e.role}),o.jsx("button",{className:"ghost",onClick:h,children:"Sign out"})]})]}),o.jsxs("div",{className:"with-assistant"+(i?" open":""),children:[o.jsx("main",{className:"page",children:o.jsx(m,{user:e})}),o.jsx(Ip,{open:i,onClose:()=>a(!1)})]})]})}Sc(document.getElementById("root")).render(o.jsx(Hp,{})); diff --git a/server/internal/web/dist/index.html b/server/internal/web/dist/index.html index 85fe50a..5a391c2 100644 --- a/server/internal/web/dist/index.html +++ b/server/internal/web/dist/index.html @@ -5,7 +5,7 @@ Behavision - + diff --git a/server/migrations/012_visitor_numbers.sql b/server/migrations/012_visitor_numbers.sql new file mode 100644 index 0000000..1eb917d --- /dev/null +++ b/server/migrations/012_visitor_numbers.sql @@ -0,0 +1,81 @@ +-- A customer number a person can say out loud. +-- +-- Until now `RecordVisit` named every new customer with eight hex characters +-- off their uuid: +-- +-- UPDATE visitors SET label = 'Visitor ' || left(id::text, 8) +-- +-- So the name a shop assistant reads on the arrivals feed, and reads back to a +-- colleague, and types into a search box, was "Visitor 3446ec35". That is not +-- a display problem to paper over in the front end - `label` is a stored +-- column that staff can overwrite, it is what `SearchVisitors` matches on, and +-- it is what the desktop app, the web console and the mobile feed all show. +-- It had to be fixed where it is written. +-- +-- The replacement is a per-CLIENT sequential number: "Visitor 42", referenced +-- as `V-42`. Three properties, each of which rules out an alternative: +-- +-- * Speakable and typeable. This is the whole point. A number is read down a +-- phone, written on a card and searched for; a uuid is copy-pasted or got +-- wrong. +-- * Per client, not global. A global sequence tells any customer who signs +-- up how many people the entire platform has ever seen, from their own +-- first visitor number - the German-tank estimate, and a number no +-- customer should be able to compute. Per tenant it only reveals a +-- tenant's own count to that tenant's own staff, who know it already. +-- * Not the primary key. `visitors.id` stays a uuid. The ids in this schema +-- are generated in places that cannot ask a database for the next value, +-- and swapping a PK that eleven tables reference for a sequence buys +-- nothing internal while risking everything. This is a public REFERENCE +-- sitting beside the key, which is the part humans needed all along. +-- +-- The counter lives on `clients`, and `UPDATE ... RETURNING` returns the value +-- AFTER the update - which is exactly what is wanted here, and is the same +-- semantics that silently broke the face prune in 011 by returning the value +-- it had just written. Taking the number this way row-locks the client for the +-- length of the insert, serialising new-visitor creation per tenant. That is +-- free: a new visitor row is written only for a face nobody in the estate has +-- ever seen, not once per visit. Computing MAX(number)+1 instead would race +-- two shops onto one number. + +BEGIN; + +ALTER TABLE clients ADD COLUMN IF NOT EXISTS visitor_seq bigint NOT NULL DEFAULT 0; +ALTER TABLE visitors ADD COLUMN IF NOT EXISTS number bigint; + +-- Existing rows are numbered in the order they were first seen, so a customer +-- who has been coming for a year has a lower number than one who arrived +-- yesterday. Ties break on id only so the result is deterministic. +WITH numbered AS ( + SELECT id, + row_number() OVER (PARTITION BY client_id + ORDER BY first_seen_at, id) AS n + FROM visitors +) +UPDATE visitors v + SET number = numbered.n + FROM numbered + WHERE v.id = numbered.id + AND v.number IS NULL; + +UPDATE clients c + SET visitor_seq = COALESCE((SELECT max(number) FROM visitors + WHERE client_id = c.id), 0); + +-- Rename ONLY the labels this system generated. The pattern is exactly the +-- eight lowercase hex characters the old statement produced, so a name a human +-- typed - including one that legitimately starts with the word Visitor - is +-- left alone. Overwriting a staff-assigned name would be silent data loss of +-- the kind nobody would notice until a customer was greeted wrongly. +UPDATE visitors + SET label = 'Visitor ' || number + WHERE number IS NOT NULL + AND label ~ '^Visitor [0-9a-f]{8}$'; + +ALTER TABLE visitors ALTER COLUMN number SET NOT NULL; + +-- Unique per tenant, and the index `V-42` is resolved through. +CREATE UNIQUE INDEX IF NOT EXISTS visitors_number_idx + ON visitors (client_id, number); + +COMMIT; diff --git a/web/src/views/Customers.jsx b/web/src/views/Customers.jsx index 5e4053f..03635f3 100644 --- a/web/src/views/Customers.jsx +++ b/web/src/views/Customers.jsx @@ -55,6 +55,11 @@ export default function Customers({ user }) { onKeyDown={e => e.key === 'Enter' && setOpen(c)}> {c.full_name || c.label} + {/* The number is shown next to a name a human typed, and + not next to the auto label, which already IS the + number ("Visitor 13"). Printing "Visitor 13 · V-13" + would read as two identifiers for one person. */} + {c.full_name && c.ref && · {c.ref}} {c.phone && · {c.phone}} {c.visit_count} @@ -118,6 +123,8 @@ function Drawer({ customer, user, onClose, onSaved }) {

{customer.full_name || customer.label}

+ {customer.full_name && customer.ref && +

{customer.ref}

}

{customer.visit_count} visits · last seen {ago(customer.last_seen_at)}

diff --git a/web/src/views/Live.jsx b/web/src/views/Live.jsx index fffb592..7434640 100644 --- a/web/src/views/Live.jsx +++ b/web/src/views/Live.jsx @@ -86,10 +86,14 @@ function Arrival({ a }) { const name = a.name || a.label || 'Unidentified' return (
  • - +
    {name} + {/* Only beside a name somebody typed. The auto label already IS the + number, so "Visitor 13 · V-13" would read as two identifiers for + one person. */} + {a.name && a.visitor_ref ? `${a.visitor_ref} · ` : ''} {a.site}{a.camera_id ? ` · ${a.camera_id}` : ''} · {ago(a.occurred_at)} {a.attributes && } @@ -111,17 +115,37 @@ function Arrival({ a }) { // be loaded by an at all — it needs the session — so a plain src here // showed a broken image on exactly the deployments that had just started // storing photos. -function Face({ image, name }) { +// customerRef, not `ref`: React reserves that prop name, so it would never +// reach this component's props. +function Face({ image, name, customerRef }) { if (image?.available) { return } return ( ) } +// What goes in the circle when there is no photograph. +// +// Initials of a name a human typed; the NUMBER for a customer the system named +// itself. Running initials() over "Visitor 13" takes the first letter of each +// word and produces "V1" - which is also what "Visitor 10" and "Visitor 15" +// produce, so three different people wore the same badge, and it read as the +// V-1 reference for a fourth. Found by opening the page: every unit test here +// passes a human name. +function avatarText(name, customerRef) { + const auto = /^Visitor (\d+)$/.exec(String(name).trim()) + if (auto) return auto[1] + if (customerRef) { + const n = /^V-(\d+)$/.exec(customerRef) + if (n) return n[1] + } + return initials(name) +} + function initials(name) { const parts = String(name).trim().split(/\s+/).filter(Boolean) if (!parts.length) return '?'