diff --git a/CHECKSUMS.txt b/CHECKSUMS.txt index a0786b62c1b2e973ae135acc27e53375d3e12d35..7efbe3666c3ea143a46de3ea587321a29469bb7d 100644 --- a/CHECKSUMS.txt +++ b/CHECKSUMS.txt @@ -1,23 +1,23 @@ -Cover Charge v0.3.12.214: web apps, plus the Cover Charge for Display tablet app for Android (downloads/android/, its SHA-256 is in downloads/android/SHA256.txt). No phone APKs were built for v0.1.2 to v0.3.12.214. +Cover Charge v0.3.12.215: web apps, plus the Cover Charge for Display tablet app for Android (downloads/android/, its SHA-256 is in downloads/android/SHA256.txt). No phone APKs were built for v0.1.2 to v0.3.12.215. SHA-256 of each web app's start page, service worker, manifest and logo: -d2a05fbb5bda1869db9fffccc00327c901da5ecaf43192e001e3faba7b2fccc3 owner-app/index.html -a2892e30c1297dabde1aacf450c79af28ee3a26519f273c861369e85afc80511 owner-app/sw.js +fa92e5da24944a248944054ae299963e40267584ba934366939abdb14b60a46c owner-app/index.html +7fc19333744f16a1539b0b9975eb34c1c7afcf9f5cc4d90114f3ad909e21f828 owner-app/sw.js e305c44d11a9c25f37372f3fa4d329d4ffb04df2edee6e7b4b9ac91f3875ac67 owner-app/manifest.webmanifest cc3dd9b8a359ba6c3f28d625c27cc6a01a46233311c2a5f5c8aaf09e91be8239 owner-app/brand-logo.png -8ceb8eeca283485b6114d84d1c9f412c81014a534238af52d49d6d07910779a1 staff-app/index.html -b8d99ffcb6542d5478cdf53901436da55275a933b415792764ba7ecda788210e staff-app/sw.js +7028038c4a807bacff1d5d8074fdeae73b5bc16f447e16401d2c9d2ac341886a staff-app/index.html +db869024eb2ee9cf945b6a9d9525a6d7a82c07ae1707817db86a2b3fba89b875 staff-app/sw.js bd1d310ebf8e2a80808e100c41fb7fe1c4369d3026478f3ad8eececaeadaf4ac staff-app/manifest.webmanifest cc3dd9b8a359ba6c3f28d625c27cc6a01a46233311c2a5f5c8aaf09e91be8239 staff-app/brand-logo.png -bc06b94119ba7e19572ccb21119134a0c7a579edc9aea3b6a69a33c830014ec9 customer-app/index.html -6cd51ffdbc1be743a08ab4dfec675984d9219774df85c6e229e3160830ffd742 customer-app/sw.js +89b61eca069444fe09fc5d88483b364fe93f436992e7e1f8e819772b455c9bd5 customer-app/index.html +08057d0e1549f65b4e2c72ad9530f6b8fd536052b9130f05ac332440b1d4730a customer-app/sw.js 3bfb1fd10cc13f09ca6be65c461e1f6b5750ae51a3ece12e079750b2a066052e customer-app/manifest.webmanifest cc3dd9b8a359ba6c3f28d625c27cc6a01a46233311c2a5f5c8aaf09e91be8239 customer-app/brand-logo.png -c4040806985ca6d82f8c5b1d15acfc33a6a29c8cb459aac32f63dffb9f7224d6 display-app/index.html -946685287a4096974e36076a0b9c8c1746b8e6f4b56d4428ba4af96b8b7a02b8 display-app/sw.js +04d1f986a2b0c3fc02148c439ecc21125eaddffc3bba2db340dae8c3f5b7022c display-app/index.html +99a1396e44d23fa0e2d14eecb0cab45a917b69625945018cf0689dd243662d89 display-app/sw.js 35e2721b86eb1ae1605e55bee64177adcee72f4e53a24ac417d19ea2873434a1 display-app/manifest.webmanifest cc3dd9b8a359ba6c3f28d625c27cc6a01a46233311c2a5f5c8aaf09e91be8239 display-app/brand-logo.png -1cc96ab5910ab0afb789abe28f98856b24dd506c9ca06f10791c5508bf90cbaf chef-app/index.html -3f3b7fe84d93bfb7c24457fa83d7df64d380c401740acfc621b1f792f501dd80 chef-app/sw.js +94f205e4ac1bfe3c19c65d2bd918bd6350ecf6788205f52230f049c715e2c55f chef-app/index.html +49ab279b1cecb5109064d0ea1d9eb0cd38a9da9114ca18cbea95d6a92e732cd8 chef-app/sw.js 97ed43decde8a888e22b7411e13a2122c6f8b9944cf38b2e28e8f62ef2e25397 chef-app/manifest.webmanifest cc3dd9b8a359ba6c3f28d625c27cc6a01a46233311c2a5f5c8aaf09e91be8239 chef-app/brand-logo.png diff --git a/car-app/_expo/static/js/web/bundle.js b/car-app/_expo/static/js/web/bundle.js index 5849b840d54e66410a839b56e2c0f1d8d4239415..0e75c63c9c17ec6e6daf42b6c4a4df98a987429c 100644 --- a/car-app/_expo/static/js/web/bundle.js +++ b/car-app/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?``:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/car-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(_g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"CREATOR_TITLE",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"pounds",{enumerable:!0,get:function(){return v}}),Object.defineProperty(_e,"numIn",{enumerable:!0,get:function(){return C}}),_e.useOwnCosting=I,_e.DishCreator=function({rid:e,canPublish:t,initial:n="create"}){const l=I(),o=(0,d.useGpCalcView)(),[c,p]=(0,i.useState)(n),[g,h]=(0,i.useState)(()=>P(o.settings.defaultTarget));return l?(0,f.jsxs)(r.default,{style:{gap:12},testID:"dish-creator",children:[o.alerts.map(e=>(0,f.jsx)(r.default,{testID:"margin-alert",children:(0,f.jsx)(a.Banner,{kind:"danger",title:`Margin dropped: ${e.ingredient} ${e.change}`,children:(0,f.jsxs)(r.default,{style:{gap:4},children:[e.dishes.map(e=>(0,f.jsxs)(a.T,{size:14,colour:"#FFE3DF",children:[e.name,": ",(0,u.pct)(e.before)," \u2192 ",(0,u.pct)(e.after),e.belowTarget?' \xb7 below target':'']},e.id)),(0,f.jsx)(s.ToastClose,{label:"Dismiss alert",testID:`margin-alert-close-${e.id}`,onPress:()=>o.dismissAlert(e.id),size:"sm",style:{alignSelf:'flex-end'}})]})})},e.id)),(0,f.jsx)(y.Tabs,{value:c,onChange:p,options:[{id:'create',label:g.name&&o.dishes.some(e=>e.id===g.id)?'Edit dish':'Create'},{id:'saved',label:'Saved dishes & GP'},{id:'items',label:'Ingredient prices'},{id:'settings',label:'VAT & rounding'}]}),'create'===c?(0,f.jsx)(D,{draft:g,setDraft:h,onNew:()=>h(P(o.settings.defaultTarget)),onSaved:()=>p('saved')},g.id):null,'saved'===c?(0,f.jsx)(G,{rid:e,canPublish:t,onEdit:e=>{h({...e,allergens:[...e.allergens??[]]}),p('create')}}):null,'items'===c?(0,f.jsx)(V,{}):null,'settings'===c?(0,f.jsx)(W,{}):null,(0,f.jsx)(a.Muted,{children:"Costs are visible to Managers and the Head Chef only. Prices you enter, not supplier quotes."})]}):(0,f.jsx)(r.default,{testID:"dish-creator-no-access",style:{alignItems:'center',paddingVertical:16},children:(0,f.jsx)(a.Muted,{center:!0,children:"Ingredient prices and dish costs are for the Head Chef, owners and managers."})})},_e.NewIngredient=A,Object.defineProperty(_e,"TALL",{enumerable:!0,get:function(){return L}}),_e.Pick=R,_e.Items=V,_e.useCardCosting=function(e,t,s="edit"){const{ingredients:n,settings:l,cardCosts:r}=(0,d.useGpCalcView)(),a=I();return(0,i.useMemo)(()=>{if(!e||!a||!(0,p.cardCostsVisible)(t,s))return null;const i=r?.[e.id];if(!i?.lines.length)return null;const o=(0,u.cardCostSummary)(i,n,l,e.price),d={};return o.lines.forEach(e=>{e.line.recipeIngId&&(d[e.line.recipeIngId]={cost:(d[e.line.recipeIngId]?.cost??0)+e.cost,label:e.label})}),{summary:o,byRecipeIng:d}},[e,t,s,a,n,l,r])},_e.CardGpPanel=function({card:e,actor:s,mode:n="edit"}){const{ingredients:l,settings:o,cardCosts:c,saveCardCost:g}=(0,d.useGpCalcView)(),h=I()&&(0,p.cardCostsVisible)(s.role,n),y=h&&'staff'!==s.role,w=c?.[e.id]??{lines:[],portions:1},P=(0,u.cardCostSummary)(w,l,o,e.price),[$,S]=(0,i.useState)(''),[D,k]=(0,i.useState)(),[M,G]=(0,i.useState)(!1),[B,V]=(0,i.useState)(w.menuPrice?(w.menuPrice/100).toFixed(2):''),[z,W]=(0,i.useState)(!1),[F,E]=(0,i.useState)(null),[U,H]=(0,i.useState)(!w.lines.length),[q,_]=(0,i.useState)(!1),[Y,X]=(0,i.useState)(null!=w.target?String(w.target):'');if(!h)return null;const K=t=>g(e.id,{...d.useGpCalc.getState().cardCosts[e.id]??w,...t}),J=(e,t)=>{if(t){const s=(0,b.suggestAmount)(t.qty,t.unit,e);if(s.qty>0)return s}const s=e.servings?'serving':(0,u.unitsFor)(e.packUnit)[0];return{qty:'serving'===s||'each'===s?1:0,unit:s}},Q=(t,s=D)=>{const i=e.ingredients.find(e=>e.id===s),n={ingId:t.id,...J(t,i),...s?{recipeIngId:s}:{}},l=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...l.lines,n]}),S(''),k(void 0),G(!1),_(!1)},Z=(e,t)=>K({lines:w.lines.map((s,i)=>i===e?{...s,...t}:s)}),ee=new Set(w.lines.map(e=>e.recipeIngId).filter(Boolean)),te=e.ingredients.filter(e=>e.name.trim()&&!ee.has(e.id)),se=te.map(e=>({ri:e,i:(0,b.matchIngredient)(e.name,l)})).filter(e=>!!e.i),ie=P.price?P.price/(1+o.vatPct/100):null,ne=l.filter(e=>!$.trim()||$.trim().toLowerCase().split(/\s+/).some(t=>t.length>2&&e.name.toLowerCase().includes(t))||e.name.toLowerCase().includes($.trim().toLowerCase())).slice(0,12),le=v(B),re=P.tone?T[P.tone]:x.colours.muted,ae=null!=e.price&&P.price===e.price;return(0,f.jsxs)(r.default,{testID:"card-gp",accessibilityLabel:"GP calculator",style:{width:'100%',gap:10,padding:14,borderRadius:18,borderWidth:1.5,borderColor:x.colours.gold,backgroundColor:N},children:[(0,f.jsx)(a.T,{size:20,weight:"bold",center:!0,colour:x.colours.gold,accessibilityRole:"header",children:"GP calculator"}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["Costs from the price list (latest delivery prices) \xb7 target ",P.target,"% GP"]}),P.price?(0,f.jsxs)(r.default,{testID:"gp-vat-line",accessible:!0,accessibilityLabel:`Menu price ${(0,u.money)(P.price)} including VAT, ${(0,u.money)(ie)} without VAT. GP is worked out on the price without VAT.`,style:{alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,weight:"semibold",children:[(0,u.money)(P.price)," inc VAT \xb7 ",(0,u.money)(ie)," ex VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:[P.priceIsSuggested?'Suggested price':w.menuPrice?'The price you typed':'Menu price on the card'," \xb7 GP is on the ex-VAT price"]})]}):null,w.lines.length?(0,f.jsx)(r.default,{testID:"card-gp-lines",style:{gap:8},children:P.lines.map((e,s)=>{const i=l.find(t=>t.id===e.line.ingId);return(0,f.jsxs)(r.default,{testID:"card-gp-line",style:{gap:6,paddingVertical:8,borderTopWidth:s?1:0,borderColor:x.colours.accentBorder},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}, ${e.label}, ${i?`${(0,u.money)(e.cost)}, ${(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}`:'not on the price list'}`,style:{flexDirection:'row',gap:8,alignItems:'center',minHeight:32},children:[(0,f.jsxs)(r.default,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(a.T,{weight:"medium",children:e.name}),(0,f.jsx)(a.T,{size:x.font.small,colour:x.colours.muted,children:e.label}),i?(0,f.jsx)(a.T,{testID:"card-gp-line-rates",size:x.font.small,colour:x.colours.goldLight,children:(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}):null]}),(0,f.jsx)(a.T,{weight:"semibold",colour:i?x.colours.goldLight:x.colours.amber,children:i?(0,u.money)(e.cost):'Removed'})]}),U&&y&&i?(()=>{const n=(0,u.unitsFor)(i.packUnit,i.servings),l=t=>(0,f.jsx)(R,{testID:`gp-unit-${s}-${t}`,label:'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2),accessibilityLabel:`${e.name} by ${'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2)}`,selected:e.line.unit===t,onPress:()=>Z(s,{unit:t})},t);return(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:`gp-qty-${s}`,accessibilityLabel:`Amount of ${e.name}`,value:e.line.qty?String(e.line.qty):'',onChangeText:e=>Z(s,{qty:C(e)??0}),placeholder:"amount",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),n.slice(0,-1).map(l),(0,f.jsxs)(r.default,{testID:`gp-unit-end-${s}`,style:{flexDirection:'row',flexWrap:'nowrap',alignItems:'center',gap:6},children:[n.slice(-1).map(l),(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})]})]})})():U&&y?(0,f.jsx)(a.Row,{gap:6,style:{justifyContent:'center'},children:(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})}):null]},s)})}):(0,f.jsx)(r.default,{testID:"card-gp-empty",style:{alignItems:'center',paddingVertical:6},children:(0,f.jsxs)(a.T,{center:!0,colour:x.colours.goldLight,children:["Not costed yet.",y?' Add the ingredients from your price list below.':'']})}),y&&w.lines.length?(0,f.jsx)(a.Button,{small:!0,kind:U?'primary':'secondary',testID:"gp-edit",label:U?'Done':'Change amounts or ingredients',accessibilityLabel:U?'Done changing the costing':`Change the costing for ${e.dish}`,onPress:()=>{H(!U),G(!1)}}):null,y&&U?(0,f.jsxs)(r.default,{style:{gap:8,alignItems:'center'},children:[se.length?(0,f.jsx)(a.Button,{testID:"gp-link-all",label:`Link ${se.length} matching price${1===se.length?'':'s'}`,accessibilityLabel:`Link ${se.length} of this card's ingredients to matching items on the price list`,onPress:()=>{const t=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...t.lines,...se.map(({ri:e,i:t})=>({ingId:t.id,...J(t,e),recipeIngId:e.id}))]}),E(`Linked ${se.length} ingredient${1===se.length?'':'s'} to the price list. Check the amounts below.`)},style:{minHeight:52}}):null,te.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Cost this card\u2019s ingredients"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:te.slice(0,10).map(e=>(0,f.jsx)(R,{testID:`gp-cost-${e.id}`,label:e.name.split(',')[0].slice(0,28),accessibilityLabel:`Cost ${e.name}`,selected:D===e.id,onPress:()=>{k(e.id),S(e.name.split(/[,(]/)[0].trim()),G(!0)}},e.id))})]}):null,M?(0,f.jsxs)(r.default,{style:{width:'100%',gap:6},children:[(0,f.jsx)(t.TextInput,{testID:"gp-search",accessibilityLabel:"Search ingredient prices",value:$,onChangeText:S,placeholder:"Search the price list",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[ne.map(e=>{const t=(0,u.perServing)(e),s=(0,u.perBaseUnit)(e),i=null!=t?`${(0,u.money)(t)} a ${(0,u.servingWord)(e,1)}`:s?`${(0,u.money)(s.pence)} a ${s.per}`:(0,u.money)(e.packPrice);return(0,f.jsx)(R,{testID:`gp-pick-${e.id}`,label:`${e.name} \xb7 ${i}`,accessibilityLabel:`Add ${e.name}, ${i}`,onPress:()=>Q(e)},e.id)}),ne.length?null:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:l.length?'Nothing on the price list matches.':'The price list is empty. Add a price here, or record a delivery.'})]}),q?(0,f.jsx)(A,{initial:$.trim(),onDone:e=>{_(!1);const t=e?d.useGpCalc.getState().ingredients.find(t=>t.id===e):void 0;t&&Q(t)}}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add-price",label:$.trim()?`Add a price for ${$.trim().slice(0,30)}`:'Add a new price',accessibilityLabel:`Add ${$.trim()||'a new ingredient'} to the price list and cost it on this card`,onPress:()=>_(!0)}),(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>{G(!1),k(void 0),S(''),_(!1)}})]}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add",kind:"secondary",label:"Add from ingredient prices",onPress:()=>{G(!0),k(void 0)}}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Target GP %"}),(0,f.jsx)(t.TextInput,{testID:"gp-target",accessibilityLabel:`Target GP percent for this dish, now ${P.target}`,value:Y,onChangeText:e=>{X(e);const t=C(e);null!=t&&t>0&&t<95?K({target:t}):e.trim()||K({target:void 0})},placeholder:String(o.defaultTarget),placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{testID:"gp-portions",accessibilityLabel:"Portions this recipe makes",value:String(w.portions||1),onChangeText:e=>K({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]})]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost",label:"Food cost per portion",value:(0,u.money)(P.perPortion),colour:x.colours.goldLight,sub:(w.portions||1)>1?`Batch ${(0,u.money)(P.batch)} \xf7 ${w.portions}`:P.missing?`${P.missing} line${1===P.missing?'':'s'} not costed`:void 0}),(0,f.jsx)(O,{testID:"gp-suggested",label:`Suggested at ${P.target}% GP`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?"inc VAT"+(o.pricePoints?', rounded up':''):'Add amounts first'})]}),y?(0,f.jsxs)(r.default,{style:{gap:6,alignItems:'center'},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Your menu price (inc VAT)"}),(0,f.jsxs)(a.Row,{gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{size:24,style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{testID:"gp-price",accessibilityLabel:"Your menu price in pounds, including VAT",value:B,onChangeText:e=>{const t=(0,j.sanitiseMoneyTyping)(e);V(t);const s=v(t);null!=s&&s>0?K({menuPrice:s}):t.trim()||K({menuPrice:void 0})},placeholder:P.price?(P.price/100).toFixed(2):'0.00',placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{minHeight:56,width:150,fontSize:24,textAlign:'center'}]})]}),(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:le?'GP below uses the price you typed.':e.price?`Blank uses the menu price, ${(0,u.money)(e.price)}.`:'Blank uses the suggested price.'}),P.suggested&&!le?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:"gp-use-suggested",label:`Use suggested ${(0,u.money)(P.suggested)}`,accessibilityLabel:`Use the suggested price, ${(0,u.money)(P.suggested)}`,onPress:()=>{V((P.suggested/100).toFixed(2)),K({menuPrice:P.suggested})}}):null]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-gp",label:`GP on ${P.price?(0,u.money)(P.price):'the price'}`,value:null!=P.gp?(0,u.pct)(P.gp):'\u2014',colour:re,sub:null!=P.gp?'ok'===P.tone?'On target':'amber'===P.tone?'Just under target':'Below target':void 0}),(0,f.jsx)(O,{testID:"gp-cash",label:"Cash GP per portion",value:null!=P.cashGp?(0,u.money)(P.cashGp):'\u2014',colour:re,sub:P.price?`${(0,u.money)(P.price/(1+o.vatPct/100))} ex VAT`:void 0})]}),(()=>{const e=(0,u.foodCostTargetOf)(P.target),t=null!=P.foodCostPct?(0,u.foodCostTone)(P.foodCostPct,e):null,s=t?T[t]:x.colours.muted,i=P.price&&P.perPortion>0?(0,u.vatAwareGp)(P.perPortion,P.price,o.vatPct):null;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost-pct",label:"Food cost %",value:null!=P.foodCostPct?(0,u.pct)(P.foodCostPct):'\u2014',colour:s,sub:null!=P.foodCostPct?`Target ${e}% \xb7 ${'ok'===t?'on target':'amber'===t?'just over':'over target'}`:`Target ${e}%`}),(0,f.jsx)(O,{testID:"gp-suggested-target",label:`Price for ${e}% food cost`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?'inc VAT':'Add amounts first'})]}),i?(0,f.jsxs)(r.default,{testID:"gp-vat-aware",accessible:!0,accessibilityLabel:`VAT ${(0,u.money)(i.vatPence)} of the ${(0,u.money)(P.price)} goes to the tax office. GP on the price without VAT is ${(0,u.pct)(i.gpPct)}. With VAT left in it would wrongly look like ${(0,u.pct)(i.naiveGpPct)}.`,style:{alignItems:'center',gap:2},children:[(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["VAT ",o.vatPct,"%: ",(0,u.money)(i.vatPence)," of each ",(0,u.money)(P.price)," is VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:["True GP ",(0,u.pct)(i.gpPct)," (ex VAT) \xb7 would look like ",(0,u.pct)(i.naiveGpPct)," with VAT left in"]})]}):null]})})(),y&&P.price&&!ae?z?(0,f.jsxs)(r.default,{testID:"gp-menu-confirm",style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Put ",(0,u.money)(P.price)," on the menu? The card goes back to Awaiting sign-off until a chef signs it again."]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"gp-menu-yes",label:`Yes, use ${(0,u.money)(P.price)}`,onPress:async()=>{if(P.price)try{await(0,m.recipeCards)().update(e.id,{price:P.price},s),E(`Menu price set to ${(0,u.money)(P.price)}. The card now waits for sign-off again.`),W(!1)}catch(e){E(e?.message??'Could not change the menu price.')}}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Not now",onPress:()=>W(!1)})]})]}):(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:"gp-menu",label:`Use ${(0,u.money)(P.price)} on the menu`,accessibilityLabel:`Use ${(0,u.money)(P.price)} as the menu price for ${e.dish}`,onPress:()=>W(!0)}):null,F?(0,f.jsx)(a.T,{center:!0,size:x.font.small,colour:x.colours.goldLight,children:F}):null,(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"GP is worked out on the price without VAT. Only the Head Chef and managers see costs."})]})};var t=_r(_d[0]),s=_r(_d[1]),i=_r(_d[2]),n=e(_r(_d[3]));_r(_d[4]);var l=e(_r(_d[5])),r=e(_r(_d[6])),a=_r(_d[7]),o=_r(_d[8]),d=_r(_d[9]),c=_r(_d[10]),u=_r(_d[11]),p=_r(_d[12]),g=_r(_d[13]),h=_r(_d[14]),m=_r(_d[15]),x=_r(_d[16]),y=_r(_d[17]),b=_r(_d[18]),j=_r(_d[19]),f=_r(_d[20]);const w='New dish creator',T={ok:x.colours.ok,amber:x.colours.amber,red:x.colours.red},v=e=>{const t=(0,j.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):null},C=e=>{const t=e.trim().replace(',','.');return/^\d*\.?\d+$/.test(t)?Number(t):null},P=e=>({id:(0,d.gid)('gd'),name:'',lines:[],portions:1,target:e,status:'draft',allergens:[],description:''});function I(){const e=(0,h.useSession)(e=>e.meId),t=(0,g.useOwner)(t=>e?t.staff.find(t=>t.id===e):void 0);return!e||!!t&&t.active&&(0,p.costsAllowedFor)(t)}function $({n:e,title:t,children:s,testID:i}){return(0,f.jsxs)(y.Box,{testID:i,children:[(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(r.default,{style:{width:30,height:30,borderRadius:15,backgroundColor:x.colours.gold,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.onGold,children:e})}),(0,f.jsx)(a.T,{size:18,weight:"semibold",style:{flex:1},children:t})]}),s]})}function S({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n}){return(0,f.jsxs)(r.default,{testID:i,style:{flexGrow:1,flexBasis:140,padding:12,borderRadius:14,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border,gap:2},children:[(0,f.jsx)(a.Muted,{children:e}),(0,f.jsx)(a.T,{size:30,weight:"bold",colour:s,children:t}),n?(0,f.jsx)(a.Muted,{children:n}):null]})}function D({draft:e,setDraft:n,onNew:l,onSaved:o}){const{ingredients:p,dishes:g,settings:h,saveDish:m}=(0,d.useGpCalcView)(),[b,w]=(0,i.useState)(''),[P,I]=(0,i.useState)(!1),[D,L]=(0,i.useState)(''),[R,M]=(0,i.useState)(e.menuPrice?'price':'gp'),[G,B]=(0,i.useState)(e.menuPrice?(e.menuPrice/100).toFixed(2):''),[V,z]=(0,i.useState)(String(e.target)),[W,N]=(0,i.useState)(String(e.targetX??4)),O=t=>n({...e,...t}),F=g.filter(t=>t.id!==e.id),E=(0,u.portionCost)(e,p,g),U=h.vatPct,H=C(V)??e.target,q=C(W)??4,_='price'===R?v(G):E>0?'gp'===R?(0,u.suggestPrice)(E,H,U,h.pricePoints):(0,u.suggestForMultiple)(E,q,U,h.multipleBasis,h.pricePoints):null,Y=_?(0,u.gpOf)(E,_,U):null,X=_?(0,u.multipleOf)(E,_,U,h.multipleBasis):0,K=Y?(0,u.toneFor)(Y.gpPct,H):'ok',J=(0,u.suggestAllergens)(e,p,g),Q=t=>{const s=p.find(e=>e.id===t),i=t.startsWith('dish:')?'each':(0,u.unitsFor)(s.packUnit,s.servings)[0],l=[...e.lines,{ingId:t,qty:t.startsWith('dish:')?1:0,unit:i}],r={...e,lines:l},a=(0,u.suggestAllergens)(r,p,g);n({...r,allergens:Array.from(new Set([...e.allergens??[],...a]))})},Z=(t,s)=>O({lines:e.lines.map((e,i)=>i===t?{...e,...s}:e)}),ee=p.filter(e=>!b.trim()||e.name.toLowerCase().includes(b.trim().toLowerCase())),te=t=>{if(!e.name.trim())return L('Give the dish a name first.');if('ready'===t){if(!e.category)return L('Pick a category to make it menu-ready.');if(!e.lines.length||E<=0)return L('Add ingredients with quantities to make it menu-ready.');if(!_)return L('Set a price to make it menu-ready.')}const s='published'===e.status?'published':t;m({...e,name:e.name.trim(),target:H,targetX:q,menuPrice:_??void 0,status:s}),L('ready'===t?`Saved \u201c${e.name.trim()}\u201d as menu-ready. A manager can publish it to the menu.`:`Saved \u201c${e.name.trim()}\u201d as a draft.`)};return(0,f.jsxs)(r.default,{style:{gap:12},children:[(0,f.jsxs)($,{n:1,title:"Name and category",testID:"step-name",children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:"Dish name",value:e.name,onChangeText:e=>O({name:e.slice(0,60)}),placeholder:"e.g. Cullen skink",placeholderTextColor:"#7D776C",style:[a.styles.input,{fontSize:20}]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:u.DISH_CATEGORIES.map(t=>(0,f.jsx)(a.Chip,{label:t,selected:e.category===t,onPress:()=>O({category:t})},t))})]}),(0,f.jsxs)($,{n:2,title:"Add saved items and ingredients",testID:"step-ingredients",children:[F.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.Muted,{children:"Saved items (tap to add a portion)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:F.map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(`dish:${e.id}`)},e.id))})]}):null,(0,f.jsx)(a.Muted,{children:"Ingredients"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredients",value:b,onChangeText:w,placeholder:"Search ingredients",placeholderTextColor:"#7D776C",style:a.styles.input}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[ee.slice(0,24).map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(e.id)},e.id)),(0,f.jsx)(a.Chip,{label:"New ingredient",onPress:()=>I(!0)})]}),P?(0,f.jsx)(A,{initial:b,onDone:e=>{I(!1),w(''),e&&Q(e)}}):null,e.lines.length?(0,f.jsx)(r.default,{style:{gap:8},testID:"dish-lines",children:e.lines.map((i,n)=>{const l=i.ingId.startsWith('dish:'),o=p.find(e=>e.id===i.ingId),d=(c=i.ingId).startsWith('dish:')?g.find(e=>e.id===c.slice(5))?.name??'Saved item':p.find(e=>e.id===c)?.name??'?';var c;return(0,f.jsxs)(r.default,{testID:"dish-line",style:{gap:6,padding:10,borderRadius:12,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between'},children:[(0,f.jsxs)(a.T,{weight:"medium",style:{flex:1},children:[d,l?' (saved item)':'']}),(0,f.jsx)(a.T,{weight:"semibold",children:(0,u.money)((0,u.lineCost)(i,p,g))}),(0,f.jsx)(s.GoldClose,{size:"sm",label:`Remove ${d}`,onPress:()=>O({lines:e.lines.filter((e,t)=>t!==n)})})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Quantity of ${d}`,value:i.qty?String(i.qty):'',onChangeText:e=>Z(n,{qty:C(e)??0}),placeholder:"qty",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:90}]}),l?(0,f.jsx)(a.Muted,{children:"portion(s)"}):(0,u.unitsFor)(o.packUnit,o.servings).map(e=>(0,f.jsx)(a.Chip,{label:'serving'===e?(0,u.servingWord)(o,2):(0,u.unitName)(e,2),selected:i.unit===e,onPress:()=>Z(n,{unit:e})},e)),l?null:(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${d}`,value:null==i.wastePct?'':String(i.wastePct),onChangeText:e=>Z(n,{wastePct:''===e.trim()?void 0:C(e)??0}),placeholder:`waste ${o.wastePct}%`,placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:110}]})]})]},n)})}):(0,f.jsx)(a.Muted,{children:"Nothing added yet. Tap a saved item or an ingredient above."}),(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Portions per batch",value:String(e.portions),onChangeText:e=>O({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,{width:80,textAlign:'center'}]})]}),(0,f.jsx)(S,{testID:"cost-per-plate",label:"Cost per plate",value:(0,u.money)(E),sub:e.portions>1?`Batch cost ${(0,u.money)(E*e.portions)} \xf7 ${e.portions}`:'Live: updates as you type'})]}),(0,f.jsxs)($,{n:3,title:"Price it",testID:"step-price",children:[(0,f.jsx)(y.Tabs,{value:R,onChange:M,options:[{id:'gp',label:'Target GP %'},{id:'x',label:'Target multiple'},{id:'price',label:'Type a price'}]}),'gp'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[65,70,75].map(e=>(0,f.jsx)(a.Chip,{label:`${e}%`,selected:H===e,onPress:()=>z(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target GP %",value:V,onChangeText:z,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'x'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[3,4,5].map(e=>(0,f.jsx)(a.Chip,{label:`${e}x`,selected:q===e,onPress:()=>N(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target multiple",value:W,onChangeText:N,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'price'===R?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{size:24,children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Menu price (inc VAT)",value:G,onChangeText:e=>B((0,j.sanitiseMoneyTyping)(e)),placeholder:"0.00",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{width:140,fontSize:24}]}),(0,f.jsx)(a.Muted,{children:"inc VAT"})]}):null,'price'!==R?(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"suggested-price",label:`Suggested menu price (inc ${U}% VAT)`,value:_?(0,u.money)(_):'\u2014',colour:x.colours.gold,sub:_?`${(0,u.money)(_/(1+U/100))} ex VAT${h.pricePoints?' \xb7 rounded up to .50 / .95':''}`:'Add ingredients first'}),_?(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Type my own price",onPress:()=>{B((_/100).toFixed(2)),M('price')}}):null]}):null,(()=>{const t=(0,u.avgMenuPrice)(g,e.category,e.id);return e.category?(0,f.jsx)(r.default,{testID:"avg-menu-price",children:(0,f.jsx)(a.Muted,{children:t?`Average menu price for ${e.category}: ${(0,u.money)(t.avg)} (${t.count} dish${1===t.count?'':'es'})${_?` \xb7 this dish ${_>=t.avg?'+':'\u2212'}${(0,u.money)(Math.abs(_-t.avg))}`:''}`:`No other priced ${e.category.toLowerCase()} yet to compare with.`})}):null})(),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"big-gp",label:`GP (target ${H}%)`,value:Y?(0,u.pct)(Y.gpPct):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-x",label:`Multiple (${'inc'===h.multipleBasis?'inc VAT price':'ex VAT price'} \xf7 cost)`,value:Y&&E>0?(0,u.fmtX)(X):'\u2014',colour:x.colours.gold}),(0,f.jsx)(S,{testID:"big-profit",label:"Profit per plate (cash GP)",value:Y?(0,u.money)(Y.cashGp):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-foodcost",label:"Food cost",value:Y?(0,u.pct)(Y.foodCostPct):'\u2014'})]}),(0,f.jsxs)(a.Muted,{children:["GP is worked out on the price without VAT (",U,"% VAT). Gold: at or above target \xb7 amber: up to 5 points under \xb7 red: more than 5 under."]})]}),(0,f.jsxs)($,{n:4,title:"Photo, allergens and description",testID:"step-details",children:[(0,f.jsx)(k,{value:e.photo,onChange:e=>O({photo:e})}),(0,f.jsx)(a.T,{weight:"medium",children:"Allergens (14 UK allergens)"}),J.length?(0,f.jsx)(r.default,{testID:"allergen-suggest",children:(0,f.jsxs)(a.Muted,{children:["Suggested from the ingredients: ",J.map(e=>c.ALLERGENS.find(t=>t.id===e).short).join(', '),". Check before it goes on the menu."]})}):(0,f.jsx)(a.Muted,{children:"No allergens known from these ingredients yet. Tick any that apply."}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:c.ALLERGENS.map(t=>{const s=(e.allergens??[]).includes(t.id);return(0,f.jsx)(a.Chip,{label:`${s?'\u2713 ':''}${t.short}`,sub:J.includes(t.id)?'suggested':void 0,selected:s,onPress:()=>O({allergens:s?e.allergens.filter(e=>e!==t.id):[...e.allergens??[],t.id]})},t.id)})}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Short description",value:e.description??'',onChangeText:e=>O({description:e.slice(0,160)}),multiline:!0,placeholder:"Short description for the menu (up to 160 characters)",placeholderTextColor:"#7D776C",style:[a.styles.input,{minHeight:70,textAlignVertical:'top'}]}),(0,f.jsxs)(a.Muted,{children:[(e.description??'').length,"/160"]})]}),(0,f.jsxs)($,{n:5,title:"Save",testID:"step-save",children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(a.Button,{label:"Save as draft",kind:"secondary",testID:"save-draft",onPress:()=>te('draft'),style:{flexGrow:1}}),(0,f.jsx)(a.Button,{label:"Save as menu-ready dish",testID:"save-ready",onPress:()=>te('ready'),style:{flexGrow:1}})]}),D?(0,f.jsx)(r.default,{testID:"creator-msg",children:(0,f.jsx)(a.T,{size:15,colour:D.startsWith('Saved')?x.colours.ok:x.colours.amber,children:D})}):null,D.startsWith('Saved')?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.Button,{small:!0,label:"See saved dishes",onPress:o}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Start a new dish",onPress:()=>{l(),L(''),B(''),M('gp')}})]}):null]})]})}function k({value:e,onChange:t}){return(0,f.jsxs)(a.Row,{gap:10,children:[e?(0,f.jsx)(n.default,{testID:"dish-photo",source:{uri:e},style:{width:96,height:72,borderRadius:10}}):(0,f.jsx)(r.default,{style:{width:96,height:72,borderRadius:10,borderWidth:1,borderStyle:'dashed',borderColor:x.colours.border,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.Muted,{children:"No photo"})}),(0,f.jsxs)(r.default,{style:{gap:6},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:e?'Change photo':'Add photo (optional)',onPress:()=>{if('undefined'==typeof document)return;const e=document.createElement('input');e.type='file',e.accept='image/*',e.onchange=()=>{const s=e.files?.[0];if(!s)return;const i=new FileReader;i.onload=()=>{const e=new window.Image;e.onload=()=>{const s=Math.min(1,480/Math.max(e.width,e.height)),i=document.createElement('canvas');i.width=Math.round(e.width*s),i.height=Math.round(e.height*s),i.getContext('2d').drawImage(e,0,0,i.width,i.height),t(i.toDataURL('image/jpeg',.8))},e.src=String(i.result)},i.readAsDataURL(s)},e.click()}}),e?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Remove photo",onPress:()=>t(void 0)}):null]})]})}function A({initial:e,onDone:s,edit:n}){const[l,o]=(0,i.useState)(n?.name??e),[p,g]=(0,i.useState)(n?String(n.packSize):''),[h,m]=(0,i.useState)(n?.packUnit??'kg'),[y,b]=(0,i.useState)(n?(n.packPrice/100).toFixed(2):''),[w,T]=(0,i.useState)(n?.wastePct?String(n.wastePct):''),[P,I]=(0,i.useState)(n?.allergens??[]),[$,S]=(0,i.useState)(n?.servings?String(n.servings):''),[D,k]=(0,i.useState)(n?.servingName??''),[A,M]=(0,i.useState)(n?.supplier??''),G=!(!l.trim()||!C(p)||null==v(y)||''!==$.trim()&&!C($)),B={id:'probe',name:l,packSize:C(p)??0,packUnit:h,packPrice:v(y)??0,wastePct:0,servings:C($)??void 0,servingName:D.trim()||void 0},V=B.packSize&&B.packPrice?(0,u.perBaseUnit)(B):null,z=B.packPrice?(0,u.perServing)(B):null,W={name:l.trim(),packSize:C(p),packUnit:h,packPrice:v(y),wastePct:Math.min(90,C(w)??0),allergens:P,servings:C($)??void 0,servingName:D.trim().toLowerCase()||void 0,supplier:A.trim()||void 0};return(0,f.jsxs)(r.default,{testID:n?`edit-ingredient-${n.id}`:'new-ingredient',style:{gap:8,padding:12,borderRadius:14,borderWidth:1,borderColor:x.colours.gold,width:'100%'},children:[(0,f.jsx)(a.T,{weight:"semibold",center:!0,accessibilityRole:"header",children:n?`Edit ${n.name}`:'New ingredient'}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Ingredient name",value:l,onChangeText:o,placeholder:"e.g. Haddock",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Pack price and what you get for it, e.g. \xa3110 for 1 stone, or \xa340 for 5 kg"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:"ing-pack-price",accessibilityLabel:"Pack price in pounds",value:y,onChangeText:e=>b((0,j.sanitiseMoneyTyping)(e)),placeholder:"\xa3 price",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110,textAlign:'center'}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"for"}),(0,f.jsx)(t.TextInput,{testID:"ing-pack-size",accessibilityLabel:"Pack size",value:p,onChangeText:g,placeholder:"size",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]})]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:u.PACK_UNITS.map(e=>(0,f.jsx)(R,{testID:`ing-unit-${e}`,label:(0,u.unitName)(e,2),selected:h===e,onPress:()=>m(e)},e))}),(0,f.jsx)(a.Muted,{center:!0,children:"Optional: roughly how many servings or pieces one pack gives"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"averages"}),(0,f.jsx)(t.TextInput,{testID:"ing-servings",accessibilityLabel:"Averages how many servings or pieces",value:$,onChangeText:S,placeholder:"e.g. 30",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),(0,f.jsx)(t.TextInput,{testID:"ing-serving-name",accessibilityLabel:"What one is called, for example serving, breast or piece",value:D,onChangeText:k,placeholder:"serving / breast",placeholderTextColor:"#7D776C",style:[a.styles.input,L,{width:150,textAlign:'center'}]})]}),V||null!=z?(0,f.jsx)(r.default,{testID:"ing-derived",accessible:!0,accessibilityLabel:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(', '),children:(0,f.jsx)(a.T,{center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(' \xb7 ')})}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Supplier (optional)",value:A,onChangeText:M,placeholder:"Supplier (optional)",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Yield loss or waste percent (optional)",value:w,onChangeText:T,placeholder:"Trim / waste % (optional, for weights)",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Allergens in this ingredient (if known)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:c.ALLERGENS.map(e=>(0,f.jsx)(a.Chip,{label:e.short,selected:P.includes(e.id),onPress:()=>I(P.includes(e.id)?P.filter(t=>t!==e.id):[...P,e.id])},e.id))}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"ing-save",label:n?'Save ingredient':'Add ingredient',disabled:!G,onPress:()=>{if(n){const e=d.useGpCalc.getState();W.packPrice!==n.packPrice&&e.addPricePaid(n.id,W.packPrice);const t=d.useGpCalc.getState().ingredients.find(e=>e.id===n.id)??n;e.saveIngredient({...t,...W,packPrice:t.packPrice}),s(n.id)}else s(d.useGpCalc.getState().addIngredient(W))}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Cancel",onPress:()=>s()})]})]})}const L={minHeight:48};function R({label:e,selected:t,onPress:s,testID:i,accessibilityLabel:n}){return(0,f.jsx)(l.default,{testID:i,accessibilityRole:"button",accessibilityState:{selected:!!t},accessibilityLabel:`${n??e}${t?', selected':''}`,onPress:s,style:{minHeight:48,minWidth:48,paddingHorizontal:14,justifyContent:'center',alignItems:'center',borderRadius:24,borderWidth:1,borderColor:t?x.colours.gold:x.colours.border,backgroundColor:t?x.colours.gold:x.colours.surface2,maxWidth:'100%'},children:(0,f.jsx)(a.T,{size:x.font.small,weight:"medium",center:!0,colour:t?x.colours.onGold:x.colours.text,children:e})})}const M={draft:{label:'Draft',kind:'neutral'},ready:{label:'Menu-ready',kind:'gold'},published:{label:'On the menu',kind:'ok'}};function G({rid:e,canPublish:t,onEdit:s}){const{dishes:n,ingredients:l,settings:c,saveDish:p}=(0,d.useGpCalcView)(),[g,h]=(0,i.useState)('low'),[m,b]=(0,i.useState)(''),j=(0,i.useMemo)(()=>n.map(e=>{const t=(0,u.portionCost)(e,l,n);return{d:e,cost:t,g:e.menuPrice?(0,u.gpOf)(t,e.menuPrice,c.vatPct):null,x:e.menuPrice?(0,u.multipleOf)(t,e.menuPrice,c.vatPct,c.multipleBasis):0}}).sort((e,t)=>(e.g?e.g.gpPct:999)-(t.g?t.g.gpPct:999)),[n,l,c]),w='low'===g?j:[...j].reverse(),v=j.filter(e=>e.g&&e.g.gpPct{const s={};(t.allergens??[]).forEach(e=>{s[e]='contains'});const i=o.useStore.getState().addMenuItem({restaurantId:e,section:t.category??'Specials',name:t.name,description:t.description??'',price:t.menuPrice??null,dietary:[],allergens:s,prepMins:12,soldOut:!1,signOff:null});p({...t,status:'published',menuItemId:i}),b(`Published \u201c${t.name}\u201d to the menu (${t.category??'Specials'}). It needs allergen sign-off in Menu & allergens.`)};return(0,f.jsxs)(y.Box,{testID:"menu-gp",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"Saved dishes and items \xb7 Menu GP"}),(0,f.jsxs)(a.Muted,{children:[j.length," saved \xb7 ",v," below target \xb7 multiples on the ",'inc'===c.multipleBasis?'inc-VAT menu price':'ex-VAT price']}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Lowest GP first",selected:'low'===g,onPress:()=>h('low')}),(0,f.jsx)(a.Chip,{label:"Highest GP first",selected:'high'===g,onPress:()=>h('high')})]}),w.map(({d:e,cost:i,g:n,x:l})=>{const o=n?(0,u.toneFor)(n.gpPct,e.target):null;return(0,f.jsxs)(r.default,{testID:"gp-row",style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:4},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between',alignItems:'flex-start'},children:[(0,f.jsxs)(r.default,{style:{flex:1,gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",children:e.name}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Badge,{kind:M[e.status??'draft'].kind,label:M[e.status??'draft'].label}),e.category?(0,f.jsx)(a.Muted,{children:e.category}):null]}),(0,f.jsxs)(a.Muted,{children:["Cost ",(0,u.money)(i),e.menuPrice?` \xb7 price ${(0,u.money)(e.menuPrice)}`:' \xb7 no price yet']})]}),(0,f.jsxs)(r.default,{style:{alignItems:'flex-end'},children:[(0,f.jsx)(a.T,{size:22,weight:"bold",colour:o?T[o]:x.colours.muted,children:n?(0,u.pct)(n.gpPct):'\u2014'}),(0,f.jsx)(a.T,{size:16,weight:"semibold",colour:x.colours.gold,children:n&&i>0?(0,u.fmtX)(l):''})]})]}),n&&n.gpPcts(e)}),t&&'ready'===e.status?(0,f.jsx)(a.Button,{small:!0,label:"Publish to menu",accessibilityLabel:`Publish ${e.name} to menu`,onPress:()=>C(e)}):null,t||'ready'!==e.status?null:(0,f.jsx)(a.Muted,{children:"Waiting for a manager to publish"})]})]},e.id)}),m?(0,f.jsx)(r.default,{testID:"publish-msg",children:(0,f.jsx)(a.T,{size:14,colour:x.colours.ok,children:m})}):null]})}function B(){const{settings:e,setSettings:t}=(0,d.useGpCalcView)(),s=e.priceBasis??'latest',i=e.avgOf??5;return(0,f.jsxs)(r.default,{testID:"price-basis",style:{gap:6},children:[(0,f.jsx)(a.T,{weight:"medium",children:"Cost dishes using"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Chip,{label:"Latest price paid",selected:'latest'===s,onPress:()=>t({priceBasis:'latest'})}),(0,f.jsx)(a.Chip,{label:`Average price (last ${i})`,selected:'average'===s,onPress:()=>t({priceBasis:'average'})})]}),'average'===s?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Muted,{children:"Average of the last"}),[3,5,10].map(e=>(0,f.jsx)(a.Chip,{label:`${e} prices`,selected:i===e,onPress:()=>t({avgOf:e})},e))]}):null,(0,f.jsx)(a.Muted,{children:'average'===s?'Averages smooth out price swings, so GP doesn\u2019t jump every delivery.':'Uses the most recent price you paid.'})]})}function V(){const{ingredients:e,dishes:s,settings:n,cardCosts:l}=(0,d.useGpCalcView)(),[o,c]=(0,i.useState)(''),[u,p]=(0,i.useState)(''),[g,h]=(0,i.useState)(!1),m=e.filter(e=>!u.trim()||`${e.name} ${e.supplier??''}`.toLowerCase().includes(u.trim().toLowerCase())).slice().sort((e,t)=>e.name.localeCompare(t.name));return(0,f.jsxs)(y.Box,{testID:"calc-items",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",center:!0,accessibilityRole:"header",children:"Ingredient prices"}),(0,f.jsx)(a.Muted,{center:!0,children:"What you pay and what a pack gives you. Recipe cards and dishes cost themselves from this list and update when a price changes."}),(0,f.jsx)(a.Button,{testID:"ing-add-new",label:"Add an ingredient",onPress:()=>{h(!0),c('')}}),g?(0,f.jsx)(A,{initial:u,onDone:e=>{h(!1),e&&c('Added to the price list.')}}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredient prices",value:u,onChangeText:p,placeholder:"Search ingredients or suppliers",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(B,{}),m.map(e=>{return(0,f.jsx)(z,{i:e,n:n.avgOf??5,basis:n.priceBasis??'latest',used:(t=e.id,s.filter(e=>e.lines.some(e=>e.ingId===t)).length+Object.values(l??{}).filter(e=>e.lines.some(e=>e.ingId===t)).length),onSaved:e=>c(e)},e.id);var t}),m.length?null:(0,f.jsx)(r.default,{testID:"ing-empty",style:{alignItems:'center',paddingVertical:12},children:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:e.length?'No ingredients match.':'No ingredient prices yet. Add the first one above.'})}),o?(0,f.jsx)(r.default,{testID:"items-msg",children:(0,f.jsx)(a.T,{size:14,center:!0,colour:x.colours.ok,children:o})}):null]})}function z({i:e,used:s,n:n,basis:l,onSaved:o}){const[c,p]=(0,i.useState)(String(e.wastePct)),[g,h]=(0,i.useState)(''),[m,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(!1),T=(0,u.priceStats)(e,n),P=c!==String(e.wastePct),I=v(g),$=(0,u.perBaseUnit)(e),S=(0,u.perServing)(e),D=`${e.name}, ${(0,u.money)(e.packPrice)} for ${e.packSize} ${(0,u.unitName)(e.packUnit,e.packSize)}${e.servings?`, averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}, ${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:''}${$?`, ${(0,u.money)($.pence)} a ${$.per}`:''}${e.supplier?`, from ${e.supplier}`:''}`;return m?(0,f.jsx)(A,{initial:"",edit:e,onDone:t=>{y(!1),t&&o(`Saved ${e.name}. Recipe cards and dishes re-costed.`)}}):(0,f.jsxs)(r.default,{testID:`item-${e.id}`,style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:6},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:D,style:{gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",size:18,center:!0,children:e.name}),(0,f.jsxs)(a.T,{testID:`pack-${e.id}`,center:!0,colour:x.colours.goldLight,children:[(0,u.money)(e.packPrice)," for ",e.packSize," ",(0,u.unitName)(e.packUnit,e.packSize),e.servings?` \xb7 averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}`:'']}),(0,f.jsx)(a.T,{testID:`derived-${e.id}`,center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=S?`${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:'',$?`${(0,u.money)($.pence)} a ${$.per}`:''].filter(Boolean).join(' \xb7 ')}),(0,f.jsx)(a.Muted,{center:!0,children:[s?`used in ${s}`:'not used yet',e.supplier,e.updatedAt?`updated ${new Date(e.updatedAt).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:''].filter(Boolean).join(' \xb7 ')})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsxs)(r.default,{testID:`latest-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'latest'===l?x.colours.gold:x.colours.border},children:[(0,f.jsx)(a.Muted,{children:"Latest"}),(0,f.jsx)(a.T,{weight:"bold",children:(0,u.money)(T.latest)})]}),(0,f.jsxs)(r.default,{testID:`avg-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'average'===l?x.colours.gold:x.colours.border},children:[(0,f.jsxs)(a.Muted,{children:["Average (",T.count,")"]}),(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.gold,children:(0,u.money)(T.avg)})]}),T.count>1?(0,f.jsxs)(r.default,{style:{paddingHorizontal:10,paddingVertical:6},children:[(0,f.jsx)(a.Muted,{children:"Range"}),(0,f.jsxs)(a.T,{size:14,children:[(0,u.money)(T.min),"\u2013",(0,u.money)(T.max)]})]}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:`Price paid for ${e.name}`,value:g,onChangeText:e=>h((0,j.sanitiseMoneyTyping)(e)),placeholder:"price paid",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110}]}),(0,f.jsx)(a.Button,{small:!0,label:"Add price paid",testID:`add-price-${e.id}`,disabled:!I,onPress:()=>{d.useGpCalc.getState().addPricePaid(e.id,I),h(''),o(`Recorded ${(0,u.money)(I)} for ${e.name}. Dishes re-costed.`)}})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${e.name}`,value:c,onChangeText:p,keyboardType:"decimal-pad",style:[a.styles.input,L,{width:60}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"% waste"}),P?(0,f.jsx)(a.Button,{small:!0,label:"Save",disabled:null==C(c),onPress:()=>{d.useGpCalc.getState().saveIngredient({...e,wastePct:Math.min(90,C(c))}),o(`Saved ${e.name}. Dishes updated.`)}}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:`ing-edit-${e.id}`,label:"Edit",accessibilityLabel:`Edit ${e.name}`,onPress:()=>y(!0)}),b?null:(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:`ing-delete-${e.id}`,label:"Delete",accessibilityLabel:`Delete ${e.name}`,onPress:()=>w(!0)})]}),b?(0,f.jsxs)(r.default,{testID:`ing-delete-confirm-${e.id}`,style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Delete ",e.name," from the price list?",s?` ${s} ${1===s?'dish or card uses':'dishes or cards use'} it and will show it as removed.`:'']}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"danger",testID:`ing-delete-yes-${e.id}`,label:"Yes, delete",accessibilityLabel:`Yes, delete ${e.name}`,onPress:()=>{d.useGpCalc.getState().removeIngredient(e.id),o(`Deleted ${e.name}.`)}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Keep it",onPress:()=>w(!1)})]})]}):null]})}function W(){const{settings:e,setSettings:s}=(0,d.useGpCalcView)(),[n,l]=(0,i.useState)(String(e.vatPct)),[r,o]=(0,i.useState)(String(e.defaultTarget));return(0,f.jsxs)(y.Box,{testID:"calc-settings",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"VAT and rounding"}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"VAT rate %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"VAT rate %",value:n,onChangeText:e=>{l(e);const t=C(e);null!=t&&t<=50&&s({vatPct:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(B,{}),(0,f.jsx)(a.Toggle,{label:"Round suggested prices up to .50 / .95",value:e.pricePoints,onChange:e=>s({pricePoints:e})}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Default target GP %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Default target GP %",value:r,onChangeText:e=>{o(e);const t=C(e);null!=t&&t<95&&s({defaultTarget:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(a.T,{weight:"medium",children:"Cost multiple (x) is based on"}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Inc VAT (menu price)",selected:'inc'===e.multipleBasis,onPress:()=>s({multipleBasis:'inc'})}),(0,f.jsx)(a.Chip,{label:"Ex VAT",selected:'ex'===e.multipleBasis,onPress:()=>s({multipleBasis:'ex'})})]}),(0,f.jsx)(a.Muted,{children:"GP % uses the ex-VAT price. The price multiple is the menu price divided by ingredient cost."})]})}const N='#3A2F1E';function O({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n,said:l}){return(0,f.jsxs)(r.default,{testID:i,accessible:!0,accessibilityLabel:l??`${e}, ${t}${n?`, ${n}`:''}`,style:{flexGrow:1,flexBasis:128,minWidth:0,padding:10,borderRadius:14,backgroundColor:x.colours.surface,borderWidth:1,borderColor:x.colours.accentBorder,alignItems:'center',gap:2},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:e}),(0,f.jsx)(a.T,{size:28,weight:"bold",center:!0,colour:s,children:t}),n?(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:n}):null]})}},1157,[812,779,17,319,219,385,85,777,816,905,845,906,909,876,920,867,804,889,907,840,8]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1665,7 +1665,7 @@ __d(function(g,_r,i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModu __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.reorder=function(t,n,i,f){const c=t.filter(t=>t.section===i&&t.id!==n).map(t=>t.id),o=f?c.indexOf(f):-1;return c.splice(o<0?c.length:o,0,n),c.map((t,n)=>({id:t,sort:10*(n+1)}))},e.moveSection=function(t,n,i){const f=t.filter(t=>t!==n),c=i?f.indexOf(i):-1;return f.splice(c<0?f.length:c,0,n),f},e.moveShift=function(n,i,f,c,o,s){const u=n.find(t=>t.id===i);if(!u)return n;if(!o&&u.staffId===f&&u.date===c)return n;const l={...u,staffId:f,date:c,day:(0,t.weekdayOf)(c)};return o?[...n,{...l,id:s(),published:!1,changed:!1}]:n.map(t=>t.id===i?{...l,changed:!!u.published||u.changed}:t)};var t=r(d[0])},1582,[876]); __d(function(g,r,_i,a,m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.RotaEditor=function({today:e}){const j=(0,i.useOwner)(e=>e.staff).filter(e=>e.active),S=(0,i.useOwner)(e=>e.shifts),[k,D]=(0,t.useState)((0,i.mondayOfDate)(e)),$=(0,h.useDateCalendar)(),[v,w]=(0,t.useState)(null),[B,O]=(0,t.useState)(''),P=(0,c.useHistory)(()=>i.useOwner.getState().shifts,e=>i.useOwner.getState().setShifts(e),'rota change'),I=x.map((e,t)=>(0,i.addDays)(k,t)),T=(e,t,o)=>{e.preventDefault(),w(null);const d=(0,u.readDrag)(e);if('shift'!==d?.kind)return;const s=S.find(e=>e.id===d.id);if(!s)return;const n=!!e.altKey,c=j.find(e=>e.id===t)?.name??'';(n||s.staffId!==t||s.date!==o)&&(S.some(e=>e.staffId===t&&e.date===o&&e.id!==s.id&&e.starte.date>=k&&e.date<=I[6]),z=_.filter(e=>!e.published||e.changed).length;return(0,b.jsxs)(d.default,{style:{flex:1,gap:10},testID:"desk-rota",children:[(0,b.jsx)(f.Tip,{children:"Drag a shift to another day or person. Hold Option (Alt) while you drop to copy it instead. Nothing goes to staff until you press Publish."}),(0,b.jsxs)(s.Row,{gap:8,children:[(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"\u2039 Week before",onPress:()=>D((0,i.addDays)(k,-7))}),(0,b.jsxs)(s.T,{weight:"semibold",children:["Week of ",new Date(k+'T12:00:00').toLocaleDateString('en-GB',{day:'numeric',month:'long'})]}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Next week \u203a",onPress:()=>D((0,i.addDays)(k,7))}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",testID:"desk-rota-cal",label:"Calendar",accessibilityLabel:"Pick a date from the calendar",onPress:$.openCal}),(0,b.jsx)(h.AppDateCalendar,{visible:$.calOpen,today:e,day:k,idPrefix:"desk-rota-cal",onClose:$.closeCal,onDay:t=>D((0,i.mondayOfDate)(t??e))}),(0,b.jsx)(d.default,{style:{flex:1}}),B?(0,b.jsx)(s.T,{size:13,colour:n.colours.goldLight,children:B}):null,(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Undo",disabled:!P.canUndo,onPress:P.undo,testID:"rota-undo"}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Redo",disabled:!P.canRedo,onPress:P.redo,testID:"rota-redo"}),(0,b.jsx)(s.Button,{small:!0,label:z?`Publish (${z})`:'Published',disabled:!z,onPress:()=>{P.record('published the week');const e=i.useOwner.getState().publishWeek(k);O(`${e} shifts published.`)},testID:"rota-publish"})]}),(0,b.jsx)("div",{style:(0,f.box)({flex:1,overflow:'auto',border:`1px solid ${n.colours.border}`,borderRadius:12}),"data-testid":"rota-grid",children:(0,b.jsxs)("div",{style:(0,f.box)({display:'grid',gridTemplateColumns:"180px repeat(7, minmax(110px, 1fr))",minWidth:960}),children:[(0,b.jsx)("div",{style:(0,f.box)({position:'sticky',top:0,background:n.colours.surface,padding:8,borderBottom:`1px solid ${n.colours.border}`,zIndex:1})}),I.map((t,o)=>(0,b.jsxs)("div",{style:(0,f.box)({position:'sticky',top:0,zIndex:1,background:t===e?n.colours.goldTint:n.colours.surface,padding:8,borderBottom:`1px solid ${n.colours.border}`,fontFamily:'Poppins_600SemiBold',fontSize:13,color:t===e?n.colours.gold:n.colours.text}),children:[x[o]," ",Number(t.slice(8))]},t)),j.map(e=>(0,b.jsxs)(o.default.Fragment,{children:[(0,b.jsxs)("div",{style:(0,f.box)({padding:8,borderBottom:`1px solid ${n.colours.hairline}`,fontSize:13}),children:[(0,b.jsx)("div",{style:(0,f.box)({fontFamily:'Poppins_600SemiBold'}),children:e.name}),(0,b.jsx)("div",{style:(0,f.box)({fontSize:11,color:n.colours.muted}),children:e.job})]}),I.map(t=>{const o=`${e.id}|${t}`,d=_.filter(o=>o.staffId===e.id&&o.date===t);return(0,b.jsx)("div",{"data-testid":`rota-cell-${e.id}-${t}`,onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect=e.altKey?'copy':'move',w(o)},onDragLeave:()=>w(null),onDrop:o=>T(o,e.id,t),style:(0,f.box)({padding:5,minHeight:54,borderBottom:`1px solid ${n.colours.hairline}`,borderLeft:`1px solid ${n.colours.hairline}`,background:v===o?n.colours.accentBg:void 0,outline:v===o?`2px dashed ${n.colours.gold}`:void 0,outlineOffset:-3}),children:d.map(e=>(0,b.jsxs)("div",{draggable:!0,onDragStart:t=>(0,u.dragData)(t,'shift',e.id),"data-testid":`rota-shift-${e.id}`,title:e.note??'',style:(0,f.box)({cursor:'grab',userSelect:'none',borderRadius:8,padding:'4px 6px',marginBottom:4,fontSize:12,fontFamily:'Poppins_600SemiBold',background:e.published&&!e.changed?n.colours.gold:n.colours.goldTint,color:e.published&&!e.changed?n.colours.onGold:n.colours.goldLight,border:`1px solid ${n.colours.accentBorder}`}),children:[(0,l.fmtH)(e.start),"\u2013",(0,l.fmtH)(e.end),!e.published||e.changed?' \u2022':'']},e.id))},o)})]},e.id))]})}),(0,b.jsx)(s.Muted,{size:12,children:"Solid gold = published. Outlined with a dot = not yet published (new or changed)."})]})};var t=r(_d[0]),o=e(t),d=e(r(_d[1])),s=r(_d[2]),i=r(_d[3]),l=r(_d[4]),n=r(_d[5]),u=r(_d[6]),c=r(_d[7]),f=r(_d[8]),h=r(_d[9]),p=r(_d[10]),b=r(_d[11]);const x=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],y=()=>`sh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`},1583,[17,85,777,876,1060,804,1578,1579,1580,1051,1582,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1584,[13,17,856,1585,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1585,[1460,1586,813,912,1072,1512,1209,1210,1028,1025,1026,1513,1547,1515,1153,891,978,1587,975,880,1031,1032,1496,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1420,1066,1084,1086,1081,1027,1010,1057,1506,1501,1528,1588,1428,920,219,1246,1182,1189,1458,1202,1185,1483,1186,878,1212,1213,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1585,[1460,1586,813,912,1072,1512,1209,1210,1028,1025,1026,1513,1547,1515,1153,891,978,1587,975,880,1031,1032,1496,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1420,1066,1084,1086,1081,1027,1010,1057,1506,1501,1528,1588,1428,920,219,1246,1182,1189,1458,1202,1185,1483,1186,878,1212,1213,884,776,899,8]); __d(function(g,_r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffBookingTimes=function(){const{r:e,rid:s}=(0,o.useCtx)(),[u,c]=(0,t.useState)(()=>Object.fromEntries(d.map(([t])=>[t,e.kitchenHours?.[t]??null]))),[h,b]=(0,t.useState)(String(e.settings.turnMins??'')),[v,y]=(0,t.useState)(String(e.settings.bookingCoversPerSlot??'')),[x,j]=(0,t.useState)(''),[k,S]=(0,t.useState)(!1),f=(e,t,s)=>c(n=>({...n,[e]:0===t?[s,n[e]?.[1]??'']:[n[e]?.[0]??'',s]})),p=Object.values(u).every(e=>!e||e.every(e=>/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(e))&&e[0]=30&&Number(h)<=360&&Number(v)>=1&&Number(v)<=1e3;return(0,r.jsxs)(n.default,{style:{gap:12,width:'100%',minWidth:0},testID:"staff-booking-times",children:[(0,r.jsx)(i.T,{center:!0,weight:"bold",children:"Booking times"}),(0,r.jsx)(i.Muted,{center:!0,children:"Change kitchen hours, table time and the Covers offered in each booking slot. Table layout and blocks have their own screens."}),d.map(([e,t])=>(0,r.jsxs)(i.Card,{children:[(0,r.jsx)(i.T,{center:!0,weight:"semibold",children:t}),(0,r.jsx)(i.Toggle,{label:`${t} open`,value:!!u[e],onChange:t=>c(s=>({...s,[e]:t?['','']:null}))}),u[e]?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i.Field,{label:`${t} opens (HH:MM)`,value:u[e][0],placeholder:"HH:MM",onChangeText:t=>f(e,0,t)}),(0,r.jsx)(i.Field,{label:`${t} closes (HH:MM)`,value:u[e][1],placeholder:"HH:MM",onChangeText:t=>f(e,1,t)})]}):(0,r.jsx)(i.Muted,{center:!0,children:"Closed"})]},e)),(0,r.jsxs)(i.Card,{children:[(0,r.jsx)(i.Field,{label:"Typical table time, minutes",value:h,onChangeText:b,keyboardType:"number-pad"}),(0,r.jsx)(i.Field,{label:"Covers per 30-minute booking slot",value:v,onChangeText:y,keyboardType:"number-pad"}),e.settings.bookingCoversPerStart||e.settings.bookingPartiesPerStart?(0,r.jsx)(i.Muted,{center:!0,children:"Online booking uses the covers and bookings caps at each start time (Settings \u203a Capacity & waitlist), not this half-hour figure."}):null]}),(0,r.jsx)(i.Button,{label:k?'Saving\u2026':'Save booking times',disabled:!p||k,accessibilityLabel:"Save booking times without changing other venue settings",onPress:async()=>{S(!0);try{await(0,l.saveStaffBookingTimes)(s,u,Number(h),Number(v)),j('Booking times saved.')}catch(e){j(e.message)}finally{S(!1)}}}),x?(0,r.jsx)(i.Muted,{center:!0,children:x}):null]})};var e,t=_r(_d[0]),s=_r(_d[1]),n=(e=s)&&e.__esModule?e:{default:e},i=_r(_d[2]),o=_r(_d[3]),l=_r(_d[4]),r=_r(_d[5]);const d=[[1,'Monday'],[2,'Tuesday'],[3,'Wednesday'],[4,'Thursday'],[5,'Friday'],[6,'Saturday'],[0,'Sunday']]},1586,[17,85,777,1057,899,8]); __d(function(g,_r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.newerRelease=r,_e.startForegroundRefresh=function(n={}){if('undefined'==typeof document)return()=>{};let o='hidden'===document.visibilityState?Date.now():0,c=!1;const s=n.reload??(()=>location.reload()),u=async()=>{if(!c){c=!0;try{await Promise.race([e.mutationQueue.retryNow(),new Promise(e=>setTimeout(e,4e3))]),n.onWake?.();const t=await(navigator.serviceWorker?.getRegistration?.().catch(()=>{}));if(await(t?.update?.().catch(()=>{})),t?.waiting){try{t.waiting.postMessage({type:'SKIP_WAITING'})}catch{}return void setTimeout(s,3e3)}await r().catch(()=>!1)&&s()}finally{c=!1}}},l=()=>{if('hidden'===document.visibilityState)return void(o=Date.now());const n=o?Date.now()-o:0;o=0,e.mutationQueue.retryNow(),n>=t&&u()},f=()=>{e.mutationQueue.retryNow()};document.addEventListener('visibilitychange',l);for(const e of['focus','online','pageshow'])window.addEventListener(e,f);return()=>{document.removeEventListener('visibilitychange',l);for(const e of['focus','online','pageshow'])window.removeEventListener(e,f)}},_r(d[0]);var e=_r(d[1]);const t=3e4,n=e=>(e.match(/_expo\/static\/js\/web\/[A-Za-z0-9_.-]+\.js(\?v=[0-9a-f]+)?/)??[])[0]??null;function o(){try{const e=[...document.querySelectorAll('script[src]')].map(e=>e.src).find(e=>/_expo\/static\/js\/web\//.test(e));return e?n(e):null}catch{return null}}async function r(e=fetch){const t=o();if(!t)return!1;const r=location.pathname.replace(/[^/]*$/,''),c=await e(`${r}index.html?fresh=${Date.now()}`,{cache:'no-store'});if(!c.ok)return!1;const s=n(await c.text());return!!s&&s!==t}},1587,[219,976]); __d(function(g,_r,i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ManagerFeaturesNote=function(){return(0,j.jsxs)(a.default,{testID:"manager-features-banner",style:{borderWidth:1,borderColor:b.colours.gold,borderRadius:12,padding:10,gap:4},children:[(0,j.jsx)(d.T,{weight:"semibold",colour:b.colours.gold,children:"Manager features are on"}),(0,j.jsx)(d.Muted,{children:"Open Me \u203a Manager features for bookings, tables, blocks, allergy checks, stock, who\u2019s clocked in and shift swaps."})]})},_e.ManagerFeaturesAbout=function(){return(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"semibold",children:"What manager features include"}),c.SHIFT_MANAGER_FEATURES.map(e=>(0,j.jsxs)(d.T,{size:14,children:["\u2022 ",e]},e)),(0,j.jsxs)(d.Muted,{children:["Not included: ",c.SHIFT_MANAGER_EXCLUDED_WORDS,". Those stay in the Managers app."]})]})},_e.ClockOverview=function({today:e,now:t}){const s=(0,o.useOwner)(e=>e.staff),n=(0,o.useOwner)(e=>e.attendance).filter(t=>t.date===e&&t.in),r=e=>x(s.find(t=>t.id===e)?.name)||'Team member',h=n.filter(e=>!e.out).sort((e,t)=>(e.in??'').localeCompare(t.in??'')),c=n.filter(e=>e.out).sort((e,t)=>(e.out??'').localeCompare(t.out??'')),u=e=>(e.breaks??[]).some(e=>!e.end);return(0,j.jsxs)(a.default,{style:{gap:10},testID:"clock-overview",children:[(0,j.jsxs)(d.T,{weight:"semibold",children:["Clocked in now (",h.length,")"]}),h.length?h.map(e=>(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"medium",children:r(e.staffId)}),(0,j.jsxs)(d.Muted,{children:["In at ",(0,l.hm)(new Date(e.in)),u(e)?' \xb7 on a break':'',!1===e.inSite?' \xb7 clocked in away from the venue':'']})]},e.id)):(0,j.jsx)(d.Muted,{children:"Nobody is clocked in right now."}),(0,j.jsxs)(d.T,{weight:"semibold",children:["Finished today (",c.length,")"]}),c.length?c.map(e=>(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"medium",children:r(e.staffId)}),(0,j.jsxs)(d.Muted,{children:[(0,l.hm)(new Date(e.in))," to ",(0,l.hm)(new Date(e.out))]})]},e.id)):(0,j.jsx)(d.Muted,{children:"Nobody has clocked out yet today."}),(0,j.jsxs)(d.Muted,{children:["Read only. To change someone\u2019s clock record, ask a manager in the Managers app. Checked at ",(0,l.hm)(t),"."]})]})},_e.TablesToClear=function({rid:e}){const s=(0,r.useFloor)(t=>t.live[e])??{},n=Object.entries(s).filter(([,e])=>e?.dirty).map(([e])=>e).sort((e,t)=>e.localeCompare(t,'en',{numeric:!0}));return(0,j.jsx)(a.default,{style:{gap:8},testID:"tables-to-clear",children:n.length?n.map(s=>(0,j.jsx)(d.Card,{children:(0,j.jsxs)(d.Row,{style:{justifyContent:'space-between'},children:[(0,j.jsx)(d.T,{weight:"semibold",children:(0,t.tableNumbers)(s)}),(0,j.jsx)(d.Button,{small:!0,kind:"success",label:"Mark cleared",accessibilityLabel:`Mark table ${s} cleared, table free`,testID:`clear-${s}`,onPress:()=>{r.useFloor.getState().setLive(e,s,{dirty:!1,stage:void 0}),(0,w.notify)({id:`clear-${s}`,title:`${(0,t.tableNumbers)(s)} is free`,timeoutMs:4e3})}})]})},s)):(0,j.jsx)(d.Muted,{children:"No tables need clearing."})})},_e.SwapApprovals=function({today:e,me:t}){const n=(0,o.useOwner)(e=>e.staff),r=(0,o.useOwner)(e=>e.shifts),y=(0,o.useOwner)(e=>e.swaps),[M,k]=(0,s.useState)(null),[I,v]=(0,s.useState)(null),[T,S]=(0,s.useState)(!1),C=e=>x(n.find(t=>t.id===e)?.name)||'Team member',D=(()=>{const t=(0,l.parseYmd)(e);return t.setDate(t.getDate()+13),t})(),N=r.filter(t=>{return!1!==t.published&&t.date>=e&&(0,l.parseYmd)(t.date)<=D&&(s=t.staffId,!('owner'===n.find(e=>e.id===s)?.role));var s}).sort((e,t)=>e.date.localeCompare(t.date)||e.start-t.start),O=e=>`${(0,l.niceDate)((0,l.parseYmd)(e.date))}, ${(0,h.fmtH)(e.start)} to ${(0,h.fmtH)(e.end)}`,R=async(e,s,n,a)=>{S(!0);const d=await(0,u.approveShiftSwap)(e.id,s,n);S(!1),d.ok?(o.useOwner.setState(t=>({shifts:t.shifts.map(t=>t.id===e.id?{...t,staffId:s}:t)})),a&&o.useOwner.getState().setSwap(a,'approved'),(0,w.notify)({id:'swap-ok',title:'Shift changed',body:`${C(e.staffId)}\u2019s shift on ${O(e)} is now ${C(s)}\u2019s. Approved by ${x(t)}.`,timeoutMs:6e3}),k(null),v(null)):(0,w.notify)({id:'swap-fail',title:'Not changed',body:d.message,timeoutMs:6e3})},$=y.filter(e=>'open'===e.status);return(0,j.jsxs)(a.default,{style:{gap:10},testID:"swap-approvals",children:[(0,j.jsxs)(d.T,{weight:"semibold",children:["Requests (",$.length,")"]}),$.length?$.map(e=>{const t=r.find(t=>t.id===e.shiftId);return(0,j.jsxs)(d.Card,{children:[(0,j.jsxs)(d.T,{weight:"medium",children:[C(e.fromId)," \xb7 ",'cover'===e.kind?'needs cover':'swap']}),(0,j.jsxs)(d.Muted,{children:[t?O(t):'Shift not found',e.toId?` \xb7 to ${C(e.toId)}`:'',e.note?` \xb7 ${e.note}`:'']}),(0,j.jsxs)(d.Row,{gap:6,children:[(0,j.jsx)(d.Button,{small:!0,label:"Approve",disabled:!t||!e.toId||T||!(0,p.canSwapWith)(n.find(t=>t.id===e.fromId),n.find(t=>t.id===e.toId),f.VENUE_RID),onPress:()=>t&&e.toId&&R(t,e.toId,e.kind,e.id)}),(0,j.jsx)(d.Button,{small:!0,kind:"ghost",label:"Decline",onPress:()=>o.useOwner.getState().setSwap(e.id,'declined')})]})]},e.id)}):(0,j.jsx)(d.Muted,{children:"No open requests on this phone. Swap requests made on other phones aren\u2019t shared yet, so if someone asks you in person, use Give a shift to someone else below."}),(0,j.jsx)(d.T,{weight:"semibold",children:"Give a shift to someone else"}),M?(0,j.jsxs)(d.Card,{highlight:b.colours.gold,children:[(0,j.jsxs)(d.T,{weight:"semibold",children:[C(M.staffId)," \xb7 ",O(M)]}),(0,j.jsx)(d.Muted,{children:"Who takes it? Only someone they are allowed to swap with."}),(0,j.jsx)(d.Row,{wrap:!0,gap:6,children:(0,c.swapTargets)(n,M.staffId,f.VENUE_RID).map(e=>(0,j.jsx)(d.Chip,{label:x(e.name),selected:I===e.id,onPress:()=>v(e.id)},e.id))}),(0,j.jsxs)(d.Row,{gap:6,children:[(0,j.jsx)(d.Button,{label:"Approve",disabled:!I||T,onPress:()=>I&&R(M,I,'swap'),testID:"swap-give"}),(0,j.jsx)(d.Button,{kind:"secondary",label:"Cancel",onPress:()=>{k(null),v(null)}})]})]}):N.length?N.map(e=>(0,j.jsxs)(d.Card,{onPress:()=>{k(e),v(null)},children:[(0,j.jsx)(d.T,{weight:"medium",children:C(e.staffId)}),(0,j.jsx)(d.Muted,{children:O(e)})]},e.id)):(0,j.jsx)(d.Muted,{children:"No published shifts in the next two weeks."}),(0,j.jsx)(d.Banner,{kind:"info",children:"Approving moves the shift on the rota for everyone and records who approved it. Writing or publishing the rota stays in the Managers app."})]})};var e,t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),a=(e=n)&&e.__esModule?e:{default:e},d=_r(_d[3]),o=_r(_d[4]),r=_r(_d[5]),l=_r(_d[6]),h=_r(_d[7]),c=_r(_d[8]),u=_r(_d[9]),p=_r(_d[10]),f=_r(_d[11]),w=_r(_d[12]),b=_r(_d[13]),j=_r(_d[14]);const x=e=>(e??'').replace(' (example)','')},1588,[843,17,85,777,876,998,863,1060,1058,899,1059,805,916,804,8]); @@ -1701,7 +1701,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0});var t=r(d[0]);Object.keys(t).forEach(function(n){'default'===n||Object.prototype.hasOwnProperty.call(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})})},1618,[1619]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.preventAutoHideAsync=async function(){return!1},e.setOptions=function(n){},e.hide=function(){},e.hideAsync=async function(){}},1619,[]); __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1620,[17,24,85,409,777,857,920,899,880,805,804,1561,1563,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1621,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1621,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1622,[813,779,17,974,385,85,856,899,976,804,777,1352,971,880,1623,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.SyncDeviceActions=function(){const e=(0,o.useSync)(),[f,p]=(0,s.useState)(!1),h='live'===e.mode||'offline'===e.mode;return e.venueId&&h?(0,b.jsxs)(b.Fragment,{children:[f?(0,b.jsxs)(c.default,{style:{gap:6,marginTop:6},children:[(0,b.jsx)(u.T,{size:12,children:"Disconnect this device? Your changes stay on it; open your personal invite link to connect again."}),(0,b.jsxs)(c.default,{style:{flexDirection:'row',gap:8},children:[(0,b.jsx)(t.default,{testID:"unpair-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, disconnect",onPress:()=>{p(!1),(0,o.disconnectStaff)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:l.colours.red},children:(0,b.jsx)(u.T,{size:12,weight:"semibold",children:"Yes, disconnect"})}),(0,b.jsx)(t.default,{accessibilityRole:"button",accessibilityLabel:"Keep connected",onPress:()=>p(!1),style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,b.jsx)(u.T,{size:12,children:"Keep"})})]})]}):(0,b.jsx)(t.default,{testID:"unpair",accessibilityRole:"button",accessibilityLabel:"Disconnect this device",onPress:()=>p(!0),style:{marginTop:6,alignSelf:'flex-start'},children:(0,b.jsx)(u.T,{size:12,colour:l.colours.gold,children:"Disconnect this device\u2026"})}),(0,b.jsx)(n.WipeDevice,{compact:!0})]}):null};var s=r(d[0]),n=r(d[1]),t=e(r(d[2])),c=e(r(d[3])),o=r(d[4]),l=r(d[5]),u=r(d[6]),b=r(d[7])},1623,[17,1461,385,85,899,804,777,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1624,[]); diff --git a/car-app/index.html b/car-app/index.html index ddc8b48ca28be038957c7f5614c795d59579cb6b..ecaf19570c46e3b93414f230b04d9137f6c5e672 100644 --- a/car-app/index.html +++ b/car-app/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/car-app/owner.html b/car-app/owner.html index 582916de34ca731e94d4008d7889104ed85aaf99..4b88d1d853df9a3c19252feec9fb07a18f162b28 100644 --- a/car-app/owner.html +++ b/car-app/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/car-app/sw.js b/car-app/sw.js index c9bd4a7cfeb4a4dd6b8b8795a3772f847249f13e..3d9aa276265cf1b7a15deb3ea3ef848420a04db7 100644 --- a/car-app/sw.js +++ b/car-app/sw.js @@ -1,7 +1,7 @@ // Anchorage car screen service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-car-2fd5243fdd"; +const V = "cc-car-53c4d440f8"; const BASE = "/car-app/"; -const PRECACHE = ["/car-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/car-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/car-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/car-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/car-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/car-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/car-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/car-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/car-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/car-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/car-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/car-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/car-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/car-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/car-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/car-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/car-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/car-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/car-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/car-app/favicon.ico", "/car-app/index.html", "/car-app/_expo/static/js/web/bundle.js?v=2fd5243fddc43e288b36012ccd137d7255746e7687fcd009e056c4c90ac1ea93"]; +const PRECACHE = ["/car-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/car-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/car-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/car-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/car-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/car-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/car-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/car-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/car-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/car-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/car-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/car-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/car-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/car-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/car-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/car-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/car-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/car-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/car-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/car-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/car-app/favicon.ico", "/car-app/index.html", "/car-app/_expo/static/js/web/bundle.js?v=53c4d440f8ecc01d5229264caea767f4bcf6ddc53e1a00e902240320dbd87cce"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/chef-app/_expo/static/js/web/bundle.js b/chef-app/_expo/static/js/web/bundle.js index 1e2ce843c22e865fc5ed60e4b39cea9f50c78fd9..ea843d95a9ee566a5ff5317f9928414255c999c6 100644 --- a/chef-app/_expo/static/js/web/bundle.js +++ b/chef-app/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?`
    ${n.map(t=>`
  • ${p(t)}
  • `).join('')}
`:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/chef-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(_g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"CREATOR_TITLE",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"pounds",{enumerable:!0,get:function(){return v}}),Object.defineProperty(_e,"numIn",{enumerable:!0,get:function(){return C}}),_e.useOwnCosting=I,_e.DishCreator=function({rid:e,canPublish:t,initial:n="create"}){const l=I(),o=(0,d.useGpCalcView)(),[c,p]=(0,i.useState)(n),[g,h]=(0,i.useState)(()=>P(o.settings.defaultTarget));return l?(0,f.jsxs)(r.default,{style:{gap:12},testID:"dish-creator",children:[o.alerts.map(e=>(0,f.jsx)(r.default,{testID:"margin-alert",children:(0,f.jsx)(a.Banner,{kind:"danger",title:`Margin dropped: ${e.ingredient} ${e.change}`,children:(0,f.jsxs)(r.default,{style:{gap:4},children:[e.dishes.map(e=>(0,f.jsxs)(a.T,{size:14,colour:"#FFE3DF",children:[e.name,": ",(0,u.pct)(e.before)," \u2192 ",(0,u.pct)(e.after),e.belowTarget?' \xb7 below target':'']},e.id)),(0,f.jsx)(s.ToastClose,{label:"Dismiss alert",testID:`margin-alert-close-${e.id}`,onPress:()=>o.dismissAlert(e.id),size:"sm",style:{alignSelf:'flex-end'}})]})})},e.id)),(0,f.jsx)(y.Tabs,{value:c,onChange:p,options:[{id:'create',label:g.name&&o.dishes.some(e=>e.id===g.id)?'Edit dish':'Create'},{id:'saved',label:'Saved dishes & GP'},{id:'items',label:'Ingredient prices'},{id:'settings',label:'VAT & rounding'}]}),'create'===c?(0,f.jsx)(D,{draft:g,setDraft:h,onNew:()=>h(P(o.settings.defaultTarget)),onSaved:()=>p('saved')},g.id):null,'saved'===c?(0,f.jsx)(G,{rid:e,canPublish:t,onEdit:e=>{h({...e,allergens:[...e.allergens??[]]}),p('create')}}):null,'items'===c?(0,f.jsx)(V,{}):null,'settings'===c?(0,f.jsx)(W,{}):null,(0,f.jsx)(a.Muted,{children:"Costs are visible to Managers and the Head Chef only. Prices you enter, not supplier quotes."})]}):(0,f.jsx)(r.default,{testID:"dish-creator-no-access",style:{alignItems:'center',paddingVertical:16},children:(0,f.jsx)(a.Muted,{center:!0,children:"Ingredient prices and dish costs are for the Head Chef, owners and managers."})})},_e.NewIngredient=A,Object.defineProperty(_e,"TALL",{enumerable:!0,get:function(){return L}}),_e.Pick=R,_e.Items=V,_e.useCardCosting=function(e,t,s="edit"){const{ingredients:n,settings:l,cardCosts:r}=(0,d.useGpCalcView)(),a=I();return(0,i.useMemo)(()=>{if(!e||!a||!(0,p.cardCostsVisible)(t,s))return null;const i=r?.[e.id];if(!i?.lines.length)return null;const o=(0,u.cardCostSummary)(i,n,l,e.price),d={};return o.lines.forEach(e=>{e.line.recipeIngId&&(d[e.line.recipeIngId]={cost:(d[e.line.recipeIngId]?.cost??0)+e.cost,label:e.label})}),{summary:o,byRecipeIng:d}},[e,t,s,a,n,l,r])},_e.CardGpPanel=function({card:e,actor:s,mode:n="edit"}){const{ingredients:l,settings:o,cardCosts:c,saveCardCost:g}=(0,d.useGpCalcView)(),h=I()&&(0,p.cardCostsVisible)(s.role,n),y=h&&'staff'!==s.role,w=c?.[e.id]??{lines:[],portions:1},P=(0,u.cardCostSummary)(w,l,o,e.price),[$,S]=(0,i.useState)(''),[D,k]=(0,i.useState)(),[M,G]=(0,i.useState)(!1),[B,V]=(0,i.useState)(w.menuPrice?(w.menuPrice/100).toFixed(2):''),[z,W]=(0,i.useState)(!1),[F,E]=(0,i.useState)(null),[U,H]=(0,i.useState)(!w.lines.length),[q,_]=(0,i.useState)(!1),[Y,X]=(0,i.useState)(null!=w.target?String(w.target):'');if(!h)return null;const K=t=>g(e.id,{...d.useGpCalc.getState().cardCosts[e.id]??w,...t}),J=(e,t)=>{if(t){const s=(0,b.suggestAmount)(t.qty,t.unit,e);if(s.qty>0)return s}const s=e.servings?'serving':(0,u.unitsFor)(e.packUnit)[0];return{qty:'serving'===s||'each'===s?1:0,unit:s}},Q=(t,s=D)=>{const i=e.ingredients.find(e=>e.id===s),n={ingId:t.id,...J(t,i),...s?{recipeIngId:s}:{}},l=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...l.lines,n]}),S(''),k(void 0),G(!1),_(!1)},Z=(e,t)=>K({lines:w.lines.map((s,i)=>i===e?{...s,...t}:s)}),ee=new Set(w.lines.map(e=>e.recipeIngId).filter(Boolean)),te=e.ingredients.filter(e=>e.name.trim()&&!ee.has(e.id)),se=te.map(e=>({ri:e,i:(0,b.matchIngredient)(e.name,l)})).filter(e=>!!e.i),ie=P.price?P.price/(1+o.vatPct/100):null,ne=l.filter(e=>!$.trim()||$.trim().toLowerCase().split(/\s+/).some(t=>t.length>2&&e.name.toLowerCase().includes(t))||e.name.toLowerCase().includes($.trim().toLowerCase())).slice(0,12),le=v(B),re=P.tone?T[P.tone]:x.colours.muted,ae=null!=e.price&&P.price===e.price;return(0,f.jsxs)(r.default,{testID:"card-gp",accessibilityLabel:"GP calculator",style:{width:'100%',gap:10,padding:14,borderRadius:18,borderWidth:1.5,borderColor:x.colours.gold,backgroundColor:N},children:[(0,f.jsx)(a.T,{size:20,weight:"bold",center:!0,colour:x.colours.gold,accessibilityRole:"header",children:"GP calculator"}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["Costs from the price list (latest delivery prices) \xb7 target ",P.target,"% GP"]}),P.price?(0,f.jsxs)(r.default,{testID:"gp-vat-line",accessible:!0,accessibilityLabel:`Menu price ${(0,u.money)(P.price)} including VAT, ${(0,u.money)(ie)} without VAT. GP is worked out on the price without VAT.`,style:{alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,weight:"semibold",children:[(0,u.money)(P.price)," inc VAT \xb7 ",(0,u.money)(ie)," ex VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:[P.priceIsSuggested?'Suggested price':w.menuPrice?'The price you typed':'Menu price on the card'," \xb7 GP is on the ex-VAT price"]})]}):null,w.lines.length?(0,f.jsx)(r.default,{testID:"card-gp-lines",style:{gap:8},children:P.lines.map((e,s)=>{const i=l.find(t=>t.id===e.line.ingId);return(0,f.jsxs)(r.default,{testID:"card-gp-line",style:{gap:6,paddingVertical:8,borderTopWidth:s?1:0,borderColor:x.colours.accentBorder},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}, ${e.label}, ${i?`${(0,u.money)(e.cost)}, ${(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}`:'not on the price list'}`,style:{flexDirection:'row',gap:8,alignItems:'center',minHeight:32},children:[(0,f.jsxs)(r.default,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(a.T,{weight:"medium",children:e.name}),(0,f.jsx)(a.T,{size:x.font.small,colour:x.colours.muted,children:e.label}),i?(0,f.jsx)(a.T,{testID:"card-gp-line-rates",size:x.font.small,colour:x.colours.goldLight,children:(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}):null]}),(0,f.jsx)(a.T,{weight:"semibold",colour:i?x.colours.goldLight:x.colours.amber,children:i?(0,u.money)(e.cost):'Removed'})]}),U&&y&&i?(()=>{const n=(0,u.unitsFor)(i.packUnit,i.servings),l=t=>(0,f.jsx)(R,{testID:`gp-unit-${s}-${t}`,label:'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2),accessibilityLabel:`${e.name} by ${'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2)}`,selected:e.line.unit===t,onPress:()=>Z(s,{unit:t})},t);return(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:`gp-qty-${s}`,accessibilityLabel:`Amount of ${e.name}`,value:e.line.qty?String(e.line.qty):'',onChangeText:e=>Z(s,{qty:C(e)??0}),placeholder:"amount",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),n.slice(0,-1).map(l),(0,f.jsxs)(r.default,{testID:`gp-unit-end-${s}`,style:{flexDirection:'row',flexWrap:'nowrap',alignItems:'center',gap:6},children:[n.slice(-1).map(l),(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})]})]})})():U&&y?(0,f.jsx)(a.Row,{gap:6,style:{justifyContent:'center'},children:(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})}):null]},s)})}):(0,f.jsx)(r.default,{testID:"card-gp-empty",style:{alignItems:'center',paddingVertical:6},children:(0,f.jsxs)(a.T,{center:!0,colour:x.colours.goldLight,children:["Not costed yet.",y?' Add the ingredients from your price list below.':'']})}),y&&w.lines.length?(0,f.jsx)(a.Button,{small:!0,kind:U?'primary':'secondary',testID:"gp-edit",label:U?'Done':'Change amounts or ingredients',accessibilityLabel:U?'Done changing the costing':`Change the costing for ${e.dish}`,onPress:()=>{H(!U),G(!1)}}):null,y&&U?(0,f.jsxs)(r.default,{style:{gap:8,alignItems:'center'},children:[se.length?(0,f.jsx)(a.Button,{testID:"gp-link-all",label:`Link ${se.length} matching price${1===se.length?'':'s'}`,accessibilityLabel:`Link ${se.length} of this card's ingredients to matching items on the price list`,onPress:()=>{const t=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...t.lines,...se.map(({ri:e,i:t})=>({ingId:t.id,...J(t,e),recipeIngId:e.id}))]}),E(`Linked ${se.length} ingredient${1===se.length?'':'s'} to the price list. Check the amounts below.`)},style:{minHeight:52}}):null,te.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Cost this card\u2019s ingredients"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:te.slice(0,10).map(e=>(0,f.jsx)(R,{testID:`gp-cost-${e.id}`,label:e.name.split(',')[0].slice(0,28),accessibilityLabel:`Cost ${e.name}`,selected:D===e.id,onPress:()=>{k(e.id),S(e.name.split(/[,(]/)[0].trim()),G(!0)}},e.id))})]}):null,M?(0,f.jsxs)(r.default,{style:{width:'100%',gap:6},children:[(0,f.jsx)(t.TextInput,{testID:"gp-search",accessibilityLabel:"Search ingredient prices",value:$,onChangeText:S,placeholder:"Search the price list",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[ne.map(e=>{const t=(0,u.perServing)(e),s=(0,u.perBaseUnit)(e),i=null!=t?`${(0,u.money)(t)} a ${(0,u.servingWord)(e,1)}`:s?`${(0,u.money)(s.pence)} a ${s.per}`:(0,u.money)(e.packPrice);return(0,f.jsx)(R,{testID:`gp-pick-${e.id}`,label:`${e.name} \xb7 ${i}`,accessibilityLabel:`Add ${e.name}, ${i}`,onPress:()=>Q(e)},e.id)}),ne.length?null:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:l.length?'Nothing on the price list matches.':'The price list is empty. Add a price here, or record a delivery.'})]}),q?(0,f.jsx)(A,{initial:$.trim(),onDone:e=>{_(!1);const t=e?d.useGpCalc.getState().ingredients.find(t=>t.id===e):void 0;t&&Q(t)}}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add-price",label:$.trim()?`Add a price for ${$.trim().slice(0,30)}`:'Add a new price',accessibilityLabel:`Add ${$.trim()||'a new ingredient'} to the price list and cost it on this card`,onPress:()=>_(!0)}),(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>{G(!1),k(void 0),S(''),_(!1)}})]}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add",kind:"secondary",label:"Add from ingredient prices",onPress:()=>{G(!0),k(void 0)}}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Target GP %"}),(0,f.jsx)(t.TextInput,{testID:"gp-target",accessibilityLabel:`Target GP percent for this dish, now ${P.target}`,value:Y,onChangeText:e=>{X(e);const t=C(e);null!=t&&t>0&&t<95?K({target:t}):e.trim()||K({target:void 0})},placeholder:String(o.defaultTarget),placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{testID:"gp-portions",accessibilityLabel:"Portions this recipe makes",value:String(w.portions||1),onChangeText:e=>K({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]})]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost",label:"Food cost per portion",value:(0,u.money)(P.perPortion),colour:x.colours.goldLight,sub:(w.portions||1)>1?`Batch ${(0,u.money)(P.batch)} \xf7 ${w.portions}`:P.missing?`${P.missing} line${1===P.missing?'':'s'} not costed`:void 0}),(0,f.jsx)(O,{testID:"gp-suggested",label:`Suggested at ${P.target}% GP`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?"inc VAT"+(o.pricePoints?', rounded up':''):'Add amounts first'})]}),y?(0,f.jsxs)(r.default,{style:{gap:6,alignItems:'center'},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Your menu price (inc VAT)"}),(0,f.jsxs)(a.Row,{gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{size:24,style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{testID:"gp-price",accessibilityLabel:"Your menu price in pounds, including VAT",value:B,onChangeText:e=>{const t=(0,j.sanitiseMoneyTyping)(e);V(t);const s=v(t);null!=s&&s>0?K({menuPrice:s}):t.trim()||K({menuPrice:void 0})},placeholder:P.price?(P.price/100).toFixed(2):'0.00',placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{minHeight:56,width:150,fontSize:24,textAlign:'center'}]})]}),(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:le?'GP below uses the price you typed.':e.price?`Blank uses the menu price, ${(0,u.money)(e.price)}.`:'Blank uses the suggested price.'}),P.suggested&&!le?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:"gp-use-suggested",label:`Use suggested ${(0,u.money)(P.suggested)}`,accessibilityLabel:`Use the suggested price, ${(0,u.money)(P.suggested)}`,onPress:()=>{V((P.suggested/100).toFixed(2)),K({menuPrice:P.suggested})}}):null]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-gp",label:`GP on ${P.price?(0,u.money)(P.price):'the price'}`,value:null!=P.gp?(0,u.pct)(P.gp):'\u2014',colour:re,sub:null!=P.gp?'ok'===P.tone?'On target':'amber'===P.tone?'Just under target':'Below target':void 0}),(0,f.jsx)(O,{testID:"gp-cash",label:"Cash GP per portion",value:null!=P.cashGp?(0,u.money)(P.cashGp):'\u2014',colour:re,sub:P.price?`${(0,u.money)(P.price/(1+o.vatPct/100))} ex VAT`:void 0})]}),(()=>{const e=(0,u.foodCostTargetOf)(P.target),t=null!=P.foodCostPct?(0,u.foodCostTone)(P.foodCostPct,e):null,s=t?T[t]:x.colours.muted,i=P.price&&P.perPortion>0?(0,u.vatAwareGp)(P.perPortion,P.price,o.vatPct):null;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost-pct",label:"Food cost %",value:null!=P.foodCostPct?(0,u.pct)(P.foodCostPct):'\u2014',colour:s,sub:null!=P.foodCostPct?`Target ${e}% \xb7 ${'ok'===t?'on target':'amber'===t?'just over':'over target'}`:`Target ${e}%`}),(0,f.jsx)(O,{testID:"gp-suggested-target",label:`Price for ${e}% food cost`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?'inc VAT':'Add amounts first'})]}),i?(0,f.jsxs)(r.default,{testID:"gp-vat-aware",accessible:!0,accessibilityLabel:`VAT ${(0,u.money)(i.vatPence)} of the ${(0,u.money)(P.price)} goes to the tax office. GP on the price without VAT is ${(0,u.pct)(i.gpPct)}. With VAT left in it would wrongly look like ${(0,u.pct)(i.naiveGpPct)}.`,style:{alignItems:'center',gap:2},children:[(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["VAT ",o.vatPct,"%: ",(0,u.money)(i.vatPence)," of each ",(0,u.money)(P.price)," is VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:["True GP ",(0,u.pct)(i.gpPct)," (ex VAT) \xb7 would look like ",(0,u.pct)(i.naiveGpPct)," with VAT left in"]})]}):null]})})(),y&&P.price&&!ae?z?(0,f.jsxs)(r.default,{testID:"gp-menu-confirm",style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Put ",(0,u.money)(P.price)," on the menu? The card goes back to Awaiting sign-off until a chef signs it again."]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"gp-menu-yes",label:`Yes, use ${(0,u.money)(P.price)}`,onPress:async()=>{if(P.price)try{await(0,m.recipeCards)().update(e.id,{price:P.price},s),E(`Menu price set to ${(0,u.money)(P.price)}. The card now waits for sign-off again.`),W(!1)}catch(e){E(e?.message??'Could not change the menu price.')}}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Not now",onPress:()=>W(!1)})]})]}):(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:"gp-menu",label:`Use ${(0,u.money)(P.price)} on the menu`,accessibilityLabel:`Use ${(0,u.money)(P.price)} as the menu price for ${e.dish}`,onPress:()=>W(!0)}):null,F?(0,f.jsx)(a.T,{center:!0,size:x.font.small,colour:x.colours.goldLight,children:F}):null,(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"GP is worked out on the price without VAT. Only the Head Chef and managers see costs."})]})};var t=_r(_d[0]),s=_r(_d[1]),i=_r(_d[2]),n=e(_r(_d[3]));_r(_d[4]);var l=e(_r(_d[5])),r=e(_r(_d[6])),a=_r(_d[7]),o=_r(_d[8]),d=_r(_d[9]),c=_r(_d[10]),u=_r(_d[11]),p=_r(_d[12]),g=_r(_d[13]),h=_r(_d[14]),m=_r(_d[15]),x=_r(_d[16]),y=_r(_d[17]),b=_r(_d[18]),j=_r(_d[19]),f=_r(_d[20]);const w='New dish creator',T={ok:x.colours.ok,amber:x.colours.amber,red:x.colours.red},v=e=>{const t=(0,j.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):null},C=e=>{const t=e.trim().replace(',','.');return/^\d*\.?\d+$/.test(t)?Number(t):null},P=e=>({id:(0,d.gid)('gd'),name:'',lines:[],portions:1,target:e,status:'draft',allergens:[],description:''});function I(){const e=(0,h.useSession)(e=>e.meId),t=(0,g.useOwner)(t=>e?t.staff.find(t=>t.id===e):void 0);return!e||!!t&&t.active&&(0,p.costsAllowedFor)(t)}function $({n:e,title:t,children:s,testID:i}){return(0,f.jsxs)(y.Box,{testID:i,children:[(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(r.default,{style:{width:30,height:30,borderRadius:15,backgroundColor:x.colours.gold,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.onGold,children:e})}),(0,f.jsx)(a.T,{size:18,weight:"semibold",style:{flex:1},children:t})]}),s]})}function S({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n}){return(0,f.jsxs)(r.default,{testID:i,style:{flexGrow:1,flexBasis:140,padding:12,borderRadius:14,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border,gap:2},children:[(0,f.jsx)(a.Muted,{children:e}),(0,f.jsx)(a.T,{size:30,weight:"bold",colour:s,children:t}),n?(0,f.jsx)(a.Muted,{children:n}):null]})}function D({draft:e,setDraft:n,onNew:l,onSaved:o}){const{ingredients:p,dishes:g,settings:h,saveDish:m}=(0,d.useGpCalcView)(),[b,w]=(0,i.useState)(''),[P,I]=(0,i.useState)(!1),[D,L]=(0,i.useState)(''),[R,M]=(0,i.useState)(e.menuPrice?'price':'gp'),[G,B]=(0,i.useState)(e.menuPrice?(e.menuPrice/100).toFixed(2):''),[V,z]=(0,i.useState)(String(e.target)),[W,N]=(0,i.useState)(String(e.targetX??4)),O=t=>n({...e,...t}),F=g.filter(t=>t.id!==e.id),E=(0,u.portionCost)(e,p,g),U=h.vatPct,H=C(V)??e.target,q=C(W)??4,_='price'===R?v(G):E>0?'gp'===R?(0,u.suggestPrice)(E,H,U,h.pricePoints):(0,u.suggestForMultiple)(E,q,U,h.multipleBasis,h.pricePoints):null,Y=_?(0,u.gpOf)(E,_,U):null,X=_?(0,u.multipleOf)(E,_,U,h.multipleBasis):0,K=Y?(0,u.toneFor)(Y.gpPct,H):'ok',J=(0,u.suggestAllergens)(e,p,g),Q=t=>{const s=p.find(e=>e.id===t),i=t.startsWith('dish:')?'each':(0,u.unitsFor)(s.packUnit,s.servings)[0],l=[...e.lines,{ingId:t,qty:t.startsWith('dish:')?1:0,unit:i}],r={...e,lines:l},a=(0,u.suggestAllergens)(r,p,g);n({...r,allergens:Array.from(new Set([...e.allergens??[],...a]))})},Z=(t,s)=>O({lines:e.lines.map((e,i)=>i===t?{...e,...s}:e)}),ee=p.filter(e=>!b.trim()||e.name.toLowerCase().includes(b.trim().toLowerCase())),te=t=>{if(!e.name.trim())return L('Give the dish a name first.');if('ready'===t){if(!e.category)return L('Pick a category to make it menu-ready.');if(!e.lines.length||E<=0)return L('Add ingredients with quantities to make it menu-ready.');if(!_)return L('Set a price to make it menu-ready.')}const s='published'===e.status?'published':t;m({...e,name:e.name.trim(),target:H,targetX:q,menuPrice:_??void 0,status:s}),L('ready'===t?`Saved \u201c${e.name.trim()}\u201d as menu-ready. A manager can publish it to the menu.`:`Saved \u201c${e.name.trim()}\u201d as a draft.`)};return(0,f.jsxs)(r.default,{style:{gap:12},children:[(0,f.jsxs)($,{n:1,title:"Name and category",testID:"step-name",children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:"Dish name",value:e.name,onChangeText:e=>O({name:e.slice(0,60)}),placeholder:"e.g. Cullen skink",placeholderTextColor:"#7D776C",style:[a.styles.input,{fontSize:20}]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:u.DISH_CATEGORIES.map(t=>(0,f.jsx)(a.Chip,{label:t,selected:e.category===t,onPress:()=>O({category:t})},t))})]}),(0,f.jsxs)($,{n:2,title:"Add saved items and ingredients",testID:"step-ingredients",children:[F.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.Muted,{children:"Saved items (tap to add a portion)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:F.map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(`dish:${e.id}`)},e.id))})]}):null,(0,f.jsx)(a.Muted,{children:"Ingredients"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredients",value:b,onChangeText:w,placeholder:"Search ingredients",placeholderTextColor:"#7D776C",style:a.styles.input}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[ee.slice(0,24).map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(e.id)},e.id)),(0,f.jsx)(a.Chip,{label:"New ingredient",onPress:()=>I(!0)})]}),P?(0,f.jsx)(A,{initial:b,onDone:e=>{I(!1),w(''),e&&Q(e)}}):null,e.lines.length?(0,f.jsx)(r.default,{style:{gap:8},testID:"dish-lines",children:e.lines.map((i,n)=>{const l=i.ingId.startsWith('dish:'),o=p.find(e=>e.id===i.ingId),d=(c=i.ingId).startsWith('dish:')?g.find(e=>e.id===c.slice(5))?.name??'Saved item':p.find(e=>e.id===c)?.name??'?';var c;return(0,f.jsxs)(r.default,{testID:"dish-line",style:{gap:6,padding:10,borderRadius:12,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between'},children:[(0,f.jsxs)(a.T,{weight:"medium",style:{flex:1},children:[d,l?' (saved item)':'']}),(0,f.jsx)(a.T,{weight:"semibold",children:(0,u.money)((0,u.lineCost)(i,p,g))}),(0,f.jsx)(s.GoldClose,{size:"sm",label:`Remove ${d}`,onPress:()=>O({lines:e.lines.filter((e,t)=>t!==n)})})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Quantity of ${d}`,value:i.qty?String(i.qty):'',onChangeText:e=>Z(n,{qty:C(e)??0}),placeholder:"qty",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:90}]}),l?(0,f.jsx)(a.Muted,{children:"portion(s)"}):(0,u.unitsFor)(o.packUnit,o.servings).map(e=>(0,f.jsx)(a.Chip,{label:'serving'===e?(0,u.servingWord)(o,2):(0,u.unitName)(e,2),selected:i.unit===e,onPress:()=>Z(n,{unit:e})},e)),l?null:(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${d}`,value:null==i.wastePct?'':String(i.wastePct),onChangeText:e=>Z(n,{wastePct:''===e.trim()?void 0:C(e)??0}),placeholder:`waste ${o.wastePct}%`,placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:110}]})]})]},n)})}):(0,f.jsx)(a.Muted,{children:"Nothing added yet. Tap a saved item or an ingredient above."}),(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Portions per batch",value:String(e.portions),onChangeText:e=>O({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,{width:80,textAlign:'center'}]})]}),(0,f.jsx)(S,{testID:"cost-per-plate",label:"Cost per plate",value:(0,u.money)(E),sub:e.portions>1?`Batch cost ${(0,u.money)(E*e.portions)} \xf7 ${e.portions}`:'Live: updates as you type'})]}),(0,f.jsxs)($,{n:3,title:"Price it",testID:"step-price",children:[(0,f.jsx)(y.Tabs,{value:R,onChange:M,options:[{id:'gp',label:'Target GP %'},{id:'x',label:'Target multiple'},{id:'price',label:'Type a price'}]}),'gp'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[65,70,75].map(e=>(0,f.jsx)(a.Chip,{label:`${e}%`,selected:H===e,onPress:()=>z(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target GP %",value:V,onChangeText:z,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'x'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[3,4,5].map(e=>(0,f.jsx)(a.Chip,{label:`${e}x`,selected:q===e,onPress:()=>N(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target multiple",value:W,onChangeText:N,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'price'===R?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{size:24,children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Menu price (inc VAT)",value:G,onChangeText:e=>B((0,j.sanitiseMoneyTyping)(e)),placeholder:"0.00",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{width:140,fontSize:24}]}),(0,f.jsx)(a.Muted,{children:"inc VAT"})]}):null,'price'!==R?(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"suggested-price",label:`Suggested menu price (inc ${U}% VAT)`,value:_?(0,u.money)(_):'\u2014',colour:x.colours.gold,sub:_?`${(0,u.money)(_/(1+U/100))} ex VAT${h.pricePoints?' \xb7 rounded up to .50 / .95':''}`:'Add ingredients first'}),_?(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Type my own price",onPress:()=>{B((_/100).toFixed(2)),M('price')}}):null]}):null,(()=>{const t=(0,u.avgMenuPrice)(g,e.category,e.id);return e.category?(0,f.jsx)(r.default,{testID:"avg-menu-price",children:(0,f.jsx)(a.Muted,{children:t?`Average menu price for ${e.category}: ${(0,u.money)(t.avg)} (${t.count} dish${1===t.count?'':'es'})${_?` \xb7 this dish ${_>=t.avg?'+':'\u2212'}${(0,u.money)(Math.abs(_-t.avg))}`:''}`:`No other priced ${e.category.toLowerCase()} yet to compare with.`})}):null})(),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"big-gp",label:`GP (target ${H}%)`,value:Y?(0,u.pct)(Y.gpPct):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-x",label:`Multiple (${'inc'===h.multipleBasis?'inc VAT price':'ex VAT price'} \xf7 cost)`,value:Y&&E>0?(0,u.fmtX)(X):'\u2014',colour:x.colours.gold}),(0,f.jsx)(S,{testID:"big-profit",label:"Profit per plate (cash GP)",value:Y?(0,u.money)(Y.cashGp):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-foodcost",label:"Food cost",value:Y?(0,u.pct)(Y.foodCostPct):'\u2014'})]}),(0,f.jsxs)(a.Muted,{children:["GP is worked out on the price without VAT (",U,"% VAT). Gold: at or above target \xb7 amber: up to 5 points under \xb7 red: more than 5 under."]})]}),(0,f.jsxs)($,{n:4,title:"Photo, allergens and description",testID:"step-details",children:[(0,f.jsx)(k,{value:e.photo,onChange:e=>O({photo:e})}),(0,f.jsx)(a.T,{weight:"medium",children:"Allergens (14 UK allergens)"}),J.length?(0,f.jsx)(r.default,{testID:"allergen-suggest",children:(0,f.jsxs)(a.Muted,{children:["Suggested from the ingredients: ",J.map(e=>c.ALLERGENS.find(t=>t.id===e).short).join(', '),". Check before it goes on the menu."]})}):(0,f.jsx)(a.Muted,{children:"No allergens known from these ingredients yet. Tick any that apply."}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:c.ALLERGENS.map(t=>{const s=(e.allergens??[]).includes(t.id);return(0,f.jsx)(a.Chip,{label:`${s?'\u2713 ':''}${t.short}`,sub:J.includes(t.id)?'suggested':void 0,selected:s,onPress:()=>O({allergens:s?e.allergens.filter(e=>e!==t.id):[...e.allergens??[],t.id]})},t.id)})}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Short description",value:e.description??'',onChangeText:e=>O({description:e.slice(0,160)}),multiline:!0,placeholder:"Short description for the menu (up to 160 characters)",placeholderTextColor:"#7D776C",style:[a.styles.input,{minHeight:70,textAlignVertical:'top'}]}),(0,f.jsxs)(a.Muted,{children:[(e.description??'').length,"/160"]})]}),(0,f.jsxs)($,{n:5,title:"Save",testID:"step-save",children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(a.Button,{label:"Save as draft",kind:"secondary",testID:"save-draft",onPress:()=>te('draft'),style:{flexGrow:1}}),(0,f.jsx)(a.Button,{label:"Save as menu-ready dish",testID:"save-ready",onPress:()=>te('ready'),style:{flexGrow:1}})]}),D?(0,f.jsx)(r.default,{testID:"creator-msg",children:(0,f.jsx)(a.T,{size:15,colour:D.startsWith('Saved')?x.colours.ok:x.colours.amber,children:D})}):null,D.startsWith('Saved')?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.Button,{small:!0,label:"See saved dishes",onPress:o}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Start a new dish",onPress:()=>{l(),L(''),B(''),M('gp')}})]}):null]})]})}function k({value:e,onChange:t}){return(0,f.jsxs)(a.Row,{gap:10,children:[e?(0,f.jsx)(n.default,{testID:"dish-photo",source:{uri:e},style:{width:96,height:72,borderRadius:10}}):(0,f.jsx)(r.default,{style:{width:96,height:72,borderRadius:10,borderWidth:1,borderStyle:'dashed',borderColor:x.colours.border,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.Muted,{children:"No photo"})}),(0,f.jsxs)(r.default,{style:{gap:6},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:e?'Change photo':'Add photo (optional)',onPress:()=>{if('undefined'==typeof document)return;const e=document.createElement('input');e.type='file',e.accept='image/*',e.onchange=()=>{const s=e.files?.[0];if(!s)return;const i=new FileReader;i.onload=()=>{const e=new window.Image;e.onload=()=>{const s=Math.min(1,480/Math.max(e.width,e.height)),i=document.createElement('canvas');i.width=Math.round(e.width*s),i.height=Math.round(e.height*s),i.getContext('2d').drawImage(e,0,0,i.width,i.height),t(i.toDataURL('image/jpeg',.8))},e.src=String(i.result)},i.readAsDataURL(s)},e.click()}}),e?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Remove photo",onPress:()=>t(void 0)}):null]})]})}function A({initial:e,onDone:s,edit:n}){const[l,o]=(0,i.useState)(n?.name??e),[p,g]=(0,i.useState)(n?String(n.packSize):''),[h,m]=(0,i.useState)(n?.packUnit??'kg'),[y,b]=(0,i.useState)(n?(n.packPrice/100).toFixed(2):''),[w,T]=(0,i.useState)(n?.wastePct?String(n.wastePct):''),[P,I]=(0,i.useState)(n?.allergens??[]),[$,S]=(0,i.useState)(n?.servings?String(n.servings):''),[D,k]=(0,i.useState)(n?.servingName??''),[A,M]=(0,i.useState)(n?.supplier??''),G=!(!l.trim()||!C(p)||null==v(y)||''!==$.trim()&&!C($)),B={id:'probe',name:l,packSize:C(p)??0,packUnit:h,packPrice:v(y)??0,wastePct:0,servings:C($)??void 0,servingName:D.trim()||void 0},V=B.packSize&&B.packPrice?(0,u.perBaseUnit)(B):null,z=B.packPrice?(0,u.perServing)(B):null,W={name:l.trim(),packSize:C(p),packUnit:h,packPrice:v(y),wastePct:Math.min(90,C(w)??0),allergens:P,servings:C($)??void 0,servingName:D.trim().toLowerCase()||void 0,supplier:A.trim()||void 0};return(0,f.jsxs)(r.default,{testID:n?`edit-ingredient-${n.id}`:'new-ingredient',style:{gap:8,padding:12,borderRadius:14,borderWidth:1,borderColor:x.colours.gold,width:'100%'},children:[(0,f.jsx)(a.T,{weight:"semibold",center:!0,accessibilityRole:"header",children:n?`Edit ${n.name}`:'New ingredient'}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Ingredient name",value:l,onChangeText:o,placeholder:"e.g. Haddock",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Pack price and what you get for it, e.g. \xa3110 for 1 stone, or \xa340 for 5 kg"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:"ing-pack-price",accessibilityLabel:"Pack price in pounds",value:y,onChangeText:e=>b((0,j.sanitiseMoneyTyping)(e)),placeholder:"\xa3 price",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110,textAlign:'center'}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"for"}),(0,f.jsx)(t.TextInput,{testID:"ing-pack-size",accessibilityLabel:"Pack size",value:p,onChangeText:g,placeholder:"size",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]})]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:u.PACK_UNITS.map(e=>(0,f.jsx)(R,{testID:`ing-unit-${e}`,label:(0,u.unitName)(e,2),selected:h===e,onPress:()=>m(e)},e))}),(0,f.jsx)(a.Muted,{center:!0,children:"Optional: roughly how many servings or pieces one pack gives"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"averages"}),(0,f.jsx)(t.TextInput,{testID:"ing-servings",accessibilityLabel:"Averages how many servings or pieces",value:$,onChangeText:S,placeholder:"e.g. 30",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),(0,f.jsx)(t.TextInput,{testID:"ing-serving-name",accessibilityLabel:"What one is called, for example serving, breast or piece",value:D,onChangeText:k,placeholder:"serving / breast",placeholderTextColor:"#7D776C",style:[a.styles.input,L,{width:150,textAlign:'center'}]})]}),V||null!=z?(0,f.jsx)(r.default,{testID:"ing-derived",accessible:!0,accessibilityLabel:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(', '),children:(0,f.jsx)(a.T,{center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(' \xb7 ')})}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Supplier (optional)",value:A,onChangeText:M,placeholder:"Supplier (optional)",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Yield loss or waste percent (optional)",value:w,onChangeText:T,placeholder:"Trim / waste % (optional, for weights)",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Allergens in this ingredient (if known)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:c.ALLERGENS.map(e=>(0,f.jsx)(a.Chip,{label:e.short,selected:P.includes(e.id),onPress:()=>I(P.includes(e.id)?P.filter(t=>t!==e.id):[...P,e.id])},e.id))}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"ing-save",label:n?'Save ingredient':'Add ingredient',disabled:!G,onPress:()=>{if(n){const e=d.useGpCalc.getState();W.packPrice!==n.packPrice&&e.addPricePaid(n.id,W.packPrice);const t=d.useGpCalc.getState().ingredients.find(e=>e.id===n.id)??n;e.saveIngredient({...t,...W,packPrice:t.packPrice}),s(n.id)}else s(d.useGpCalc.getState().addIngredient(W))}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Cancel",onPress:()=>s()})]})]})}const L={minHeight:48};function R({label:e,selected:t,onPress:s,testID:i,accessibilityLabel:n}){return(0,f.jsx)(l.default,{testID:i,accessibilityRole:"button",accessibilityState:{selected:!!t},accessibilityLabel:`${n??e}${t?', selected':''}`,onPress:s,style:{minHeight:48,minWidth:48,paddingHorizontal:14,justifyContent:'center',alignItems:'center',borderRadius:24,borderWidth:1,borderColor:t?x.colours.gold:x.colours.border,backgroundColor:t?x.colours.gold:x.colours.surface2,maxWidth:'100%'},children:(0,f.jsx)(a.T,{size:x.font.small,weight:"medium",center:!0,colour:t?x.colours.onGold:x.colours.text,children:e})})}const M={draft:{label:'Draft',kind:'neutral'},ready:{label:'Menu-ready',kind:'gold'},published:{label:'On the menu',kind:'ok'}};function G({rid:e,canPublish:t,onEdit:s}){const{dishes:n,ingredients:l,settings:c,saveDish:p}=(0,d.useGpCalcView)(),[g,h]=(0,i.useState)('low'),[m,b]=(0,i.useState)(''),j=(0,i.useMemo)(()=>n.map(e=>{const t=(0,u.portionCost)(e,l,n);return{d:e,cost:t,g:e.menuPrice?(0,u.gpOf)(t,e.menuPrice,c.vatPct):null,x:e.menuPrice?(0,u.multipleOf)(t,e.menuPrice,c.vatPct,c.multipleBasis):0}}).sort((e,t)=>(e.g?e.g.gpPct:999)-(t.g?t.g.gpPct:999)),[n,l,c]),w='low'===g?j:[...j].reverse(),v=j.filter(e=>e.g&&e.g.gpPct{const s={};(t.allergens??[]).forEach(e=>{s[e]='contains'});const i=o.useStore.getState().addMenuItem({restaurantId:e,section:t.category??'Specials',name:t.name,description:t.description??'',price:t.menuPrice??null,dietary:[],allergens:s,prepMins:12,soldOut:!1,signOff:null});p({...t,status:'published',menuItemId:i}),b(`Published \u201c${t.name}\u201d to the menu (${t.category??'Specials'}). It needs allergen sign-off in Menu & allergens.`)};return(0,f.jsxs)(y.Box,{testID:"menu-gp",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"Saved dishes and items \xb7 Menu GP"}),(0,f.jsxs)(a.Muted,{children:[j.length," saved \xb7 ",v," below target \xb7 multiples on the ",'inc'===c.multipleBasis?'inc-VAT menu price':'ex-VAT price']}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Lowest GP first",selected:'low'===g,onPress:()=>h('low')}),(0,f.jsx)(a.Chip,{label:"Highest GP first",selected:'high'===g,onPress:()=>h('high')})]}),w.map(({d:e,cost:i,g:n,x:l})=>{const o=n?(0,u.toneFor)(n.gpPct,e.target):null;return(0,f.jsxs)(r.default,{testID:"gp-row",style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:4},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between',alignItems:'flex-start'},children:[(0,f.jsxs)(r.default,{style:{flex:1,gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",children:e.name}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Badge,{kind:M[e.status??'draft'].kind,label:M[e.status??'draft'].label}),e.category?(0,f.jsx)(a.Muted,{children:e.category}):null]}),(0,f.jsxs)(a.Muted,{children:["Cost ",(0,u.money)(i),e.menuPrice?` \xb7 price ${(0,u.money)(e.menuPrice)}`:' \xb7 no price yet']})]}),(0,f.jsxs)(r.default,{style:{alignItems:'flex-end'},children:[(0,f.jsx)(a.T,{size:22,weight:"bold",colour:o?T[o]:x.colours.muted,children:n?(0,u.pct)(n.gpPct):'\u2014'}),(0,f.jsx)(a.T,{size:16,weight:"semibold",colour:x.colours.gold,children:n&&i>0?(0,u.fmtX)(l):''})]})]}),n&&n.gpPcts(e)}),t&&'ready'===e.status?(0,f.jsx)(a.Button,{small:!0,label:"Publish to menu",accessibilityLabel:`Publish ${e.name} to menu`,onPress:()=>C(e)}):null,t||'ready'!==e.status?null:(0,f.jsx)(a.Muted,{children:"Waiting for a manager to publish"})]})]},e.id)}),m?(0,f.jsx)(r.default,{testID:"publish-msg",children:(0,f.jsx)(a.T,{size:14,colour:x.colours.ok,children:m})}):null]})}function B(){const{settings:e,setSettings:t}=(0,d.useGpCalcView)(),s=e.priceBasis??'latest',i=e.avgOf??5;return(0,f.jsxs)(r.default,{testID:"price-basis",style:{gap:6},children:[(0,f.jsx)(a.T,{weight:"medium",children:"Cost dishes using"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Chip,{label:"Latest price paid",selected:'latest'===s,onPress:()=>t({priceBasis:'latest'})}),(0,f.jsx)(a.Chip,{label:`Average price (last ${i})`,selected:'average'===s,onPress:()=>t({priceBasis:'average'})})]}),'average'===s?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Muted,{children:"Average of the last"}),[3,5,10].map(e=>(0,f.jsx)(a.Chip,{label:`${e} prices`,selected:i===e,onPress:()=>t({avgOf:e})},e))]}):null,(0,f.jsx)(a.Muted,{children:'average'===s?'Averages smooth out price swings, so GP doesn\u2019t jump every delivery.':'Uses the most recent price you paid.'})]})}function V(){const{ingredients:e,dishes:s,settings:n,cardCosts:l}=(0,d.useGpCalcView)(),[o,c]=(0,i.useState)(''),[u,p]=(0,i.useState)(''),[g,h]=(0,i.useState)(!1),m=e.filter(e=>!u.trim()||`${e.name} ${e.supplier??''}`.toLowerCase().includes(u.trim().toLowerCase())).slice().sort((e,t)=>e.name.localeCompare(t.name));return(0,f.jsxs)(y.Box,{testID:"calc-items",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",center:!0,accessibilityRole:"header",children:"Ingredient prices"}),(0,f.jsx)(a.Muted,{center:!0,children:"What you pay and what a pack gives you. Recipe cards and dishes cost themselves from this list and update when a price changes."}),(0,f.jsx)(a.Button,{testID:"ing-add-new",label:"Add an ingredient",onPress:()=>{h(!0),c('')}}),g?(0,f.jsx)(A,{initial:u,onDone:e=>{h(!1),e&&c('Added to the price list.')}}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredient prices",value:u,onChangeText:p,placeholder:"Search ingredients or suppliers",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(B,{}),m.map(e=>{return(0,f.jsx)(z,{i:e,n:n.avgOf??5,basis:n.priceBasis??'latest',used:(t=e.id,s.filter(e=>e.lines.some(e=>e.ingId===t)).length+Object.values(l??{}).filter(e=>e.lines.some(e=>e.ingId===t)).length),onSaved:e=>c(e)},e.id);var t}),m.length?null:(0,f.jsx)(r.default,{testID:"ing-empty",style:{alignItems:'center',paddingVertical:12},children:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:e.length?'No ingredients match.':'No ingredient prices yet. Add the first one above.'})}),o?(0,f.jsx)(r.default,{testID:"items-msg",children:(0,f.jsx)(a.T,{size:14,center:!0,colour:x.colours.ok,children:o})}):null]})}function z({i:e,used:s,n:n,basis:l,onSaved:o}){const[c,p]=(0,i.useState)(String(e.wastePct)),[g,h]=(0,i.useState)(''),[m,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(!1),T=(0,u.priceStats)(e,n),P=c!==String(e.wastePct),I=v(g),$=(0,u.perBaseUnit)(e),S=(0,u.perServing)(e),D=`${e.name}, ${(0,u.money)(e.packPrice)} for ${e.packSize} ${(0,u.unitName)(e.packUnit,e.packSize)}${e.servings?`, averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}, ${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:''}${$?`, ${(0,u.money)($.pence)} a ${$.per}`:''}${e.supplier?`, from ${e.supplier}`:''}`;return m?(0,f.jsx)(A,{initial:"",edit:e,onDone:t=>{y(!1),t&&o(`Saved ${e.name}. Recipe cards and dishes re-costed.`)}}):(0,f.jsxs)(r.default,{testID:`item-${e.id}`,style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:6},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:D,style:{gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",size:18,center:!0,children:e.name}),(0,f.jsxs)(a.T,{testID:`pack-${e.id}`,center:!0,colour:x.colours.goldLight,children:[(0,u.money)(e.packPrice)," for ",e.packSize," ",(0,u.unitName)(e.packUnit,e.packSize),e.servings?` \xb7 averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}`:'']}),(0,f.jsx)(a.T,{testID:`derived-${e.id}`,center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=S?`${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:'',$?`${(0,u.money)($.pence)} a ${$.per}`:''].filter(Boolean).join(' \xb7 ')}),(0,f.jsx)(a.Muted,{center:!0,children:[s?`used in ${s}`:'not used yet',e.supplier,e.updatedAt?`updated ${new Date(e.updatedAt).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:''].filter(Boolean).join(' \xb7 ')})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsxs)(r.default,{testID:`latest-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'latest'===l?x.colours.gold:x.colours.border},children:[(0,f.jsx)(a.Muted,{children:"Latest"}),(0,f.jsx)(a.T,{weight:"bold",children:(0,u.money)(T.latest)})]}),(0,f.jsxs)(r.default,{testID:`avg-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'average'===l?x.colours.gold:x.colours.border},children:[(0,f.jsxs)(a.Muted,{children:["Average (",T.count,")"]}),(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.gold,children:(0,u.money)(T.avg)})]}),T.count>1?(0,f.jsxs)(r.default,{style:{paddingHorizontal:10,paddingVertical:6},children:[(0,f.jsx)(a.Muted,{children:"Range"}),(0,f.jsxs)(a.T,{size:14,children:[(0,u.money)(T.min),"\u2013",(0,u.money)(T.max)]})]}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:`Price paid for ${e.name}`,value:g,onChangeText:e=>h((0,j.sanitiseMoneyTyping)(e)),placeholder:"price paid",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110}]}),(0,f.jsx)(a.Button,{small:!0,label:"Add price paid",testID:`add-price-${e.id}`,disabled:!I,onPress:()=>{d.useGpCalc.getState().addPricePaid(e.id,I),h(''),o(`Recorded ${(0,u.money)(I)} for ${e.name}. Dishes re-costed.`)}})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${e.name}`,value:c,onChangeText:p,keyboardType:"decimal-pad",style:[a.styles.input,L,{width:60}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"% waste"}),P?(0,f.jsx)(a.Button,{small:!0,label:"Save",disabled:null==C(c),onPress:()=>{d.useGpCalc.getState().saveIngredient({...e,wastePct:Math.min(90,C(c))}),o(`Saved ${e.name}. Dishes updated.`)}}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:`ing-edit-${e.id}`,label:"Edit",accessibilityLabel:`Edit ${e.name}`,onPress:()=>y(!0)}),b?null:(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:`ing-delete-${e.id}`,label:"Delete",accessibilityLabel:`Delete ${e.name}`,onPress:()=>w(!0)})]}),b?(0,f.jsxs)(r.default,{testID:`ing-delete-confirm-${e.id}`,style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Delete ",e.name," from the price list?",s?` ${s} ${1===s?'dish or card uses':'dishes or cards use'} it and will show it as removed.`:'']}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"danger",testID:`ing-delete-yes-${e.id}`,label:"Yes, delete",accessibilityLabel:`Yes, delete ${e.name}`,onPress:()=>{d.useGpCalc.getState().removeIngredient(e.id),o(`Deleted ${e.name}.`)}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Keep it",onPress:()=>w(!1)})]})]}):null]})}function W(){const{settings:e,setSettings:s}=(0,d.useGpCalcView)(),[n,l]=(0,i.useState)(String(e.vatPct)),[r,o]=(0,i.useState)(String(e.defaultTarget));return(0,f.jsxs)(y.Box,{testID:"calc-settings",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"VAT and rounding"}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"VAT rate %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"VAT rate %",value:n,onChangeText:e=>{l(e);const t=C(e);null!=t&&t<=50&&s({vatPct:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(B,{}),(0,f.jsx)(a.Toggle,{label:"Round suggested prices up to .50 / .95",value:e.pricePoints,onChange:e=>s({pricePoints:e})}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Default target GP %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Default target GP %",value:r,onChangeText:e=>{o(e);const t=C(e);null!=t&&t<95&&s({defaultTarget:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(a.T,{weight:"medium",children:"Cost multiple (x) is based on"}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Inc VAT (menu price)",selected:'inc'===e.multipleBasis,onPress:()=>s({multipleBasis:'inc'})}),(0,f.jsx)(a.Chip,{label:"Ex VAT",selected:'ex'===e.multipleBasis,onPress:()=>s({multipleBasis:'ex'})})]}),(0,f.jsx)(a.Muted,{children:"GP % uses the ex-VAT price. The price multiple is the menu price divided by ingredient cost."})]})}const N='#3A2F1E';function O({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n,said:l}){return(0,f.jsxs)(r.default,{testID:i,accessible:!0,accessibilityLabel:l??`${e}, ${t}${n?`, ${n}`:''}`,style:{flexGrow:1,flexBasis:128,minWidth:0,padding:10,borderRadius:14,backgroundColor:x.colours.surface,borderWidth:1,borderColor:x.colours.accentBorder,alignItems:'center',gap:2},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:e}),(0,f.jsx)(a.T,{size:28,weight:"bold",center:!0,colour:s,children:t}),n?(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:n}):null]})}},1157,[812,779,17,319,219,385,85,777,816,905,845,906,909,876,920,867,804,889,907,840,8]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1500,7 +1500,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return f}});var t=r(d[0]);r(d[1]);var n=r(d[2]),u=r(d[3]),c=r(d[4]);function f(){return'owner'!==u.APP_VARIANT?(0,c.jsx)(t.Redirect,{href:u.ENTRY[u.APP_VARIANT]}):(0,c.jsx)(n.OwnerApp,{})}},1417,[13,17,1418,856,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.OwnerApp=function(){return null}},1418,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1419,[13,17,856,1420,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1420,[1421,1425,813,912,1072,1426,1209,1210,1028,1025,1026,1427,1429,1432,1153,891,978,1434,975,880,1031,1032,1435,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1436,1066,1084,1086,1081,1027,1010,1057,1443,1444,1445,1453,1454,920,219,1246,1182,1189,1450,1202,1185,1459,1186,878,1212,1213,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1420,[1421,1425,813,912,1072,1426,1209,1210,1028,1025,1026,1427,1429,1432,1153,891,978,1434,975,880,1031,1032,1435,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1436,1066,1084,1086,1081,1027,1010,1057,1443,1444,1445,1453,1454,920,219,1246,1182,1189,1450,1202,1185,1459,1186,878,1212,1213,884,776,899,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.TablePlan=function({startStep:e}){const{rid:s,r:n,now:w,me:f,role:S}=(0,b.useCtx)(6e4),T=(0,x.usePlan)(s),[P,C]=(0,t.useState)(null),[D,I]=(0,t.useState)(T.areas[0]?.id??''),[M,B]=(0,t.useState)(null),N=T.areas.find(e=>e.id===D)??T.areas[0],O=(0,x.planCounts)(T),A=(0,p.closedAreasAt)((0,p.useBlocks)(e=>e.blocks),s,(0,y.ymd)(w),`${String(w.getHours()).padStart(2,'0')}:${String(w.getMinutes()).padStart(2,'0')}`);return(0,k.jsxs)(a.default,{style:{gap:12},testID:"tableplan-page",children:[(0,k.jsxs)(h.Muted,{children:["The table plan for ",n.name,". Each venue has its own plan; it drives the Display floor view, walk-ins and which tables online bookings can use."]}),(0,k.jsxs)(h.Card,{children:[(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},wrap:!0,gap:8,children:[(0,k.jsxs)(a.default,{children:[(0,k.jsxs)(h.T,{size:20,weight:"bold",colour:j.colours.gold,children:[O.tables," tables \xb7 ",O.seats," seats"]}),(0,k.jsxs)(h.Muted,{children:[T.areas.length," areas \xb7 ",T.joins.length," joined ",1===T.joins.length?"pair":"pairs"]})]}),(0,k.jsx)(h.Button,{label:"Open table plan designer",testID:"open-designer",onPress:()=>C(e??'arrange')})]}),v.RELEASE.planPhoto?(0,k.jsx)(m.PlanPhoto,{rid:s}):null,(0,k.jsx)(a.default,{style:{gap:6},children:T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return(0,k.jsxs)(a.default,{testID:`area-summary-${e.id}`,style:{width:'100%',minWidth:0,gap:8,alignItems:'stretch',borderTopWidth:1,borderTopColor:j.colours.border,paddingTop:12,paddingBottom:6},children:[(0,k.jsx)(h.T,{center:!0,weight:"semibold",colour:(0,j.brandColour)(e.colour),children:e.name}),e.dogs||e.outdoor?(0,k.jsxs)(h.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[e.dogs?(0,k.jsx)(h.Badge,{kind:"gold",label:"\ud83d\udc3e Dogs allowed"}):null,e.outdoor?(0,k.jsx)(h.Badge,{kind:A.has(e.id)?'red':'neutral',label:A.has(e.id)?'\ud83c\udf27 Closed for weather':'\ud83c\udf26 Outdoor'}):null]}):null,e.label?(0,k.jsx)(h.Muted,{center:!0,size:14,children:e.label}):null,(0,k.jsxs)(h.Muted,{center:!0,children:[s.tables," tables \xb7 ",s.seats," seats"]})]},e.id)})}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Areas",onPress:()=>C('areas')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Tables",onPress:()=>C('tables')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Arrange",onPress:()=>C('arrange')})]})]}),T.areas.some(e=>e.outdoor)?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(h.T,{weight:"semibold",children:"Weather"}),(0,k.jsx)(h.Muted,{children:"Closes the outdoor areas for the rest of today: no online bookings or walk-ins there, and the Display shows them as closed. Uses Block bookings, so you can reopen in one tap."}),(0,k.jsx)(c.CloseGardenButton,{rid:s,r:n,now:w,by:f})]}):null,N?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(o.AreaTabs,{plan:T,area:N.id,onPick:I,closed:A,counts:Object.fromEntries(T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return[e.id,`${s.tables} \xb7 ${s.seats}`]}))}),(0,k.jsx)(a.default,{pointerEvents:"none",style:{borderRadius:12,overflow:'hidden'},children:(0,k.jsx)(r.FloorCanvas,{plan:T,areaId:N.id,mode:"live",fit:"width",maxH:360,sectionColours:!0})}),(0,k.jsx)(h.Muted,{children:"Preview only. Open the designer to change it."})]}):null,M?(0,k.jsx)(h.Banner,{kind:"success",title:M}):null,(0,k.jsx)(l.default,{visible:!!P,animationType:"slide",onRequestClose:()=>C(null),presentationStyle:"fullScreen",children:(0,k.jsx)(a.default,{style:{flex:1,backgroundColor:j.colours.bg},children:P?(0,k.jsx)(u.PlanDesigner,{initial:T,venue:n.name,mode:"managers",role:S,startStep:P,onSave:e=>{x.useFloor.getState().setPlan(s,e),C(null),B('Table plan saved. The Display uses it straight away.')},onLiveChange:e=>{x.useFloor.getState().setPlan(s,e),B('Live seating plan updated on every screen.')},onCancel:()=>C(null)}):null})})]})},_e.DisplaySettingsPage=function(){const{rid:e,role:s}=(0,b.useCtx)(6e4),t=(0,x.useDisplaySettings)(e),n=s=>x.useFloor.getState().setSettings(e,s);return(0,k.jsxs)(a.default,{style:{gap:14},children:[(0,k.jsxs)(a.default,{style:{gap:6},testID:"privacy-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Privacy on the Display"}),'owner'===s?(0,k.jsx)(h.Toggle,{label:"Privacy mode (recommended)",value:t.privacy,onChange:e=>n({privacy:e})}):(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},children:[(0,k.jsx)(h.T,{children:"Privacy mode"}),(0,k.jsxs)(h.T,{weight:"semibold",children:[t.privacy?'On':'Off'," \xb7 owner only"]})]}),(0,k.jsx)(h.Muted,{children:"On: guest surnames show as initials (Campbell \u2192 C.), and no phone numbers, emails, notes or allergy details appear on the main screen (an icon only). Staff tap for details in a panel that closes after 20 seconds."})]}),(0,k.jsxs)(a.default,{style:{gap:6},children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Screensaver"}),(0,k.jsx)(h.T,{size:14,children:"Start after nobody touches the Display for"}),(0,k.jsx)(h.Row,{gap:6,children:[1,2,5,10].map(e=>(0,k.jsx)(a.default,{testID:`idle-${e}`,children:(0,k.jsx)(h.Chip,{label:`${e} min`,selected:t.idleMins===e,onPress:()=>n({idleMins:e})})},e))}),(0,k.jsx)(h.Toggle,{label:"Ask for a staff PIN on wake",value:t.pinOn,onChange:e=>n({pinOn:e})}),t.pinOn?(0,k.jsx)(S,{rid:e}):null,(0,k.jsx)(h.Muted,{children:"Used on this Display until a screensaver is saved in Settings \u203a Display screensaver (style, idle time and night dim for every Display, changed live). Any touch wakes it straight away and that first touch doesn\u2019t press anything. Where the browser allows, the Display also asks to keep the screen on."})]}),(0,k.jsx)(T,{}),(0,k.jsxs)(a.default,{style:{gap:6},testID:"wipe-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Shared tablet or phone"}),(0,k.jsx)(h.Muted,{children:"Selling or handing over this device, or it was used by someone who has left? Sign out and wipe it."}),(0,k.jsx)(f.WipeDevice,{})]}),(0,k.jsx)(h.Banner,{kind:"info",title:"Settings live on this device",children:"They\u2019re saved in this browser for the venue and picked up by the Display app on the same device."})]})};var s=_r(d[0]),t=_r(d[1]),n=_r(d[2]),l=e(_r(d[3])),a=e(_r(d[4])),o=_r(d[5]),r=_r(d[6]),u=_r(d[7]),c=_r(d[8]),h=_r(d[9]),p=_r(d[10]),x=_r(d[11]),y=_r(d[12]),j=_r(d[13]),b=_r(d[14]),w=_r(d[15]),f=_r(d[16]),m=_r(d[17]),v=_r(d[18]),k=_r(d[19]);function S({rid:e}){const n=(0,x.useDisplaySettings)(e),[l,o]=(0,t.useState)(''),[r,u]=(0,t.useState)(''),[c,p]=(0,t.useState)(null),y=l?(0,w.wakePinProblem)(l):null,b=[h.styles.input,{width:130}];return(0,k.jsxs)(a.default,{style:{gap:6},testID:"wake-pin-setting",children:[n.pinDefault?(0,k.jsx)(a.default,{testID:"wake-pin-default",children:(0,k.jsx)(h.Banner,{kind:"warn",title:"Change the wake PIN",children:"This Display still uses the starting PIN, 2580, which anyone could guess. Set a new 6 to 8 digit PIN below."})}):(0,k.jsxs)(h.Muted,{children:["A wake PIN of ",n.pinLen," digits is set. Type a new one to change it."]}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(s.TextInput,{testID:"wake-pin-new",accessibilityLabel:"New wake PIN",value:l,onChangeText:e=>{o(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"New PIN (6\u20138 digits)",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(s.TextInput,{testID:"wake-pin-again",accessibilityLabel:"New wake PIN again",value:r,onChangeText:e=>{u(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"Type it again",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(h.Button,{small:!0,testID:"wake-pin-save",label:"Save PIN",disabled:!l||!r,onPress:()=>{const s=(0,w.wakePinProblem)(l);s?p(s):l===r?(x.useFloor.getState().setSettings(e,(0,w.makeWakePin)(l)),o(''),u(''),p('Wake PIN saved. Tell the team in person; it isn\u2019t shown again.')):p('The two PINs don\u2019t match.')}})]}),c||y?(0,k.jsx)(h.Muted,{children:c??y}):null]})}function T(){const[e,s]=(0,t.useState)((0,n.flapSoundOn)());return(0,k.jsxs)(a.default,{style:{gap:6},testID:"flap-sound-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Covers counter sound"}),(0,k.jsx)(h.Toggle,{label:"Soft flap click when the Covers change (Display only)",value:e,onChange:e=>{(0,n.setFlapSound)(e),s(e)}}),(0,k.jsx)(h.Muted,{children:"Off by default. Only this device clicks; phones never do."})]})}},1421,[812,17,1018,378,85,1108,1109,1367,1400,777,995,998,863,804,1057,999,1422,1423,1020,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.WipeDevice=function({compact:e}){const f=(0,u.useDisplaySettings)(p.VENUE_RID),[v,T]=(0,s.useState)(!1),[w,j]=(0,s.useState)(''),[D,C]=(0,s.useState)(!1),I='display'===h.APP_VARIANT&&f.pinOn,P=!I||(0,b.wakePinMatches)(f,w);return v?(0,x.jsxs)(o.default,{testID:"wipe-confirm-box",style:{gap:6,marginTop:6},children:[(0,x.jsx)(l.T,{size:e?12:14,children:"Sign out and remove everything CoverCharge keeps on this device: sign-ins, pairing, saved screens and any changes not sent yet. The venue\u2019s shared data is not touched. To use it again, open a personal link or pair the Display again."}),I?(0,x.jsx)(t.TextInput,{testID:"wipe-pin",value:w,onChangeText:j,placeholder:"Display wake PIN",placeholderTextColor:c.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",accessibilityLabel:"Display wake PIN",style:{borderWidth:1,borderColor:'rgba(255,255,255,0.2)',borderRadius:8,paddingHorizontal:10,paddingVertical:6,color:c.colours.text}}):null,(0,x.jsxs)(o.default,{style:{flexDirection:'row',gap:8},children:[(0,x.jsx)(n.default,{testID:"wipe-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, wipe this device",disabled:!P||D,onPress:()=>{C(!0),(0,y.wipeThisDevice)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:P?c.colours.red:'rgba(255,255,255,0.08)'},children:(0,x.jsx)(l.T,{size:12,weight:"semibold",children:D?'Wiping\u2026':'Yes, wipe this device'})}),(0,x.jsx)(n.default,{accessibilityRole:"button",accessibilityLabel:"Cancel",onPress:()=>{T(!1),j('')},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,x.jsx)(l.T,{size:12,children:"Cancel"})})]})]}):(0,x.jsx)(n.default,{testID:"wipe-device",accessibilityRole:"button",accessibilityLabel:"Sign out and wipe this device",onPress:()=>T(!0),style:{alignSelf:'flex-start',marginTop:e?4:0,minHeight:44,justifyContent:'center'},children:(0,x.jsx)(l.T,{size:e?12:14,colour:c.colours.gold,children:"Sign out and wipe this device\u2026"})})};var t=r(d[0]),s=r(d[1]),n=e(r(d[2])),o=e(r(d[3])),l=r(d[4]),c=r(d[5]),u=r(d[6]),p=r(d[7]),b=r(d[8]),h=r(d[9]),y=r(d[10]),x=r(d[11])},1422,[812,17,385,85,777,804,998,805,999,856,899,8]); __d(function(g,r,_i,_a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.PlanPhoto=function({rid:e}){const t=(0,n.usePlan)(e),b=(0,n.useFloor)(e=>e.setPlan),[y,f]=(0,a.useState)(null),[x,w]=(0,a.useState)(null),[v,j]=(0,a.useState)(null),[k,S]=(0,a.useState)(''),[P,T]=(0,a.useState)(!1),I=async e=>{let a;T(!0);try{const{data:t,error:l}=await(0,u.getSupabase)().functions.invoke('plan-photo-read',{body:{image:e}});a=l?{ok:!1,message:'The plan could not be read. The photo is still here.'}:{ok:!0,tables:(0,o.cleanFindings)(t)}}catch{a={ok:!1,message:'The plan could not be read. The photo is still here.'}}finally{T(!1)}const t=(0,o.planReadAfter)(e,a);w(t.photo),f(t.rows&&t.rows.length?t.rows:null),S(t.note)},L=async()=>{S('');const e=(await(0,c.pickPhotos)({source:'camera'}))[0];e?(w(e),await I(e)):S('No photo taken.')};return(0,p.jsxs)(l.default,{testID:"plan-photo",style:{width:'100%',alignItems:'center',gap:10},children:[(0,p.jsx)(s.Button,{testID:"plan-photo-camera",label:P?'Reading the plan\u2026':'Take a picture of the table plan',accessibilityLabel:"Take a picture of a hand-drawn table plan",disabled:P,onPress:()=>{L()}}),k?(0,p.jsx)(s.Muted,{center:!0,testID:"plan-photo-note",children:k}):null,x&&!P?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-retry",label:"Read this photo again",accessibilityLabel:"Read this photo again",onPress:()=>{I(x)}}):null,y?(0,p.jsx)(l.default,{testID:"plan-photo-review",style:{width:'100%'},children:(0,p.jsxs)(s.Card,{style:{alignItems:'center',width:'100%'},children:[(0,p.jsx)(s.T,{center:!0,weight:"bold",colour:h.colours.gold,children:"Check what was read"}),(0,p.jsx)(s.Muted,{center:!0,children:"Nothing is saved until you tap Save the plan."}),y.map((e,a)=>(0,p.jsxs)(l.default,{style:{width:'100%',gap:6},children:[(0,p.jsx)(s.Field,{label:"Area",accessibilityLabel:`Area ${a+1}`,value:e.area,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,area:e}:t))}),(0,p.jsx)(s.Field,{label:"Table",accessibilityLabel:`Table ${a+1}`,value:e.name,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,name:e}:t))}),(0,p.jsx)(s.Field,{label:"Seats",accessibilityLabel:`Seats at table ${a+1}`,value:String(e.seats),keyboardType:"number-pad",onChangeText:e=>f(y.map((t,l)=>l===a?{...t,seats:Math.max(1,Math.min(30,Number(e.replace(/\D/g,''))||1))}:t))}),(0,p.jsx)(s.Button,{kind:"ghost",label:`Remove ${e.name||'table'}`,accessibilityLabel:`Remove ${e.name||'table'}`,onPress:()=>f(y.filter((e,t)=>t!==a))})]},`${e.area}-${e.name}-${a}`)),(0,p.jsx)(s.Button,{testID:"plan-photo-save",label:"Save the plan",accessibilityLabel:"Save the checked table plan",disabled:!y.length,onPress:()=>{if(!y?.length)return;j(t);const a=[...t.areas],l=[...t.tables];for(const e of y){let t=a.find(a=>a.name.toLowerCase()===e.area.toLowerCase());t||(t={id:(0,i.fid)('area'),name:e.area},a.push(t));const s=(0,i.sizeFor)(e.seats),n=l.filter(e=>e.areaId===t.id).length;l.push({id:(0,i.fid)('t'),name:e.name,areaId:t.id,shape:s.shape,minSeats:1,maxSeats:e.seats,x:40+n%6*140,y:40+120*Math.floor(n/6),w:s.w,h:s.h,rot:0,online:!0})}b(e,{...t,areas:a,tables:l}),f(null),S('Plan saved. Undo puts the previous plan back.')}})]})}):null,v?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-undo",label:"Undo table plan",accessibilityLabel:"Undo the table plan and restore the previous one",onPress:()=>{b(e,v),j(null),S('Previous plan restored.')}}):null]})};var e,a=r(d[0]),t=r(d[1]),l=(e=t)&&e.__esModule?e:{default:e},s=r(d[2]),n=r(d[3]),o=r(d[4]),i=r(d[5]),h=r(d[6]),c=r(d[7]),u=r(d[8]),p=r(d[9])},1423,[17,85,777,998,1424,842,804,1038,928,8]); @@ -1576,7 +1576,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1493,[17,24,85,409,777,857,920,899,880,805,804,1494,1495,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CAR_BUTTONS",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"MENU_BUTTON",{enumerable:!0,get:function(){return l}}),e.menuSizes=function(o,l){const s=Math.round(Math.max(300,Math.min(o-24,o>=1600?520:o>=1200?460:420))),t=Math.floor((s-40-2)/3),n=Math.floor(Math.max(84,(l-72-40)/4)),c=l>=1e3?15:13,b=Math.round(1.4*c),h=Math.max(52,Math.min(76,n-b-18,t-28));return{panelW:s,colW:t,per:n,circle:h,label:c,lineH:b,icon:Math.round(.44*h),cols:3,rows:4,head:72,pad:20}},Object.defineProperty(e,"spokenCode",{enumerable:!0,get:function(){return s}});const o=[{id:'rota',label:'Rota',short:'Rota',icon:'rota',pages:[{id:'rota',label:'Rota'}]},{id:'signoff',label:'Sign off hours',short:'Sign off',icon:'signoff',pages:[{id:'signoff',label:'Sign off hours'},{id:'timesheets',label:'Timesheets'}]},{id:'menu',label:'Menu & sold out',short:'Menu',icon:'menu',pages:[{id:'soldout',label:'Sold out'},{id:'menu',label:'Menu & allergens'},{id:'tableqr',label:'Table QR codes'}]},{id:'bookings',label:'Bookings',short:'Bookings',icon:'bookings',pages:[{id:'@bookings',label:'Bookings'},{id:'lookback',label:'Look back'}]},{id:'noshows',label:'No-shows',short:'No-shows',icon:'noshow',pages:[{id:'@noshows',label:'No-shows'}]},{id:'chat',label:'Staff chat',short:'Chat',icon:'chat',pages:[{id:'@chat',label:'Staff chat'}]},{id:'stock',label:'Stock & suppliers',short:'Stock',icon:'stock',pages:[{id:'kitchencosts',label:'Deliveries & GP'},{id:'trackedstock',label:'Tracked stock'},{id:'orderlists',label:'Order lists'},{id:'suppliers',label:'Suppliers'}]},{id:'loyalty',label:'Loyalty',short:'Loyalty',icon:'loyalty',pages:[{id:'loyalty',label:'Stamp card'}]},{id:'takings',label:'Takings & tips',short:'Takings',icon:'takings',pages:[{id:'cashup',label:'Cash up & sales'},{id:'tips',label:'Tips'},{id:'spendhead',label:'Spend per head'}]},{id:'safety',label:'Food safety',short:'Safety',icon:'safety',pages:[{id:'haccp',label:'CookSafe log'}]},{id:'reviews',label:'Reviews',short:'Reviews',icon:'reviews',pages:[{id:'reviews',label:'Reviews'}]}],l=56;const s=o=>o.split('').join(' ')},1494,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ParkedOnly=function({small:e}){return(0,s.jsx)(n.default,{testID:"parked-only",accessible:!0,accessibilityLabel:"Parked only. Use this screen only when the car is in Park.",style:{minHeight:e?28:36,paddingHorizontal:e?8:12,borderRadius:999,borderWidth:1,borderColor:t.colours.amber,backgroundColor:'rgba(232,168,56,0.12)',alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,s.jsx)(o.T,{size:e?11:13,weight:"semibold",colour:t.colours.amber,center:!0,children:"PARKED ONLY"})})},r(d[0]);var e,l=r(d[1]),n=(e=l)&&e.__esModule?e:{default:e},o=r(d[2]),t=r(d[3]),s=r(d[4])},1495,[17,85,777,804,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1496,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1496,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1497,[813,779,17,974,385,85,856,899,976,804,777,1352,971,880,1498,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.SyncDeviceActions=function(){const e=(0,o.useSync)(),[f,p]=(0,s.useState)(!1),h='live'===e.mode||'offline'===e.mode;return e.venueId&&h?(0,b.jsxs)(b.Fragment,{children:[f?(0,b.jsxs)(c.default,{style:{gap:6,marginTop:6},children:[(0,b.jsx)(u.T,{size:12,children:"Disconnect this device? Your changes stay on it; open your personal invite link to connect again."}),(0,b.jsxs)(c.default,{style:{flexDirection:'row',gap:8},children:[(0,b.jsx)(t.default,{testID:"unpair-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, disconnect",onPress:()=>{p(!1),(0,o.disconnectStaff)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:l.colours.red},children:(0,b.jsx)(u.T,{size:12,weight:"semibold",children:"Yes, disconnect"})}),(0,b.jsx)(t.default,{accessibilityRole:"button",accessibilityLabel:"Keep connected",onPress:()=>p(!1),style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,b.jsx)(u.T,{size:12,children:"Keep"})})]})]}):(0,b.jsx)(t.default,{testID:"unpair",accessibilityRole:"button",accessibilityLabel:"Disconnect this device",onPress:()=>p(!0),style:{marginTop:6,alignSelf:'flex-start'},children:(0,b.jsx)(u.T,{size:12,colour:l.colours.gold,children:"Disconnect this device\u2026"})}),(0,b.jsx)(n.WipeDevice,{compact:!0})]}):null};var s=r(d[0]),n=r(d[1]),t=e(r(d[2])),c=e(r(d[3])),o=r(d[4]),l=r(d[5]),u=r(d[6]),b=r(d[7])},1498,[17,1422,385,85,899,804,777,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1499,[]); diff --git a/chef-app/admin.html b/chef-app/admin.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/admin.html +++ b/chef-app/admin.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer.html b/chef-app/customer.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer.html +++ b/chef-app/customer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage.html b/chef-app/customer/anchorage.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage.html +++ b/chef-app/customer/anchorage.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/book.html b/chef-app/customer/anchorage/book.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/book.html +++ b/chef-app/customer/anchorage/book.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/feedback.html b/chef-app/customer/anchorage/feedback.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/feedback.html +++ b/chef-app/customer/anchorage/feedback.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/gift.html b/chef-app/customer/anchorage/gift.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/gift.html +++ b/chef-app/customer/anchorage/gift.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/lost.html b/chef-app/customer/anchorage/lost.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/lost.html +++ b/chef-app/customer/anchorage/lost.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/loyalty.html b/chef-app/customer/anchorage/loyalty.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/loyalty.html +++ b/chef-app/customer/anchorage/loyalty.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/merch.html b/chef-app/customer/anchorage/merch.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/merch.html +++ b/chef-app/customer/anchorage/merch.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/offers.html b/chef-app/customer/anchorage/offers.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/offers.html +++ b/chef-app/customer/anchorage/offers.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/refer.html b/chef-app/customer/anchorage/refer.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/refer.html +++ b/chef-app/customer/anchorage/refer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/waitlist.html b/chef-app/customer/anchorage/waitlist.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/waitlist.html +++ b/chef-app/customer/anchorage/waitlist.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/anchorage/whatson.html b/chef-app/customer/anchorage/whatson.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/anchorage/whatson.html +++ b/chef-app/customer/anchorage/whatson.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/basket.html b/chef-app/customer/basket.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/basket.html +++ b/chef-app/customer/basket.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/customer/profile.html b/chef-app/customer/profile.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/customer/profile.html +++ b/chef-app/customer/profile.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/demo.html b/chef-app/demo.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/demo.html +++ b/chef-app/demo.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/display.html b/chef-app/display.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/display.html +++ b/chef-app/display.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/index.html b/chef-app/index.html index 9eaa5f7321ca4d3e57f530c1c185915b0ce1a750..2a94aa4197890beadd33a4460609aaefcb768bdf 100644 --- a/chef-app/index.html +++ b/chef-app/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/kitchen.html b/chef-app/kitchen.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/kitchen.html +++ b/chef-app/kitchen.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/owner.html b/chef-app/owner.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/owner.html +++ b/chef-app/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/staff.html b/chef-app/staff.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/staff.html +++ b/chef-app/staff.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/chef-app/sw.js b/chef-app/sw.js index 7b400b337b4e5d09c91b5e93250babdee6203ebd..8f3cb01d7516816cdf05c39142ade5499583de25 100644 --- a/chef-app/sw.js +++ b/chef-app/sw.js @@ -1,7 +1,7 @@ // Anchorage Head Chef service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-chef-f22ed7ed0c"; +const V = "cc-chef-34f7529cea"; const BASE = "/chef-app/"; -const PRECACHE = ["/chef-app/apple-touch-icon.png", "/chef-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/chef-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/chef-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/chef-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/chef-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/chef-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/chef-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/chef-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/chef-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/chef-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/chef-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/chef-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/chef-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/chef-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/chef-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/chef-app/brand-logo.png", "/chef-app/favicon.ico", "/chef-app/icon-192.png", "/chef-app/icon-512.png", "/chef-app/icon-maskable-192.png", "/chef-app/icon-maskable-512.png", "/chef-app/manifest.webmanifest", "/chef-app/index.html", "/chef-app/_expo/static/js/web/bundle.js?v=f22ed7ed0c6a3a6a5ca3f1b67cd4e98026bca0f671c470f1c4e3573d52e5bf95"]; +const PRECACHE = ["/chef-app/apple-touch-icon.png", "/chef-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/chef-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/chef-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/chef-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/chef-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/chef-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/chef-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/chef-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/chef-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/chef-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/chef-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/chef-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/chef-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/chef-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/chef-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/chef-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/chef-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/chef-app/brand-logo.png", "/chef-app/favicon.ico", "/chef-app/icon-192.png", "/chef-app/icon-512.png", "/chef-app/icon-maskable-192.png", "/chef-app/icon-maskable-512.png", "/chef-app/manifest.webmanifest", "/chef-app/index.html", "/chef-app/_expo/static/js/web/bundle.js?v=34f7529ceaae3b79d709447d3e02d92eed1441d1c5db9eff686653acce994da8"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/chef-app/team.html b/chef-app/team.html index f160a96f9de662453ace07ce65838c96f0dbfba2..67e86268a52b824b0d9269555581a5ec63abe8e6 100644 --- a/chef-app/team.html +++ b/chef-app/team.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/_expo/static/js/web/bundle.js b/customer-app/_expo/static/js/web/bundle.js index c023dee84120948ad400e6d95607046b5e8e19e9..b12c62ea8fce3eb96a0f22cf367cdb8273524c4e 100644 --- a/customer-app/_expo/static/js/web/bundle.js +++ b/customer-app/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?`
    ${n.map(t=>`
  • ${p(t)}
  • `).join('')}
`:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/customer-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CREATOR_TITLE",{enumerable:!0,get:function(){return n}}),e.DishCreator=function(n){return null},e.useCardCosting=function(...n){return null},e.CardGpPanel=function(n){return null};const n='New dish creator'},1157,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1483,7 +1483,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return f}});var t=r(d[0]);r(d[1]);var n=r(d[2]),u=r(d[3]),c=r(d[4]);function f(){return'owner'!==u.APP_VARIANT?(0,c.jsx)(t.Redirect,{href:u.ENTRY[u.APP_VARIANT]}):(0,c.jsx)(n.OwnerApp,{})}},1400,[13,17,1401,856,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.OwnerApp=function(){return null}},1401,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1402,[13,17,856,1403,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1403,[1404,1408,813,912,1072,1409,1203,1204,1028,1025,1026,1410,1412,1415,1153,891,978,1417,975,880,1031,1032,1418,914,1008,915,17,1155,1220,1224,1197,356,385,278,85,409,19,777,857,876,804,1161,1419,1066,1084,1086,1081,1027,1010,1057,1426,1427,1428,1437,1438,920,219,1225,1176,1183,1434,1196,1179,1443,1180,878,1206,1207,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1403,[1404,1408,813,912,1072,1409,1203,1204,1028,1025,1026,1410,1412,1415,1153,891,978,1417,975,880,1031,1032,1418,914,1008,915,17,1155,1220,1224,1197,356,385,278,85,409,19,777,857,876,804,1161,1419,1066,1084,1086,1081,1027,1010,1057,1426,1427,1428,1437,1438,920,219,1225,1176,1183,1434,1196,1179,1443,1180,878,1206,1207,884,776,899,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.TablePlan=function({startStep:e}){const{rid:s,r:n,now:w,me:f,role:S}=(0,b.useCtx)(6e4),T=(0,x.usePlan)(s),[P,C]=(0,t.useState)(null),[D,I]=(0,t.useState)(T.areas[0]?.id??''),[M,B]=(0,t.useState)(null),N=T.areas.find(e=>e.id===D)??T.areas[0],O=(0,x.planCounts)(T),A=(0,p.closedAreasAt)((0,p.useBlocks)(e=>e.blocks),s,(0,y.ymd)(w),`${String(w.getHours()).padStart(2,'0')}:${String(w.getMinutes()).padStart(2,'0')}`);return(0,k.jsxs)(a.default,{style:{gap:12},testID:"tableplan-page",children:[(0,k.jsxs)(h.Muted,{children:["The table plan for ",n.name,". Each venue has its own plan; it drives the Display floor view, walk-ins and which tables online bookings can use."]}),(0,k.jsxs)(h.Card,{children:[(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},wrap:!0,gap:8,children:[(0,k.jsxs)(a.default,{children:[(0,k.jsxs)(h.T,{size:20,weight:"bold",colour:j.colours.gold,children:[O.tables," tables \xb7 ",O.seats," seats"]}),(0,k.jsxs)(h.Muted,{children:[T.areas.length," areas \xb7 ",T.joins.length," joined ",1===T.joins.length?"pair":"pairs"]})]}),(0,k.jsx)(h.Button,{label:"Open table plan designer",testID:"open-designer",onPress:()=>C(e??'arrange')})]}),v.RELEASE.planPhoto?(0,k.jsx)(m.PlanPhoto,{rid:s}):null,(0,k.jsx)(a.default,{style:{gap:6},children:T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return(0,k.jsxs)(a.default,{testID:`area-summary-${e.id}`,style:{width:'100%',minWidth:0,gap:8,alignItems:'stretch',borderTopWidth:1,borderTopColor:j.colours.border,paddingTop:12,paddingBottom:6},children:[(0,k.jsx)(h.T,{center:!0,weight:"semibold",colour:(0,j.brandColour)(e.colour),children:e.name}),e.dogs||e.outdoor?(0,k.jsxs)(h.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[e.dogs?(0,k.jsx)(h.Badge,{kind:"gold",label:"\ud83d\udc3e Dogs allowed"}):null,e.outdoor?(0,k.jsx)(h.Badge,{kind:A.has(e.id)?'red':'neutral',label:A.has(e.id)?'\ud83c\udf27 Closed for weather':'\ud83c\udf26 Outdoor'}):null]}):null,e.label?(0,k.jsx)(h.Muted,{center:!0,size:14,children:e.label}):null,(0,k.jsxs)(h.Muted,{center:!0,children:[s.tables," tables \xb7 ",s.seats," seats"]})]},e.id)})}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Areas",onPress:()=>C('areas')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Tables",onPress:()=>C('tables')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Arrange",onPress:()=>C('arrange')})]})]}),T.areas.some(e=>e.outdoor)?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(h.T,{weight:"semibold",children:"Weather"}),(0,k.jsx)(h.Muted,{children:"Closes the outdoor areas for the rest of today: no online bookings or walk-ins there, and the Display shows them as closed. Uses Block bookings, so you can reopen in one tap."}),(0,k.jsx)(c.CloseGardenButton,{rid:s,r:n,now:w,by:f})]}):null,N?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(o.AreaTabs,{plan:T,area:N.id,onPick:I,closed:A,counts:Object.fromEntries(T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return[e.id,`${s.tables} \xb7 ${s.seats}`]}))}),(0,k.jsx)(a.default,{pointerEvents:"none",style:{borderRadius:12,overflow:'hidden'},children:(0,k.jsx)(r.FloorCanvas,{plan:T,areaId:N.id,mode:"live",fit:"width",maxH:360,sectionColours:!0})}),(0,k.jsx)(h.Muted,{children:"Preview only. Open the designer to change it."})]}):null,M?(0,k.jsx)(h.Banner,{kind:"success",title:M}):null,(0,k.jsx)(l.default,{visible:!!P,animationType:"slide",onRequestClose:()=>C(null),presentationStyle:"fullScreen",children:(0,k.jsx)(a.default,{style:{flex:1,backgroundColor:j.colours.bg},children:P?(0,k.jsx)(u.PlanDesigner,{initial:T,venue:n.name,mode:"managers",role:S,startStep:P,onSave:e=>{x.useFloor.getState().setPlan(s,e),C(null),B('Table plan saved. The Display uses it straight away.')},onLiveChange:e=>{x.useFloor.getState().setPlan(s,e),B('Live seating plan updated on every screen.')},onCancel:()=>C(null)}):null})})]})},_e.DisplaySettingsPage=function(){const{rid:e,role:s}=(0,b.useCtx)(6e4),t=(0,x.useDisplaySettings)(e),n=s=>x.useFloor.getState().setSettings(e,s);return(0,k.jsxs)(a.default,{style:{gap:14},children:[(0,k.jsxs)(a.default,{style:{gap:6},testID:"privacy-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Privacy on the Display"}),'owner'===s?(0,k.jsx)(h.Toggle,{label:"Privacy mode (recommended)",value:t.privacy,onChange:e=>n({privacy:e})}):(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},children:[(0,k.jsx)(h.T,{children:"Privacy mode"}),(0,k.jsxs)(h.T,{weight:"semibold",children:[t.privacy?'On':'Off'," \xb7 owner only"]})]}),(0,k.jsx)(h.Muted,{children:"On: guest surnames show as initials (Campbell \u2192 C.), and no phone numbers, emails, notes or allergy details appear on the main screen (an icon only). Staff tap for details in a panel that closes after 20 seconds."})]}),(0,k.jsxs)(a.default,{style:{gap:6},children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Screensaver"}),(0,k.jsx)(h.T,{size:14,children:"Start after nobody touches the Display for"}),(0,k.jsx)(h.Row,{gap:6,children:[1,2,5,10].map(e=>(0,k.jsx)(a.default,{testID:`idle-${e}`,children:(0,k.jsx)(h.Chip,{label:`${e} min`,selected:t.idleMins===e,onPress:()=>n({idleMins:e})})},e))}),(0,k.jsx)(h.Toggle,{label:"Ask for a staff PIN on wake",value:t.pinOn,onChange:e=>n({pinOn:e})}),t.pinOn?(0,k.jsx)(S,{rid:e}):null,(0,k.jsx)(h.Muted,{children:"Used on this Display until a screensaver is saved in Settings \u203a Display screensaver (style, idle time and night dim for every Display, changed live). Any touch wakes it straight away and that first touch doesn\u2019t press anything. Where the browser allows, the Display also asks to keep the screen on."})]}),(0,k.jsx)(T,{}),(0,k.jsxs)(a.default,{style:{gap:6},testID:"wipe-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Shared tablet or phone"}),(0,k.jsx)(h.Muted,{children:"Selling or handing over this device, or it was used by someone who has left? Sign out and wipe it."}),(0,k.jsx)(f.WipeDevice,{})]}),(0,k.jsx)(h.Banner,{kind:"info",title:"Settings live on this device",children:"They\u2019re saved in this browser for the venue and picked up by the Display app on the same device."})]})};var s=_r(d[0]),t=_r(d[1]),n=_r(d[2]),l=e(_r(d[3])),a=e(_r(d[4])),o=_r(d[5]),r=_r(d[6]),u=_r(d[7]),c=_r(d[8]),h=_r(d[9]),p=_r(d[10]),x=_r(d[11]),y=_r(d[12]),j=_r(d[13]),b=_r(d[14]),w=_r(d[15]),f=_r(d[16]),m=_r(d[17]),v=_r(d[18]),k=_r(d[19]);function S({rid:e}){const n=(0,x.useDisplaySettings)(e),[l,o]=(0,t.useState)(''),[r,u]=(0,t.useState)(''),[c,p]=(0,t.useState)(null),y=l?(0,w.wakePinProblem)(l):null,b=[h.styles.input,{width:130}];return(0,k.jsxs)(a.default,{style:{gap:6},testID:"wake-pin-setting",children:[n.pinDefault?(0,k.jsx)(a.default,{testID:"wake-pin-default",children:(0,k.jsx)(h.Banner,{kind:"warn",title:"Change the wake PIN",children:"This Display still uses the starting PIN, 2580, which anyone could guess. Set a new 6 to 8 digit PIN below."})}):(0,k.jsxs)(h.Muted,{children:["A wake PIN of ",n.pinLen," digits is set. Type a new one to change it."]}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(s.TextInput,{testID:"wake-pin-new",accessibilityLabel:"New wake PIN",value:l,onChangeText:e=>{o(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"New PIN (6\u20138 digits)",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(s.TextInput,{testID:"wake-pin-again",accessibilityLabel:"New wake PIN again",value:r,onChangeText:e=>{u(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"Type it again",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(h.Button,{small:!0,testID:"wake-pin-save",label:"Save PIN",disabled:!l||!r,onPress:()=>{const s=(0,w.wakePinProblem)(l);s?p(s):l===r?(x.useFloor.getState().setSettings(e,(0,w.makeWakePin)(l)),o(''),u(''),p('Wake PIN saved. Tell the team in person; it isn\u2019t shown again.')):p('The two PINs don\u2019t match.')}})]}),c||y?(0,k.jsx)(h.Muted,{children:c??y}):null]})}function T(){const[e,s]=(0,t.useState)((0,n.flapSoundOn)());return(0,k.jsxs)(a.default,{style:{gap:6},testID:"flap-sound-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Covers counter sound"}),(0,k.jsx)(h.Toggle,{label:"Soft flap click when the Covers change (Display only)",value:e,onChange:e=>{(0,n.setFlapSound)(e),s(e)}}),(0,k.jsx)(h.Muted,{children:"Off by default. Only this device clicks; phones never do."})]})}},1404,[812,17,1018,378,85,1108,1109,1350,1383,777,995,998,863,804,1057,999,1405,1406,1020,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.WipeDevice=function({compact:e}){const f=(0,u.useDisplaySettings)(p.VENUE_RID),[v,T]=(0,s.useState)(!1),[w,j]=(0,s.useState)(''),[D,C]=(0,s.useState)(!1),I='display'===h.APP_VARIANT&&f.pinOn,P=!I||(0,b.wakePinMatches)(f,w);return v?(0,x.jsxs)(o.default,{testID:"wipe-confirm-box",style:{gap:6,marginTop:6},children:[(0,x.jsx)(l.T,{size:e?12:14,children:"Sign out and remove everything CoverCharge keeps on this device: sign-ins, pairing, saved screens and any changes not sent yet. The venue\u2019s shared data is not touched. To use it again, open a personal link or pair the Display again."}),I?(0,x.jsx)(t.TextInput,{testID:"wipe-pin",value:w,onChangeText:j,placeholder:"Display wake PIN",placeholderTextColor:c.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",accessibilityLabel:"Display wake PIN",style:{borderWidth:1,borderColor:'rgba(255,255,255,0.2)',borderRadius:8,paddingHorizontal:10,paddingVertical:6,color:c.colours.text}}):null,(0,x.jsxs)(o.default,{style:{flexDirection:'row',gap:8},children:[(0,x.jsx)(n.default,{testID:"wipe-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, wipe this device",disabled:!P||D,onPress:()=>{C(!0),(0,y.wipeThisDevice)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:P?c.colours.red:'rgba(255,255,255,0.08)'},children:(0,x.jsx)(l.T,{size:12,weight:"semibold",children:D?'Wiping\u2026':'Yes, wipe this device'})}),(0,x.jsx)(n.default,{accessibilityRole:"button",accessibilityLabel:"Cancel",onPress:()=>{T(!1),j('')},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,x.jsx)(l.T,{size:12,children:"Cancel"})})]})]}):(0,x.jsx)(n.default,{testID:"wipe-device",accessibilityRole:"button",accessibilityLabel:"Sign out and wipe this device",onPress:()=>T(!0),style:{alignSelf:'flex-start',marginTop:e?4:0,minHeight:44,justifyContent:'center'},children:(0,x.jsx)(l.T,{size:e?12:14,colour:c.colours.gold,children:"Sign out and wipe this device\u2026"})})};var t=r(d[0]),s=r(d[1]),n=e(r(d[2])),o=e(r(d[3])),l=r(d[4]),c=r(d[5]),u=r(d[6]),p=r(d[7]),b=r(d[8]),h=r(d[9]),y=r(d[10]),x=r(d[11])},1405,[812,17,385,85,777,804,998,805,999,856,899,8]); __d(function(g,r,_i,_a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.PlanPhoto=function({rid:e}){const t=(0,n.usePlan)(e),b=(0,n.useFloor)(e=>e.setPlan),[y,f]=(0,a.useState)(null),[x,w]=(0,a.useState)(null),[v,j]=(0,a.useState)(null),[k,S]=(0,a.useState)(''),[P,T]=(0,a.useState)(!1),I=async e=>{let a;T(!0);try{const{data:t,error:l}=await(0,u.getSupabase)().functions.invoke('plan-photo-read',{body:{image:e}});a=l?{ok:!1,message:'The plan could not be read. The photo is still here.'}:{ok:!0,tables:(0,o.cleanFindings)(t)}}catch{a={ok:!1,message:'The plan could not be read. The photo is still here.'}}finally{T(!1)}const t=(0,o.planReadAfter)(e,a);w(t.photo),f(t.rows&&t.rows.length?t.rows:null),S(t.note)},L=async()=>{S('');const e=(await(0,c.pickPhotos)({source:'camera'}))[0];e?(w(e),await I(e)):S('No photo taken.')};return(0,p.jsxs)(l.default,{testID:"plan-photo",style:{width:'100%',alignItems:'center',gap:10},children:[(0,p.jsx)(s.Button,{testID:"plan-photo-camera",label:P?'Reading the plan\u2026':'Take a picture of the table plan',accessibilityLabel:"Take a picture of a hand-drawn table plan",disabled:P,onPress:()=>{L()}}),k?(0,p.jsx)(s.Muted,{center:!0,testID:"plan-photo-note",children:k}):null,x&&!P?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-retry",label:"Read this photo again",accessibilityLabel:"Read this photo again",onPress:()=>{I(x)}}):null,y?(0,p.jsx)(l.default,{testID:"plan-photo-review",style:{width:'100%'},children:(0,p.jsxs)(s.Card,{style:{alignItems:'center',width:'100%'},children:[(0,p.jsx)(s.T,{center:!0,weight:"bold",colour:h.colours.gold,children:"Check what was read"}),(0,p.jsx)(s.Muted,{center:!0,children:"Nothing is saved until you tap Save the plan."}),y.map((e,a)=>(0,p.jsxs)(l.default,{style:{width:'100%',gap:6},children:[(0,p.jsx)(s.Field,{label:"Area",accessibilityLabel:`Area ${a+1}`,value:e.area,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,area:e}:t))}),(0,p.jsx)(s.Field,{label:"Table",accessibilityLabel:`Table ${a+1}`,value:e.name,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,name:e}:t))}),(0,p.jsx)(s.Field,{label:"Seats",accessibilityLabel:`Seats at table ${a+1}`,value:String(e.seats),keyboardType:"number-pad",onChangeText:e=>f(y.map((t,l)=>l===a?{...t,seats:Math.max(1,Math.min(30,Number(e.replace(/\D/g,''))||1))}:t))}),(0,p.jsx)(s.Button,{kind:"ghost",label:`Remove ${e.name||'table'}`,accessibilityLabel:`Remove ${e.name||'table'}`,onPress:()=>f(y.filter((e,t)=>t!==a))})]},`${e.area}-${e.name}-${a}`)),(0,p.jsx)(s.Button,{testID:"plan-photo-save",label:"Save the plan",accessibilityLabel:"Save the checked table plan",disabled:!y.length,onPress:()=>{if(!y?.length)return;j(t);const a=[...t.areas],l=[...t.tables];for(const e of y){let t=a.find(a=>a.name.toLowerCase()===e.area.toLowerCase());t||(t={id:(0,i.fid)('area'),name:e.area},a.push(t));const s=(0,i.sizeFor)(e.seats),n=l.filter(e=>e.areaId===t.id).length;l.push({id:(0,i.fid)('t'),name:e.name,areaId:t.id,shape:s.shape,minSeats:1,maxSeats:e.seats,x:40+n%6*140,y:40+120*Math.floor(n/6),w:s.w,h:s.h,rot:0,online:!0})}b(e,{...t,areas:a,tables:l}),f(null),S('Plan saved. Undo puts the previous plan back.')}})]})}):null,v?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-undo",label:"Undo table plan",accessibilityLabel:"Undo the table plan and restore the previous one",onPress:()=>{b(e,v),j(null),S('Previous plan restored.')}}):null]})};var e,a=r(d[0]),t=r(d[1]),l=(e=t)&&e.__esModule?e:{default:e},s=r(d[2]),n=r(d[3]),o=r(d[4]),i=r(d[5]),h=r(d[6]),c=r(d[7]),u=r(d[8]),p=r(d[9])},1406,[17,85,777,998,1407,842,804,1038,928,8]); @@ -1560,7 +1560,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1477,[17,24,85,409,777,857,920,899,880,805,804,1478,1479,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CAR_BUTTONS",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"MENU_BUTTON",{enumerable:!0,get:function(){return l}}),e.menuSizes=function(o,l){const s=Math.round(Math.max(300,Math.min(o-24,o>=1600?520:o>=1200?460:420))),t=Math.floor((s-40-2)/3),n=Math.floor(Math.max(84,(l-72-40)/4)),c=l>=1e3?15:13,b=Math.round(1.4*c),h=Math.max(52,Math.min(76,n-b-18,t-28));return{panelW:s,colW:t,per:n,circle:h,label:c,lineH:b,icon:Math.round(.44*h),cols:3,rows:4,head:72,pad:20}},Object.defineProperty(e,"spokenCode",{enumerable:!0,get:function(){return s}});const o=[{id:'rota',label:'Rota',short:'Rota',icon:'rota',pages:[{id:'rota',label:'Rota'}]},{id:'signoff',label:'Sign off hours',short:'Sign off',icon:'signoff',pages:[{id:'signoff',label:'Sign off hours'},{id:'timesheets',label:'Timesheets'}]},{id:'menu',label:'Menu & sold out',short:'Menu',icon:'menu',pages:[{id:'soldout',label:'Sold out'},{id:'menu',label:'Menu & allergens'},{id:'tableqr',label:'Table QR codes'}]},{id:'bookings',label:'Bookings',short:'Bookings',icon:'bookings',pages:[{id:'@bookings',label:'Bookings'},{id:'lookback',label:'Look back'}]},{id:'noshows',label:'No-shows',short:'No-shows',icon:'noshow',pages:[{id:'@noshows',label:'No-shows'}]},{id:'chat',label:'Staff chat',short:'Chat',icon:'chat',pages:[{id:'@chat',label:'Staff chat'}]},{id:'stock',label:'Stock & suppliers',short:'Stock',icon:'stock',pages:[{id:'kitchencosts',label:'Deliveries & GP'},{id:'trackedstock',label:'Tracked stock'},{id:'orderlists',label:'Order lists'},{id:'suppliers',label:'Suppliers'}]},{id:'loyalty',label:'Loyalty',short:'Loyalty',icon:'loyalty',pages:[{id:'loyalty',label:'Stamp card'}]},{id:'takings',label:'Takings & tips',short:'Takings',icon:'takings',pages:[{id:'cashup',label:'Cash up & sales'},{id:'tips',label:'Tips'},{id:'spendhead',label:'Spend per head'}]},{id:'safety',label:'Food safety',short:'Safety',icon:'safety',pages:[{id:'haccp',label:'CookSafe log'}]},{id:'reviews',label:'Reviews',short:'Reviews',icon:'reviews',pages:[{id:'reviews',label:'Reviews'}]}],l=56;const s=o=>o.split('').join(' ')},1478,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ParkedOnly=function({small:e}){return(0,s.jsx)(n.default,{testID:"parked-only",accessible:!0,accessibilityLabel:"Parked only. Use this screen only when the car is in Park.",style:{minHeight:e?28:36,paddingHorizontal:e?8:12,borderRadius:999,borderWidth:1,borderColor:t.colours.amber,backgroundColor:'rgba(232,168,56,0.12)',alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,s.jsx)(o.T,{size:e?11:13,weight:"semibold",colour:t.colours.amber,center:!0,children:"PARKED ONLY"})})},r(d[0]);var e,l=r(d[1]),n=(e=l)&&e.__esModule?e:{default:e},o=r(d[2]),t=r(d[3]),s=r(d[4])},1479,[17,85,777,804,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1480,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1480,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1481,[813,779,17,974,385,85,856,899,976,804,777,1335,971,880,1482,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.SyncDeviceActions=function(){const e=(0,o.useSync)(),[f,p]=(0,s.useState)(!1),h='live'===e.mode||'offline'===e.mode;return e.venueId&&h?(0,b.jsxs)(b.Fragment,{children:[f?(0,b.jsxs)(c.default,{style:{gap:6,marginTop:6},children:[(0,b.jsx)(u.T,{size:12,children:"Disconnect this device? Your changes stay on it; open your personal invite link to connect again."}),(0,b.jsxs)(c.default,{style:{flexDirection:'row',gap:8},children:[(0,b.jsx)(t.default,{testID:"unpair-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, disconnect",onPress:()=>{p(!1),(0,o.disconnectStaff)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:l.colours.red},children:(0,b.jsx)(u.T,{size:12,weight:"semibold",children:"Yes, disconnect"})}),(0,b.jsx)(t.default,{accessibilityRole:"button",accessibilityLabel:"Keep connected",onPress:()=>p(!1),style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,b.jsx)(u.T,{size:12,children:"Keep"})})]})]}):(0,b.jsx)(t.default,{testID:"unpair",accessibilityRole:"button",accessibilityLabel:"Disconnect this device",onPress:()=>p(!0),style:{marginTop:6,alignSelf:'flex-start'},children:(0,b.jsx)(u.T,{size:12,colour:l.colours.gold,children:"Disconnect this device\u2026"})}),(0,b.jsx)(n.WipeDevice,{compact:!0})]}):null};var s=r(d[0]),n=r(d[1]),t=e(r(d[2])),c=e(r(d[3])),o=r(d[4]),l=r(d[5]),u=r(d[6]),b=r(d[7])},1482,[17,1405,385,85,899,804,777,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1483,[]); diff --git a/customer-app/admin.html b/customer-app/admin.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/admin.html +++ b/customer-app/admin.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer.html b/customer-app/customer.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer.html +++ b/customer-app/customer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage.html b/customer-app/customer/anchorage.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage.html +++ b/customer-app/customer/anchorage.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/book.html b/customer-app/customer/anchorage/book.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/book.html +++ b/customer-app/customer/anchorage/book.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/feedback.html b/customer-app/customer/anchorage/feedback.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/feedback.html +++ b/customer-app/customer/anchorage/feedback.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/gift.html b/customer-app/customer/anchorage/gift.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/gift.html +++ b/customer-app/customer/anchorage/gift.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/lost.html b/customer-app/customer/anchorage/lost.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/lost.html +++ b/customer-app/customer/anchorage/lost.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/loyalty.html b/customer-app/customer/anchorage/loyalty.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/loyalty.html +++ b/customer-app/customer/anchorage/loyalty.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/merch.html b/customer-app/customer/anchorage/merch.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/merch.html +++ b/customer-app/customer/anchorage/merch.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/offers.html b/customer-app/customer/anchorage/offers.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/offers.html +++ b/customer-app/customer/anchorage/offers.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/refer.html b/customer-app/customer/anchorage/refer.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/refer.html +++ b/customer-app/customer/anchorage/refer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/waitlist.html b/customer-app/customer/anchorage/waitlist.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/waitlist.html +++ b/customer-app/customer/anchorage/waitlist.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/anchorage/whatson.html b/customer-app/customer/anchorage/whatson.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/anchorage/whatson.html +++ b/customer-app/customer/anchorage/whatson.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/basket.html b/customer-app/customer/basket.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/basket.html +++ b/customer-app/customer/basket.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/customer/profile.html b/customer-app/customer/profile.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/customer/profile.html +++ b/customer-app/customer/profile.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/demo.html b/customer-app/demo.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/demo.html +++ b/customer-app/demo.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/display.html b/customer-app/display.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/display.html +++ b/customer-app/display.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/index.html b/customer-app/index.html index fb291c9facc7e9d0b7a1a4141f27c0463d27ac89..54c53dbc860e96e0b6c9dd3364fe518c48d43aec 100644 --- a/customer-app/index.html +++ b/customer-app/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/kitchen.html b/customer-app/kitchen.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/kitchen.html +++ b/customer-app/kitchen.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/owner.html b/customer-app/owner.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/owner.html +++ b/customer-app/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/staff.html b/customer-app/staff.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/staff.html +++ b/customer-app/staff.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/customer-app/sw.js b/customer-app/sw.js index 2b4c576a9c54d6530d4c3270ee2d5d33ab3c3685..45f4ef133d57bf8b33a0f83ff74a93ee67bcdc9e 100644 --- a/customer-app/sw.js +++ b/customer-app/sw.js @@ -1,7 +1,7 @@ // Anchorage service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-customer-4a0990f93b"; +const V = "cc-customer-b7a24b428e"; const BASE = "/customer-app/"; -const PRECACHE = ["/customer-app/apple-touch-icon.png", "/customer-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/customer-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/customer-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/customer-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/customer-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/customer-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/customer-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/customer-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/customer-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/customer-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/customer-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/customer-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/customer-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/customer-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/customer-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/customer-app/brand-logo.png", "/customer-app/favicon.ico", "/customer-app/icon-192.png", "/customer-app/icon-512.png", "/customer-app/icon-maskable-192.png", "/customer-app/icon-maskable-512.png", "/customer-app/manifest.webmanifest", "/customer-app/index.html", "/customer-app/_expo/static/js/web/bundle.js?v=4a0990f93b17a2fd5d49ee3f7836ea7d54aa78499bb0962650f5bf2b4ff1cdb4"]; +const PRECACHE = ["/customer-app/apple-touch-icon.png", "/customer-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/customer-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/customer-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/customer-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/customer-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/customer-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/customer-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/customer-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/customer-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/customer-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/customer-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/customer-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/customer-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/customer-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/customer-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/customer-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/customer-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/customer-app/brand-logo.png", "/customer-app/favicon.ico", "/customer-app/icon-192.png", "/customer-app/icon-512.png", "/customer-app/icon-maskable-192.png", "/customer-app/icon-maskable-512.png", "/customer-app/manifest.webmanifest", "/customer-app/index.html", "/customer-app/_expo/static/js/web/bundle.js?v=b7a24b428e0f6ef2bec41c4168ffa97867df630766372332d319403a6b5b5812"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/customer-app/team.html b/customer-app/team.html index 7de47877f1d0fbc5aa25c02b23211b6201f3c804..a8514a2cc64dbf19797f65e748bd85a88ce8479a 100644 --- a/customer-app/team.html +++ b/customer-app/team.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/_expo/static/js/web/bundle.js b/display-app/_expo/static/js/web/bundle.js index 3b96ce50d555dc48842154bfa7badaecaaf9dece..96741d866148161f42b09b474845ac28dba03699 100644 --- a/display-app/_expo/static/js/web/bundle.js +++ b/display-app/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?`
    ${n.map(t=>`
  • ${p(t)}
  • `).join('')}
`:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/display-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CREATOR_TITLE",{enumerable:!0,get:function(){return n}}),e.DishCreator=function(n){return null},e.useCardCosting=function(...n){return null},e.CardGpPanel=function(n){return null};const n='New dish creator'},1157,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1483,7 +1483,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return f}});var t=r(d[0]);r(d[1]);var n=r(d[2]),u=r(d[3]),c=r(d[4]);function f(){return'owner'!==u.APP_VARIANT?(0,c.jsx)(t.Redirect,{href:u.ENTRY[u.APP_VARIANT]}):(0,c.jsx)(n.OwnerApp,{})}},1400,[13,17,1401,856,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.OwnerApp=function(){return null}},1401,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1402,[13,17,856,1403,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1403,[1404,1408,813,912,1072,1409,1203,1204,1028,1025,1026,1410,1412,1415,1153,891,978,1417,975,880,1031,1032,1418,914,1008,915,17,1155,1220,1224,1197,356,385,278,85,409,19,777,857,876,804,1161,1419,1066,1084,1086,1081,1027,1010,1057,1426,1427,1428,1437,1438,920,219,1225,1176,1183,1434,1196,1179,1443,1180,878,1206,1207,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1403,[1404,1408,813,912,1072,1409,1203,1204,1028,1025,1026,1410,1412,1415,1153,891,978,1417,975,880,1031,1032,1418,914,1008,915,17,1155,1220,1224,1197,356,385,278,85,409,19,777,857,876,804,1161,1419,1066,1084,1086,1081,1027,1010,1057,1426,1427,1428,1437,1438,920,219,1225,1176,1183,1434,1196,1179,1443,1180,878,1206,1207,884,776,899,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.TablePlan=function({startStep:e}){const{rid:s,r:n,now:w,me:f,role:S}=(0,b.useCtx)(6e4),T=(0,x.usePlan)(s),[P,C]=(0,t.useState)(null),[D,I]=(0,t.useState)(T.areas[0]?.id??''),[M,B]=(0,t.useState)(null),N=T.areas.find(e=>e.id===D)??T.areas[0],O=(0,x.planCounts)(T),A=(0,p.closedAreasAt)((0,p.useBlocks)(e=>e.blocks),s,(0,y.ymd)(w),`${String(w.getHours()).padStart(2,'0')}:${String(w.getMinutes()).padStart(2,'0')}`);return(0,k.jsxs)(a.default,{style:{gap:12},testID:"tableplan-page",children:[(0,k.jsxs)(h.Muted,{children:["The table plan for ",n.name,". Each venue has its own plan; it drives the Display floor view, walk-ins and which tables online bookings can use."]}),(0,k.jsxs)(h.Card,{children:[(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},wrap:!0,gap:8,children:[(0,k.jsxs)(a.default,{children:[(0,k.jsxs)(h.T,{size:20,weight:"bold",colour:j.colours.gold,children:[O.tables," tables \xb7 ",O.seats," seats"]}),(0,k.jsxs)(h.Muted,{children:[T.areas.length," areas \xb7 ",T.joins.length," joined ",1===T.joins.length?"pair":"pairs"]})]}),(0,k.jsx)(h.Button,{label:"Open table plan designer",testID:"open-designer",onPress:()=>C(e??'arrange')})]}),v.RELEASE.planPhoto?(0,k.jsx)(m.PlanPhoto,{rid:s}):null,(0,k.jsx)(a.default,{style:{gap:6},children:T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return(0,k.jsxs)(a.default,{testID:`area-summary-${e.id}`,style:{width:'100%',minWidth:0,gap:8,alignItems:'stretch',borderTopWidth:1,borderTopColor:j.colours.border,paddingTop:12,paddingBottom:6},children:[(0,k.jsx)(h.T,{center:!0,weight:"semibold",colour:(0,j.brandColour)(e.colour),children:e.name}),e.dogs||e.outdoor?(0,k.jsxs)(h.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[e.dogs?(0,k.jsx)(h.Badge,{kind:"gold",label:"\ud83d\udc3e Dogs allowed"}):null,e.outdoor?(0,k.jsx)(h.Badge,{kind:A.has(e.id)?'red':'neutral',label:A.has(e.id)?'\ud83c\udf27 Closed for weather':'\ud83c\udf26 Outdoor'}):null]}):null,e.label?(0,k.jsx)(h.Muted,{center:!0,size:14,children:e.label}):null,(0,k.jsxs)(h.Muted,{center:!0,children:[s.tables," tables \xb7 ",s.seats," seats"]})]},e.id)})}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Areas",onPress:()=>C('areas')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Tables",onPress:()=>C('tables')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Arrange",onPress:()=>C('arrange')})]})]}),T.areas.some(e=>e.outdoor)?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(h.T,{weight:"semibold",children:"Weather"}),(0,k.jsx)(h.Muted,{children:"Closes the outdoor areas for the rest of today: no online bookings or walk-ins there, and the Display shows them as closed. Uses Block bookings, so you can reopen in one tap."}),(0,k.jsx)(c.CloseGardenButton,{rid:s,r:n,now:w,by:f})]}):null,N?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(o.AreaTabs,{plan:T,area:N.id,onPick:I,closed:A,counts:Object.fromEntries(T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return[e.id,`${s.tables} \xb7 ${s.seats}`]}))}),(0,k.jsx)(a.default,{pointerEvents:"none",style:{borderRadius:12,overflow:'hidden'},children:(0,k.jsx)(r.FloorCanvas,{plan:T,areaId:N.id,mode:"live",fit:"width",maxH:360,sectionColours:!0})}),(0,k.jsx)(h.Muted,{children:"Preview only. Open the designer to change it."})]}):null,M?(0,k.jsx)(h.Banner,{kind:"success",title:M}):null,(0,k.jsx)(l.default,{visible:!!P,animationType:"slide",onRequestClose:()=>C(null),presentationStyle:"fullScreen",children:(0,k.jsx)(a.default,{style:{flex:1,backgroundColor:j.colours.bg},children:P?(0,k.jsx)(u.PlanDesigner,{initial:T,venue:n.name,mode:"managers",role:S,startStep:P,onSave:e=>{x.useFloor.getState().setPlan(s,e),C(null),B('Table plan saved. The Display uses it straight away.')},onLiveChange:e=>{x.useFloor.getState().setPlan(s,e),B('Live seating plan updated on every screen.')},onCancel:()=>C(null)}):null})})]})},_e.DisplaySettingsPage=function(){const{rid:e,role:s}=(0,b.useCtx)(6e4),t=(0,x.useDisplaySettings)(e),n=s=>x.useFloor.getState().setSettings(e,s);return(0,k.jsxs)(a.default,{style:{gap:14},children:[(0,k.jsxs)(a.default,{style:{gap:6},testID:"privacy-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Privacy on the Display"}),'owner'===s?(0,k.jsx)(h.Toggle,{label:"Privacy mode (recommended)",value:t.privacy,onChange:e=>n({privacy:e})}):(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},children:[(0,k.jsx)(h.T,{children:"Privacy mode"}),(0,k.jsxs)(h.T,{weight:"semibold",children:[t.privacy?'On':'Off'," \xb7 owner only"]})]}),(0,k.jsx)(h.Muted,{children:"On: guest surnames show as initials (Campbell \u2192 C.), and no phone numbers, emails, notes or allergy details appear on the main screen (an icon only). Staff tap for details in a panel that closes after 20 seconds."})]}),(0,k.jsxs)(a.default,{style:{gap:6},children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Screensaver"}),(0,k.jsx)(h.T,{size:14,children:"Start after nobody touches the Display for"}),(0,k.jsx)(h.Row,{gap:6,children:[1,2,5,10].map(e=>(0,k.jsx)(a.default,{testID:`idle-${e}`,children:(0,k.jsx)(h.Chip,{label:`${e} min`,selected:t.idleMins===e,onPress:()=>n({idleMins:e})})},e))}),(0,k.jsx)(h.Toggle,{label:"Ask for a staff PIN on wake",value:t.pinOn,onChange:e=>n({pinOn:e})}),t.pinOn?(0,k.jsx)(S,{rid:e}):null,(0,k.jsx)(h.Muted,{children:"Used on this Display until a screensaver is saved in Settings \u203a Display screensaver (style, idle time and night dim for every Display, changed live). Any touch wakes it straight away and that first touch doesn\u2019t press anything. Where the browser allows, the Display also asks to keep the screen on."})]}),(0,k.jsx)(T,{}),(0,k.jsxs)(a.default,{style:{gap:6},testID:"wipe-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Shared tablet or phone"}),(0,k.jsx)(h.Muted,{children:"Selling or handing over this device, or it was used by someone who has left? Sign out and wipe it."}),(0,k.jsx)(f.WipeDevice,{})]}),(0,k.jsx)(h.Banner,{kind:"info",title:"Settings live on this device",children:"They\u2019re saved in this browser for the venue and picked up by the Display app on the same device."})]})};var s=_r(d[0]),t=_r(d[1]),n=_r(d[2]),l=e(_r(d[3])),a=e(_r(d[4])),o=_r(d[5]),r=_r(d[6]),u=_r(d[7]),c=_r(d[8]),h=_r(d[9]),p=_r(d[10]),x=_r(d[11]),y=_r(d[12]),j=_r(d[13]),b=_r(d[14]),w=_r(d[15]),f=_r(d[16]),m=_r(d[17]),v=_r(d[18]),k=_r(d[19]);function S({rid:e}){const n=(0,x.useDisplaySettings)(e),[l,o]=(0,t.useState)(''),[r,u]=(0,t.useState)(''),[c,p]=(0,t.useState)(null),y=l?(0,w.wakePinProblem)(l):null,b=[h.styles.input,{width:130}];return(0,k.jsxs)(a.default,{style:{gap:6},testID:"wake-pin-setting",children:[n.pinDefault?(0,k.jsx)(a.default,{testID:"wake-pin-default",children:(0,k.jsx)(h.Banner,{kind:"warn",title:"Change the wake PIN",children:"This Display still uses the starting PIN, 2580, which anyone could guess. Set a new 6 to 8 digit PIN below."})}):(0,k.jsxs)(h.Muted,{children:["A wake PIN of ",n.pinLen," digits is set. Type a new one to change it."]}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(s.TextInput,{testID:"wake-pin-new",accessibilityLabel:"New wake PIN",value:l,onChangeText:e=>{o(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"New PIN (6\u20138 digits)",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(s.TextInput,{testID:"wake-pin-again",accessibilityLabel:"New wake PIN again",value:r,onChangeText:e=>{u(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"Type it again",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(h.Button,{small:!0,testID:"wake-pin-save",label:"Save PIN",disabled:!l||!r,onPress:()=>{const s=(0,w.wakePinProblem)(l);s?p(s):l===r?(x.useFloor.getState().setSettings(e,(0,w.makeWakePin)(l)),o(''),u(''),p('Wake PIN saved. Tell the team in person; it isn\u2019t shown again.')):p('The two PINs don\u2019t match.')}})]}),c||y?(0,k.jsx)(h.Muted,{children:c??y}):null]})}function T(){const[e,s]=(0,t.useState)((0,n.flapSoundOn)());return(0,k.jsxs)(a.default,{style:{gap:6},testID:"flap-sound-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Covers counter sound"}),(0,k.jsx)(h.Toggle,{label:"Soft flap click when the Covers change (Display only)",value:e,onChange:e=>{(0,n.setFlapSound)(e),s(e)}}),(0,k.jsx)(h.Muted,{children:"Off by default. Only this device clicks; phones never do."})]})}},1404,[812,17,1018,378,85,1108,1109,1350,1383,777,995,998,863,804,1057,999,1405,1406,1020,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.WipeDevice=function(n){return null}},1405,[]); __d(function(g,r,_i,_a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.PlanPhoto=function({rid:e}){const t=(0,n.usePlan)(e),b=(0,n.useFloor)(e=>e.setPlan),[y,f]=(0,a.useState)(null),[x,w]=(0,a.useState)(null),[v,j]=(0,a.useState)(null),[k,S]=(0,a.useState)(''),[P,T]=(0,a.useState)(!1),I=async e=>{let a;T(!0);try{const{data:t,error:l}=await(0,u.getSupabase)().functions.invoke('plan-photo-read',{body:{image:e}});a=l?{ok:!1,message:'The plan could not be read. The photo is still here.'}:{ok:!0,tables:(0,o.cleanFindings)(t)}}catch{a={ok:!1,message:'The plan could not be read. The photo is still here.'}}finally{T(!1)}const t=(0,o.planReadAfter)(e,a);w(t.photo),f(t.rows&&t.rows.length?t.rows:null),S(t.note)},L=async()=>{S('');const e=(await(0,c.pickPhotos)({source:'camera'}))[0];e?(w(e),await I(e)):S('No photo taken.')};return(0,p.jsxs)(l.default,{testID:"plan-photo",style:{width:'100%',alignItems:'center',gap:10},children:[(0,p.jsx)(s.Button,{testID:"plan-photo-camera",label:P?'Reading the plan\u2026':'Take a picture of the table plan',accessibilityLabel:"Take a picture of a hand-drawn table plan",disabled:P,onPress:()=>{L()}}),k?(0,p.jsx)(s.Muted,{center:!0,testID:"plan-photo-note",children:k}):null,x&&!P?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-retry",label:"Read this photo again",accessibilityLabel:"Read this photo again",onPress:()=>{I(x)}}):null,y?(0,p.jsx)(l.default,{testID:"plan-photo-review",style:{width:'100%'},children:(0,p.jsxs)(s.Card,{style:{alignItems:'center',width:'100%'},children:[(0,p.jsx)(s.T,{center:!0,weight:"bold",colour:h.colours.gold,children:"Check what was read"}),(0,p.jsx)(s.Muted,{center:!0,children:"Nothing is saved until you tap Save the plan."}),y.map((e,a)=>(0,p.jsxs)(l.default,{style:{width:'100%',gap:6},children:[(0,p.jsx)(s.Field,{label:"Area",accessibilityLabel:`Area ${a+1}`,value:e.area,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,area:e}:t))}),(0,p.jsx)(s.Field,{label:"Table",accessibilityLabel:`Table ${a+1}`,value:e.name,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,name:e}:t))}),(0,p.jsx)(s.Field,{label:"Seats",accessibilityLabel:`Seats at table ${a+1}`,value:String(e.seats),keyboardType:"number-pad",onChangeText:e=>f(y.map((t,l)=>l===a?{...t,seats:Math.max(1,Math.min(30,Number(e.replace(/\D/g,''))||1))}:t))}),(0,p.jsx)(s.Button,{kind:"ghost",label:`Remove ${e.name||'table'}`,accessibilityLabel:`Remove ${e.name||'table'}`,onPress:()=>f(y.filter((e,t)=>t!==a))})]},`${e.area}-${e.name}-${a}`)),(0,p.jsx)(s.Button,{testID:"plan-photo-save",label:"Save the plan",accessibilityLabel:"Save the checked table plan",disabled:!y.length,onPress:()=>{if(!y?.length)return;j(t);const a=[...t.areas],l=[...t.tables];for(const e of y){let t=a.find(a=>a.name.toLowerCase()===e.area.toLowerCase());t||(t={id:(0,i.fid)('area'),name:e.area},a.push(t));const s=(0,i.sizeFor)(e.seats),n=l.filter(e=>e.areaId===t.id).length;l.push({id:(0,i.fid)('t'),name:e.name,areaId:t.id,shape:s.shape,minSeats:1,maxSeats:e.seats,x:40+n%6*140,y:40+120*Math.floor(n/6),w:s.w,h:s.h,rot:0,online:!0})}b(e,{...t,areas:a,tables:l}),f(null),S('Plan saved. Undo puts the previous plan back.')}})]})}):null,v?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-undo",label:"Undo table plan",accessibilityLabel:"Undo the table plan and restore the previous one",onPress:()=>{b(e,v),j(null),S('Previous plan restored.')}}):null]})};var e,a=r(d[0]),t=r(d[1]),l=(e=t)&&e.__esModule?e:{default:e},s=r(d[2]),n=r(d[3]),o=r(d[4]),i=r(d[5]),h=r(d[6]),c=r(d[7]),u=r(d[8]),p=r(d[9])},1406,[17,85,777,998,1407,842,804,1038,928,8]); @@ -1560,7 +1560,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1477,[17,24,85,409,777,857,920,899,880,805,804,1478,1479,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CAR_BUTTONS",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"MENU_BUTTON",{enumerable:!0,get:function(){return l}}),e.menuSizes=function(o,l){const s=Math.round(Math.max(300,Math.min(o-24,o>=1600?520:o>=1200?460:420))),t=Math.floor((s-40-2)/3),n=Math.floor(Math.max(84,(l-72-40)/4)),c=l>=1e3?15:13,b=Math.round(1.4*c),h=Math.max(52,Math.min(76,n-b-18,t-28));return{panelW:s,colW:t,per:n,circle:h,label:c,lineH:b,icon:Math.round(.44*h),cols:3,rows:4,head:72,pad:20}},Object.defineProperty(e,"spokenCode",{enumerable:!0,get:function(){return s}});const o=[{id:'rota',label:'Rota',short:'Rota',icon:'rota',pages:[{id:'rota',label:'Rota'}]},{id:'signoff',label:'Sign off hours',short:'Sign off',icon:'signoff',pages:[{id:'signoff',label:'Sign off hours'},{id:'timesheets',label:'Timesheets'}]},{id:'menu',label:'Menu & sold out',short:'Menu',icon:'menu',pages:[{id:'soldout',label:'Sold out'},{id:'menu',label:'Menu & allergens'},{id:'tableqr',label:'Table QR codes'}]},{id:'bookings',label:'Bookings',short:'Bookings',icon:'bookings',pages:[{id:'@bookings',label:'Bookings'},{id:'lookback',label:'Look back'}]},{id:'noshows',label:'No-shows',short:'No-shows',icon:'noshow',pages:[{id:'@noshows',label:'No-shows'}]},{id:'chat',label:'Staff chat',short:'Chat',icon:'chat',pages:[{id:'@chat',label:'Staff chat'}]},{id:'stock',label:'Stock & suppliers',short:'Stock',icon:'stock',pages:[{id:'kitchencosts',label:'Deliveries & GP'},{id:'trackedstock',label:'Tracked stock'},{id:'orderlists',label:'Order lists'},{id:'suppliers',label:'Suppliers'}]},{id:'loyalty',label:'Loyalty',short:'Loyalty',icon:'loyalty',pages:[{id:'loyalty',label:'Stamp card'}]},{id:'takings',label:'Takings & tips',short:'Takings',icon:'takings',pages:[{id:'cashup',label:'Cash up & sales'},{id:'tips',label:'Tips'},{id:'spendhead',label:'Spend per head'}]},{id:'safety',label:'Food safety',short:'Safety',icon:'safety',pages:[{id:'haccp',label:'CookSafe log'}]},{id:'reviews',label:'Reviews',short:'Reviews',icon:'reviews',pages:[{id:'reviews',label:'Reviews'}]}],l=56;const s=o=>o.split('').join(' ')},1478,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ParkedOnly=function({small:e}){return(0,s.jsx)(n.default,{testID:"parked-only",accessible:!0,accessibilityLabel:"Parked only. Use this screen only when the car is in Park.",style:{minHeight:e?28:36,paddingHorizontal:e?8:12,borderRadius:999,borderWidth:1,borderColor:t.colours.amber,backgroundColor:'rgba(232,168,56,0.12)',alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,s.jsx)(o.T,{size:e?11:13,weight:"semibold",colour:t.colours.amber,center:!0,children:"PARKED ONLY"})})},r(d[0]);var e,l=r(d[1]),n=(e=l)&&e.__esModule?e:{default:e},o=r(d[2]),t=r(d[3]),s=r(d[4])},1479,[17,85,777,804,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1480,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1480,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1481,[813,779,17,974,385,85,856,899,976,804,777,1335,971,880,1482,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.SyncDeviceActions=function(){return null}},1482,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1483,[]); diff --git a/display-app/admin.html b/display-app/admin.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/admin.html +++ b/display-app/admin.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer.html b/display-app/customer.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer.html +++ b/display-app/customer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage.html b/display-app/customer/anchorage.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage.html +++ b/display-app/customer/anchorage.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/book.html b/display-app/customer/anchorage/book.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/book.html +++ b/display-app/customer/anchorage/book.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/feedback.html b/display-app/customer/anchorage/feedback.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/feedback.html +++ b/display-app/customer/anchorage/feedback.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/gift.html b/display-app/customer/anchorage/gift.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/gift.html +++ b/display-app/customer/anchorage/gift.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/lost.html b/display-app/customer/anchorage/lost.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/lost.html +++ b/display-app/customer/anchorage/lost.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/loyalty.html b/display-app/customer/anchorage/loyalty.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/loyalty.html +++ b/display-app/customer/anchorage/loyalty.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/merch.html b/display-app/customer/anchorage/merch.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/merch.html +++ b/display-app/customer/anchorage/merch.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/offers.html b/display-app/customer/anchorage/offers.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/offers.html +++ b/display-app/customer/anchorage/offers.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/refer.html b/display-app/customer/anchorage/refer.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/refer.html +++ b/display-app/customer/anchorage/refer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/waitlist.html b/display-app/customer/anchorage/waitlist.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/waitlist.html +++ b/display-app/customer/anchorage/waitlist.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/anchorage/whatson.html b/display-app/customer/anchorage/whatson.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/anchorage/whatson.html +++ b/display-app/customer/anchorage/whatson.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/basket.html b/display-app/customer/basket.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/basket.html +++ b/display-app/customer/basket.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/customer/profile.html b/display-app/customer/profile.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/customer/profile.html +++ b/display-app/customer/profile.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/demo.html b/display-app/demo.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/demo.html +++ b/display-app/demo.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/display.html b/display-app/display.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/display.html +++ b/display-app/display.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/index.html b/display-app/index.html index 5abc7b42141e963029c786324148e799bb24aaca..135b5ad410c9e5e2259dc3f970c27fe543b7ae41 100644 --- a/display-app/index.html +++ b/display-app/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/kitchen.html b/display-app/kitchen.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/kitchen.html +++ b/display-app/kitchen.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/owner.html b/display-app/owner.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/owner.html +++ b/display-app/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/staff.html b/display-app/staff.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/staff.html +++ b/display-app/staff.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/display-app/sw.js b/display-app/sw.js index 341240a4514b82a0ef8b1fc303c74026d304b8f9..e2f5bc282137b80e2a32ded9ffadd513f04d6d24 100644 --- a/display-app/sw.js +++ b/display-app/sw.js @@ -1,7 +1,7 @@ // Anchorage Display service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-display-83e60c92fd"; +const V = "cc-display-ccc9114602"; const BASE = "/display-app/"; -const PRECACHE = ["/display-app/apple-touch-icon.png", "/display-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/display-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/display-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/display-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/display-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/display-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/display-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/display-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/display-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/display-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/display-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/display-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/display-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/display-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/display-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/display-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/display-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/display-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/display-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/display-app/brand-logo.png", "/display-app/favicon.ico", "/display-app/icon-192.png", "/display-app/icon-512.png", "/display-app/icon-maskable-192.png", "/display-app/icon-maskable-512.png", "/display-app/manifest.webmanifest", "/display-app/index.html", "/display-app/_expo/static/js/web/bundle.js?v=83e60c92fdc1bf6f20f3be4c315afe70e1c0e41e4b1291eb2c864e9bd4fcf61f"]; +const PRECACHE = ["/display-app/apple-touch-icon.png", "/display-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/display-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/display-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/display-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/display-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/display-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/display-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/display-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/display-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/display-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/display-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/display-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/display-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/display-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/display-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/display-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/display-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/display-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/display-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/display-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/display-app/brand-logo.png", "/display-app/favicon.ico", "/display-app/icon-192.png", "/display-app/icon-512.png", "/display-app/icon-maskable-192.png", "/display-app/icon-maskable-512.png", "/display-app/manifest.webmanifest", "/display-app/index.html", "/display-app/_expo/static/js/web/bundle.js?v=ccc9114602909081967265e4c49eaff7bd2d4ddc7057f8d632b14b1aa77a6393"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/display-app/team.html b/display-app/team.html index 94411e21d62518872f6c6d053875b17194c7937e..55d7b2b5e40d1b326e22ef60f4313f8ad4ead78d 100644 --- a/display-app/team.html +++ b/display-app/team.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/index.html b/index.html index 24b5c15768b8a80e1be7010afb769227f133e285..804f1672d4ea7fccb7b85ac2139b79ace6f6b47b 100644 --- a/index.html +++ b/index.html @@ -3,7 +3,7 @@ -Cover Charge: try the apps (v0.3.12.214) +Cover Charge: try the apps (v0.3.12.215) @@ -63,7 +63,7 @@ footer{margin-top:28px;color:var(--muted);font-size:.8rem;text-align:center} Cover Charge logo

covercharge

All in one restaurant booking app

-

Cover Charge: try the apps (v0.3.12.214)

+

Cover Charge: try the apps (v0.3.12.215)

The Anchorage, Harbour View, Dunure

@@ -129,7 +129,7 @@ footer{margin-top:28px;color:var(--muted);font-size:.8rem;text-align:center}
-

Cover Charge v0.3.12.214

+

Cover Charge v0.3.12.215

diff --git a/owner-app/_expo/static/js/web/bundle.js b/owner-app/_expo/static/js/web/bundle.js index e5645e131cac00bd7e3147b9733245f7676bd937..ba8cfddaecfa6adfe0c39cccaec8e7d4b25d4735 100644 --- a/owner-app/_expo/static/js/web/bundle.js +++ b/owner-app/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?`
    ${n.map(t=>`
  • ${p(t)}
  • `).join('')}
`:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/owner-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(_g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"CREATOR_TITLE",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"pounds",{enumerable:!0,get:function(){return v}}),Object.defineProperty(_e,"numIn",{enumerable:!0,get:function(){return C}}),_e.useOwnCosting=I,_e.DishCreator=function({rid:e,canPublish:t,initial:n="create"}){const l=I(),o=(0,d.useGpCalcView)(),[c,p]=(0,i.useState)(n),[g,h]=(0,i.useState)(()=>P(o.settings.defaultTarget));return l?(0,f.jsxs)(r.default,{style:{gap:12},testID:"dish-creator",children:[o.alerts.map(e=>(0,f.jsx)(r.default,{testID:"margin-alert",children:(0,f.jsx)(a.Banner,{kind:"danger",title:`Margin dropped: ${e.ingredient} ${e.change}`,children:(0,f.jsxs)(r.default,{style:{gap:4},children:[e.dishes.map(e=>(0,f.jsxs)(a.T,{size:14,colour:"#FFE3DF",children:[e.name,": ",(0,u.pct)(e.before)," \u2192 ",(0,u.pct)(e.after),e.belowTarget?' \xb7 below target':'']},e.id)),(0,f.jsx)(s.ToastClose,{label:"Dismiss alert",testID:`margin-alert-close-${e.id}`,onPress:()=>o.dismissAlert(e.id),size:"sm",style:{alignSelf:'flex-end'}})]})})},e.id)),(0,f.jsx)(y.Tabs,{value:c,onChange:p,options:[{id:'create',label:g.name&&o.dishes.some(e=>e.id===g.id)?'Edit dish':'Create'},{id:'saved',label:'Saved dishes & GP'},{id:'items',label:'Ingredient prices'},{id:'settings',label:'VAT & rounding'}]}),'create'===c?(0,f.jsx)(D,{draft:g,setDraft:h,onNew:()=>h(P(o.settings.defaultTarget)),onSaved:()=>p('saved')},g.id):null,'saved'===c?(0,f.jsx)(G,{rid:e,canPublish:t,onEdit:e=>{h({...e,allergens:[...e.allergens??[]]}),p('create')}}):null,'items'===c?(0,f.jsx)(V,{}):null,'settings'===c?(0,f.jsx)(W,{}):null,(0,f.jsx)(a.Muted,{children:"Costs are visible to Managers and the Head Chef only. Prices you enter, not supplier quotes."})]}):(0,f.jsx)(r.default,{testID:"dish-creator-no-access",style:{alignItems:'center',paddingVertical:16},children:(0,f.jsx)(a.Muted,{center:!0,children:"Ingredient prices and dish costs are for the Head Chef, owners and managers."})})},_e.NewIngredient=A,Object.defineProperty(_e,"TALL",{enumerable:!0,get:function(){return L}}),_e.Pick=R,_e.Items=V,_e.useCardCosting=function(e,t,s="edit"){const{ingredients:n,settings:l,cardCosts:r}=(0,d.useGpCalcView)(),a=I();return(0,i.useMemo)(()=>{if(!e||!a||!(0,p.cardCostsVisible)(t,s))return null;const i=r?.[e.id];if(!i?.lines.length)return null;const o=(0,u.cardCostSummary)(i,n,l,e.price),d={};return o.lines.forEach(e=>{e.line.recipeIngId&&(d[e.line.recipeIngId]={cost:(d[e.line.recipeIngId]?.cost??0)+e.cost,label:e.label})}),{summary:o,byRecipeIng:d}},[e,t,s,a,n,l,r])},_e.CardGpPanel=function({card:e,actor:s,mode:n="edit"}){const{ingredients:l,settings:o,cardCosts:c,saveCardCost:g}=(0,d.useGpCalcView)(),h=I()&&(0,p.cardCostsVisible)(s.role,n),y=h&&'staff'!==s.role,w=c?.[e.id]??{lines:[],portions:1},P=(0,u.cardCostSummary)(w,l,o,e.price),[$,S]=(0,i.useState)(''),[D,k]=(0,i.useState)(),[M,G]=(0,i.useState)(!1),[B,V]=(0,i.useState)(w.menuPrice?(w.menuPrice/100).toFixed(2):''),[z,W]=(0,i.useState)(!1),[F,E]=(0,i.useState)(null),[U,H]=(0,i.useState)(!w.lines.length),[q,_]=(0,i.useState)(!1),[Y,X]=(0,i.useState)(null!=w.target?String(w.target):'');if(!h)return null;const K=t=>g(e.id,{...d.useGpCalc.getState().cardCosts[e.id]??w,...t}),J=(e,t)=>{if(t){const s=(0,b.suggestAmount)(t.qty,t.unit,e);if(s.qty>0)return s}const s=e.servings?'serving':(0,u.unitsFor)(e.packUnit)[0];return{qty:'serving'===s||'each'===s?1:0,unit:s}},Q=(t,s=D)=>{const i=e.ingredients.find(e=>e.id===s),n={ingId:t.id,...J(t,i),...s?{recipeIngId:s}:{}},l=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...l.lines,n]}),S(''),k(void 0),G(!1),_(!1)},Z=(e,t)=>K({lines:w.lines.map((s,i)=>i===e?{...s,...t}:s)}),ee=new Set(w.lines.map(e=>e.recipeIngId).filter(Boolean)),te=e.ingredients.filter(e=>e.name.trim()&&!ee.has(e.id)),se=te.map(e=>({ri:e,i:(0,b.matchIngredient)(e.name,l)})).filter(e=>!!e.i),ie=P.price?P.price/(1+o.vatPct/100):null,ne=l.filter(e=>!$.trim()||$.trim().toLowerCase().split(/\s+/).some(t=>t.length>2&&e.name.toLowerCase().includes(t))||e.name.toLowerCase().includes($.trim().toLowerCase())).slice(0,12),le=v(B),re=P.tone?T[P.tone]:x.colours.muted,ae=null!=e.price&&P.price===e.price;return(0,f.jsxs)(r.default,{testID:"card-gp",accessibilityLabel:"GP calculator",style:{width:'100%',gap:10,padding:14,borderRadius:18,borderWidth:1.5,borderColor:x.colours.gold,backgroundColor:N},children:[(0,f.jsx)(a.T,{size:20,weight:"bold",center:!0,colour:x.colours.gold,accessibilityRole:"header",children:"GP calculator"}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["Costs from the price list (latest delivery prices) \xb7 target ",P.target,"% GP"]}),P.price?(0,f.jsxs)(r.default,{testID:"gp-vat-line",accessible:!0,accessibilityLabel:`Menu price ${(0,u.money)(P.price)} including VAT, ${(0,u.money)(ie)} without VAT. GP is worked out on the price without VAT.`,style:{alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,weight:"semibold",children:[(0,u.money)(P.price)," inc VAT \xb7 ",(0,u.money)(ie)," ex VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:[P.priceIsSuggested?'Suggested price':w.menuPrice?'The price you typed':'Menu price on the card'," \xb7 GP is on the ex-VAT price"]})]}):null,w.lines.length?(0,f.jsx)(r.default,{testID:"card-gp-lines",style:{gap:8},children:P.lines.map((e,s)=>{const i=l.find(t=>t.id===e.line.ingId);return(0,f.jsxs)(r.default,{testID:"card-gp-line",style:{gap:6,paddingVertical:8,borderTopWidth:s?1:0,borderColor:x.colours.accentBorder},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}, ${e.label}, ${i?`${(0,u.money)(e.cost)}, ${(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}`:'not on the price list'}`,style:{flexDirection:'row',gap:8,alignItems:'center',minHeight:32},children:[(0,f.jsxs)(r.default,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(a.T,{weight:"medium",children:e.name}),(0,f.jsx)(a.T,{size:x.font.small,colour:x.colours.muted,children:e.label}),i?(0,f.jsx)(a.T,{testID:"card-gp-line-rates",size:x.font.small,colour:x.colours.goldLight,children:(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}):null]}),(0,f.jsx)(a.T,{weight:"semibold",colour:i?x.colours.goldLight:x.colours.amber,children:i?(0,u.money)(e.cost):'Removed'})]}),U&&y&&i?(()=>{const n=(0,u.unitsFor)(i.packUnit,i.servings),l=t=>(0,f.jsx)(R,{testID:`gp-unit-${s}-${t}`,label:'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2),accessibilityLabel:`${e.name} by ${'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2)}`,selected:e.line.unit===t,onPress:()=>Z(s,{unit:t})},t);return(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:`gp-qty-${s}`,accessibilityLabel:`Amount of ${e.name}`,value:e.line.qty?String(e.line.qty):'',onChangeText:e=>Z(s,{qty:C(e)??0}),placeholder:"amount",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),n.slice(0,-1).map(l),(0,f.jsxs)(r.default,{testID:`gp-unit-end-${s}`,style:{flexDirection:'row',flexWrap:'nowrap',alignItems:'center',gap:6},children:[n.slice(-1).map(l),(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})]})]})})():U&&y?(0,f.jsx)(a.Row,{gap:6,style:{justifyContent:'center'},children:(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})}):null]},s)})}):(0,f.jsx)(r.default,{testID:"card-gp-empty",style:{alignItems:'center',paddingVertical:6},children:(0,f.jsxs)(a.T,{center:!0,colour:x.colours.goldLight,children:["Not costed yet.",y?' Add the ingredients from your price list below.':'']})}),y&&w.lines.length?(0,f.jsx)(a.Button,{small:!0,kind:U?'primary':'secondary',testID:"gp-edit",label:U?'Done':'Change amounts or ingredients',accessibilityLabel:U?'Done changing the costing':`Change the costing for ${e.dish}`,onPress:()=>{H(!U),G(!1)}}):null,y&&U?(0,f.jsxs)(r.default,{style:{gap:8,alignItems:'center'},children:[se.length?(0,f.jsx)(a.Button,{testID:"gp-link-all",label:`Link ${se.length} matching price${1===se.length?'':'s'}`,accessibilityLabel:`Link ${se.length} of this card's ingredients to matching items on the price list`,onPress:()=>{const t=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...t.lines,...se.map(({ri:e,i:t})=>({ingId:t.id,...J(t,e),recipeIngId:e.id}))]}),E(`Linked ${se.length} ingredient${1===se.length?'':'s'} to the price list. Check the amounts below.`)},style:{minHeight:52}}):null,te.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Cost this card\u2019s ingredients"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:te.slice(0,10).map(e=>(0,f.jsx)(R,{testID:`gp-cost-${e.id}`,label:e.name.split(',')[0].slice(0,28),accessibilityLabel:`Cost ${e.name}`,selected:D===e.id,onPress:()=>{k(e.id),S(e.name.split(/[,(]/)[0].trim()),G(!0)}},e.id))})]}):null,M?(0,f.jsxs)(r.default,{style:{width:'100%',gap:6},children:[(0,f.jsx)(t.TextInput,{testID:"gp-search",accessibilityLabel:"Search ingredient prices",value:$,onChangeText:S,placeholder:"Search the price list",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[ne.map(e=>{const t=(0,u.perServing)(e),s=(0,u.perBaseUnit)(e),i=null!=t?`${(0,u.money)(t)} a ${(0,u.servingWord)(e,1)}`:s?`${(0,u.money)(s.pence)} a ${s.per}`:(0,u.money)(e.packPrice);return(0,f.jsx)(R,{testID:`gp-pick-${e.id}`,label:`${e.name} \xb7 ${i}`,accessibilityLabel:`Add ${e.name}, ${i}`,onPress:()=>Q(e)},e.id)}),ne.length?null:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:l.length?'Nothing on the price list matches.':'The price list is empty. Add a price here, or record a delivery.'})]}),q?(0,f.jsx)(A,{initial:$.trim(),onDone:e=>{_(!1);const t=e?d.useGpCalc.getState().ingredients.find(t=>t.id===e):void 0;t&&Q(t)}}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add-price",label:$.trim()?`Add a price for ${$.trim().slice(0,30)}`:'Add a new price',accessibilityLabel:`Add ${$.trim()||'a new ingredient'} to the price list and cost it on this card`,onPress:()=>_(!0)}),(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>{G(!1),k(void 0),S(''),_(!1)}})]}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add",kind:"secondary",label:"Add from ingredient prices",onPress:()=>{G(!0),k(void 0)}}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Target GP %"}),(0,f.jsx)(t.TextInput,{testID:"gp-target",accessibilityLabel:`Target GP percent for this dish, now ${P.target}`,value:Y,onChangeText:e=>{X(e);const t=C(e);null!=t&&t>0&&t<95?K({target:t}):e.trim()||K({target:void 0})},placeholder:String(o.defaultTarget),placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{testID:"gp-portions",accessibilityLabel:"Portions this recipe makes",value:String(w.portions||1),onChangeText:e=>K({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]})]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost",label:"Food cost per portion",value:(0,u.money)(P.perPortion),colour:x.colours.goldLight,sub:(w.portions||1)>1?`Batch ${(0,u.money)(P.batch)} \xf7 ${w.portions}`:P.missing?`${P.missing} line${1===P.missing?'':'s'} not costed`:void 0}),(0,f.jsx)(O,{testID:"gp-suggested",label:`Suggested at ${P.target}% GP`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?"inc VAT"+(o.pricePoints?', rounded up':''):'Add amounts first'})]}),y?(0,f.jsxs)(r.default,{style:{gap:6,alignItems:'center'},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Your menu price (inc VAT)"}),(0,f.jsxs)(a.Row,{gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{size:24,style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{testID:"gp-price",accessibilityLabel:"Your menu price in pounds, including VAT",value:B,onChangeText:e=>{const t=(0,j.sanitiseMoneyTyping)(e);V(t);const s=v(t);null!=s&&s>0?K({menuPrice:s}):t.trim()||K({menuPrice:void 0})},placeholder:P.price?(P.price/100).toFixed(2):'0.00',placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{minHeight:56,width:150,fontSize:24,textAlign:'center'}]})]}),(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:le?'GP below uses the price you typed.':e.price?`Blank uses the menu price, ${(0,u.money)(e.price)}.`:'Blank uses the suggested price.'}),P.suggested&&!le?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:"gp-use-suggested",label:`Use suggested ${(0,u.money)(P.suggested)}`,accessibilityLabel:`Use the suggested price, ${(0,u.money)(P.suggested)}`,onPress:()=>{V((P.suggested/100).toFixed(2)),K({menuPrice:P.suggested})}}):null]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-gp",label:`GP on ${P.price?(0,u.money)(P.price):'the price'}`,value:null!=P.gp?(0,u.pct)(P.gp):'\u2014',colour:re,sub:null!=P.gp?'ok'===P.tone?'On target':'amber'===P.tone?'Just under target':'Below target':void 0}),(0,f.jsx)(O,{testID:"gp-cash",label:"Cash GP per portion",value:null!=P.cashGp?(0,u.money)(P.cashGp):'\u2014',colour:re,sub:P.price?`${(0,u.money)(P.price/(1+o.vatPct/100))} ex VAT`:void 0})]}),(()=>{const e=(0,u.foodCostTargetOf)(P.target),t=null!=P.foodCostPct?(0,u.foodCostTone)(P.foodCostPct,e):null,s=t?T[t]:x.colours.muted,i=P.price&&P.perPortion>0?(0,u.vatAwareGp)(P.perPortion,P.price,o.vatPct):null;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost-pct",label:"Food cost %",value:null!=P.foodCostPct?(0,u.pct)(P.foodCostPct):'\u2014',colour:s,sub:null!=P.foodCostPct?`Target ${e}% \xb7 ${'ok'===t?'on target':'amber'===t?'just over':'over target'}`:`Target ${e}%`}),(0,f.jsx)(O,{testID:"gp-suggested-target",label:`Price for ${e}% food cost`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?'inc VAT':'Add amounts first'})]}),i?(0,f.jsxs)(r.default,{testID:"gp-vat-aware",accessible:!0,accessibilityLabel:`VAT ${(0,u.money)(i.vatPence)} of the ${(0,u.money)(P.price)} goes to the tax office. GP on the price without VAT is ${(0,u.pct)(i.gpPct)}. With VAT left in it would wrongly look like ${(0,u.pct)(i.naiveGpPct)}.`,style:{alignItems:'center',gap:2},children:[(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["VAT ",o.vatPct,"%: ",(0,u.money)(i.vatPence)," of each ",(0,u.money)(P.price)," is VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:["True GP ",(0,u.pct)(i.gpPct)," (ex VAT) \xb7 would look like ",(0,u.pct)(i.naiveGpPct)," with VAT left in"]})]}):null]})})(),y&&P.price&&!ae?z?(0,f.jsxs)(r.default,{testID:"gp-menu-confirm",style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Put ",(0,u.money)(P.price)," on the menu? The card goes back to Awaiting sign-off until a chef signs it again."]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"gp-menu-yes",label:`Yes, use ${(0,u.money)(P.price)}`,onPress:async()=>{if(P.price)try{await(0,m.recipeCards)().update(e.id,{price:P.price},s),E(`Menu price set to ${(0,u.money)(P.price)}. The card now waits for sign-off again.`),W(!1)}catch(e){E(e?.message??'Could not change the menu price.')}}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Not now",onPress:()=>W(!1)})]})]}):(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:"gp-menu",label:`Use ${(0,u.money)(P.price)} on the menu`,accessibilityLabel:`Use ${(0,u.money)(P.price)} as the menu price for ${e.dish}`,onPress:()=>W(!0)}):null,F?(0,f.jsx)(a.T,{center:!0,size:x.font.small,colour:x.colours.goldLight,children:F}):null,(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"GP is worked out on the price without VAT. Only the Head Chef and managers see costs."})]})};var t=_r(_d[0]),s=_r(_d[1]),i=_r(_d[2]),n=e(_r(_d[3]));_r(_d[4]);var l=e(_r(_d[5])),r=e(_r(_d[6])),a=_r(_d[7]),o=_r(_d[8]),d=_r(_d[9]),c=_r(_d[10]),u=_r(_d[11]),p=_r(_d[12]),g=_r(_d[13]),h=_r(_d[14]),m=_r(_d[15]),x=_r(_d[16]),y=_r(_d[17]),b=_r(_d[18]),j=_r(_d[19]),f=_r(_d[20]);const w='New dish creator',T={ok:x.colours.ok,amber:x.colours.amber,red:x.colours.red},v=e=>{const t=(0,j.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):null},C=e=>{const t=e.trim().replace(',','.');return/^\d*\.?\d+$/.test(t)?Number(t):null},P=e=>({id:(0,d.gid)('gd'),name:'',lines:[],portions:1,target:e,status:'draft',allergens:[],description:''});function I(){const e=(0,h.useSession)(e=>e.meId),t=(0,g.useOwner)(t=>e?t.staff.find(t=>t.id===e):void 0);return!e||!!t&&t.active&&(0,p.costsAllowedFor)(t)}function $({n:e,title:t,children:s,testID:i}){return(0,f.jsxs)(y.Box,{testID:i,children:[(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(r.default,{style:{width:30,height:30,borderRadius:15,backgroundColor:x.colours.gold,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.onGold,children:e})}),(0,f.jsx)(a.T,{size:18,weight:"semibold",style:{flex:1},children:t})]}),s]})}function S({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n}){return(0,f.jsxs)(r.default,{testID:i,style:{flexGrow:1,flexBasis:140,padding:12,borderRadius:14,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border,gap:2},children:[(0,f.jsx)(a.Muted,{children:e}),(0,f.jsx)(a.T,{size:30,weight:"bold",colour:s,children:t}),n?(0,f.jsx)(a.Muted,{children:n}):null]})}function D({draft:e,setDraft:n,onNew:l,onSaved:o}){const{ingredients:p,dishes:g,settings:h,saveDish:m}=(0,d.useGpCalcView)(),[b,w]=(0,i.useState)(''),[P,I]=(0,i.useState)(!1),[D,L]=(0,i.useState)(''),[R,M]=(0,i.useState)(e.menuPrice?'price':'gp'),[G,B]=(0,i.useState)(e.menuPrice?(e.menuPrice/100).toFixed(2):''),[V,z]=(0,i.useState)(String(e.target)),[W,N]=(0,i.useState)(String(e.targetX??4)),O=t=>n({...e,...t}),F=g.filter(t=>t.id!==e.id),E=(0,u.portionCost)(e,p,g),U=h.vatPct,H=C(V)??e.target,q=C(W)??4,_='price'===R?v(G):E>0?'gp'===R?(0,u.suggestPrice)(E,H,U,h.pricePoints):(0,u.suggestForMultiple)(E,q,U,h.multipleBasis,h.pricePoints):null,Y=_?(0,u.gpOf)(E,_,U):null,X=_?(0,u.multipleOf)(E,_,U,h.multipleBasis):0,K=Y?(0,u.toneFor)(Y.gpPct,H):'ok',J=(0,u.suggestAllergens)(e,p,g),Q=t=>{const s=p.find(e=>e.id===t),i=t.startsWith('dish:')?'each':(0,u.unitsFor)(s.packUnit,s.servings)[0],l=[...e.lines,{ingId:t,qty:t.startsWith('dish:')?1:0,unit:i}],r={...e,lines:l},a=(0,u.suggestAllergens)(r,p,g);n({...r,allergens:Array.from(new Set([...e.allergens??[],...a]))})},Z=(t,s)=>O({lines:e.lines.map((e,i)=>i===t?{...e,...s}:e)}),ee=p.filter(e=>!b.trim()||e.name.toLowerCase().includes(b.trim().toLowerCase())),te=t=>{if(!e.name.trim())return L('Give the dish a name first.');if('ready'===t){if(!e.category)return L('Pick a category to make it menu-ready.');if(!e.lines.length||E<=0)return L('Add ingredients with quantities to make it menu-ready.');if(!_)return L('Set a price to make it menu-ready.')}const s='published'===e.status?'published':t;m({...e,name:e.name.trim(),target:H,targetX:q,menuPrice:_??void 0,status:s}),L('ready'===t?`Saved \u201c${e.name.trim()}\u201d as menu-ready. A manager can publish it to the menu.`:`Saved \u201c${e.name.trim()}\u201d as a draft.`)};return(0,f.jsxs)(r.default,{style:{gap:12},children:[(0,f.jsxs)($,{n:1,title:"Name and category",testID:"step-name",children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:"Dish name",value:e.name,onChangeText:e=>O({name:e.slice(0,60)}),placeholder:"e.g. Cullen skink",placeholderTextColor:"#7D776C",style:[a.styles.input,{fontSize:20}]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:u.DISH_CATEGORIES.map(t=>(0,f.jsx)(a.Chip,{label:t,selected:e.category===t,onPress:()=>O({category:t})},t))})]}),(0,f.jsxs)($,{n:2,title:"Add saved items and ingredients",testID:"step-ingredients",children:[F.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.Muted,{children:"Saved items (tap to add a portion)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:F.map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(`dish:${e.id}`)},e.id))})]}):null,(0,f.jsx)(a.Muted,{children:"Ingredients"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredients",value:b,onChangeText:w,placeholder:"Search ingredients",placeholderTextColor:"#7D776C",style:a.styles.input}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[ee.slice(0,24).map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(e.id)},e.id)),(0,f.jsx)(a.Chip,{label:"New ingredient",onPress:()=>I(!0)})]}),P?(0,f.jsx)(A,{initial:b,onDone:e=>{I(!1),w(''),e&&Q(e)}}):null,e.lines.length?(0,f.jsx)(r.default,{style:{gap:8},testID:"dish-lines",children:e.lines.map((i,n)=>{const l=i.ingId.startsWith('dish:'),o=p.find(e=>e.id===i.ingId),d=(c=i.ingId).startsWith('dish:')?g.find(e=>e.id===c.slice(5))?.name??'Saved item':p.find(e=>e.id===c)?.name??'?';var c;return(0,f.jsxs)(r.default,{testID:"dish-line",style:{gap:6,padding:10,borderRadius:12,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between'},children:[(0,f.jsxs)(a.T,{weight:"medium",style:{flex:1},children:[d,l?' (saved item)':'']}),(0,f.jsx)(a.T,{weight:"semibold",children:(0,u.money)((0,u.lineCost)(i,p,g))}),(0,f.jsx)(s.GoldClose,{size:"sm",label:`Remove ${d}`,onPress:()=>O({lines:e.lines.filter((e,t)=>t!==n)})})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Quantity of ${d}`,value:i.qty?String(i.qty):'',onChangeText:e=>Z(n,{qty:C(e)??0}),placeholder:"qty",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:90}]}),l?(0,f.jsx)(a.Muted,{children:"portion(s)"}):(0,u.unitsFor)(o.packUnit,o.servings).map(e=>(0,f.jsx)(a.Chip,{label:'serving'===e?(0,u.servingWord)(o,2):(0,u.unitName)(e,2),selected:i.unit===e,onPress:()=>Z(n,{unit:e})},e)),l?null:(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${d}`,value:null==i.wastePct?'':String(i.wastePct),onChangeText:e=>Z(n,{wastePct:''===e.trim()?void 0:C(e)??0}),placeholder:`waste ${o.wastePct}%`,placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:110}]})]})]},n)})}):(0,f.jsx)(a.Muted,{children:"Nothing added yet. Tap a saved item or an ingredient above."}),(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Portions per batch",value:String(e.portions),onChangeText:e=>O({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,{width:80,textAlign:'center'}]})]}),(0,f.jsx)(S,{testID:"cost-per-plate",label:"Cost per plate",value:(0,u.money)(E),sub:e.portions>1?`Batch cost ${(0,u.money)(E*e.portions)} \xf7 ${e.portions}`:'Live: updates as you type'})]}),(0,f.jsxs)($,{n:3,title:"Price it",testID:"step-price",children:[(0,f.jsx)(y.Tabs,{value:R,onChange:M,options:[{id:'gp',label:'Target GP %'},{id:'x',label:'Target multiple'},{id:'price',label:'Type a price'}]}),'gp'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[65,70,75].map(e=>(0,f.jsx)(a.Chip,{label:`${e}%`,selected:H===e,onPress:()=>z(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target GP %",value:V,onChangeText:z,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'x'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[3,4,5].map(e=>(0,f.jsx)(a.Chip,{label:`${e}x`,selected:q===e,onPress:()=>N(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target multiple",value:W,onChangeText:N,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'price'===R?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{size:24,children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Menu price (inc VAT)",value:G,onChangeText:e=>B((0,j.sanitiseMoneyTyping)(e)),placeholder:"0.00",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{width:140,fontSize:24}]}),(0,f.jsx)(a.Muted,{children:"inc VAT"})]}):null,'price'!==R?(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"suggested-price",label:`Suggested menu price (inc ${U}% VAT)`,value:_?(0,u.money)(_):'\u2014',colour:x.colours.gold,sub:_?`${(0,u.money)(_/(1+U/100))} ex VAT${h.pricePoints?' \xb7 rounded up to .50 / .95':''}`:'Add ingredients first'}),_?(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Type my own price",onPress:()=>{B((_/100).toFixed(2)),M('price')}}):null]}):null,(()=>{const t=(0,u.avgMenuPrice)(g,e.category,e.id);return e.category?(0,f.jsx)(r.default,{testID:"avg-menu-price",children:(0,f.jsx)(a.Muted,{children:t?`Average menu price for ${e.category}: ${(0,u.money)(t.avg)} (${t.count} dish${1===t.count?'':'es'})${_?` \xb7 this dish ${_>=t.avg?'+':'\u2212'}${(0,u.money)(Math.abs(_-t.avg))}`:''}`:`No other priced ${e.category.toLowerCase()} yet to compare with.`})}):null})(),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"big-gp",label:`GP (target ${H}%)`,value:Y?(0,u.pct)(Y.gpPct):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-x",label:`Multiple (${'inc'===h.multipleBasis?'inc VAT price':'ex VAT price'} \xf7 cost)`,value:Y&&E>0?(0,u.fmtX)(X):'\u2014',colour:x.colours.gold}),(0,f.jsx)(S,{testID:"big-profit",label:"Profit per plate (cash GP)",value:Y?(0,u.money)(Y.cashGp):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-foodcost",label:"Food cost",value:Y?(0,u.pct)(Y.foodCostPct):'\u2014'})]}),(0,f.jsxs)(a.Muted,{children:["GP is worked out on the price without VAT (",U,"% VAT). Gold: at or above target \xb7 amber: up to 5 points under \xb7 red: more than 5 under."]})]}),(0,f.jsxs)($,{n:4,title:"Photo, allergens and description",testID:"step-details",children:[(0,f.jsx)(k,{value:e.photo,onChange:e=>O({photo:e})}),(0,f.jsx)(a.T,{weight:"medium",children:"Allergens (14 UK allergens)"}),J.length?(0,f.jsx)(r.default,{testID:"allergen-suggest",children:(0,f.jsxs)(a.Muted,{children:["Suggested from the ingredients: ",J.map(e=>c.ALLERGENS.find(t=>t.id===e).short).join(', '),". Check before it goes on the menu."]})}):(0,f.jsx)(a.Muted,{children:"No allergens known from these ingredients yet. Tick any that apply."}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:c.ALLERGENS.map(t=>{const s=(e.allergens??[]).includes(t.id);return(0,f.jsx)(a.Chip,{label:`${s?'\u2713 ':''}${t.short}`,sub:J.includes(t.id)?'suggested':void 0,selected:s,onPress:()=>O({allergens:s?e.allergens.filter(e=>e!==t.id):[...e.allergens??[],t.id]})},t.id)})}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Short description",value:e.description??'',onChangeText:e=>O({description:e.slice(0,160)}),multiline:!0,placeholder:"Short description for the menu (up to 160 characters)",placeholderTextColor:"#7D776C",style:[a.styles.input,{minHeight:70,textAlignVertical:'top'}]}),(0,f.jsxs)(a.Muted,{children:[(e.description??'').length,"/160"]})]}),(0,f.jsxs)($,{n:5,title:"Save",testID:"step-save",children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(a.Button,{label:"Save as draft",kind:"secondary",testID:"save-draft",onPress:()=>te('draft'),style:{flexGrow:1}}),(0,f.jsx)(a.Button,{label:"Save as menu-ready dish",testID:"save-ready",onPress:()=>te('ready'),style:{flexGrow:1}})]}),D?(0,f.jsx)(r.default,{testID:"creator-msg",children:(0,f.jsx)(a.T,{size:15,colour:D.startsWith('Saved')?x.colours.ok:x.colours.amber,children:D})}):null,D.startsWith('Saved')?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.Button,{small:!0,label:"See saved dishes",onPress:o}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Start a new dish",onPress:()=>{l(),L(''),B(''),M('gp')}})]}):null]})]})}function k({value:e,onChange:t}){return(0,f.jsxs)(a.Row,{gap:10,children:[e?(0,f.jsx)(n.default,{testID:"dish-photo",source:{uri:e},style:{width:96,height:72,borderRadius:10}}):(0,f.jsx)(r.default,{style:{width:96,height:72,borderRadius:10,borderWidth:1,borderStyle:'dashed',borderColor:x.colours.border,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.Muted,{children:"No photo"})}),(0,f.jsxs)(r.default,{style:{gap:6},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:e?'Change photo':'Add photo (optional)',onPress:()=>{if('undefined'==typeof document)return;const e=document.createElement('input');e.type='file',e.accept='image/*',e.onchange=()=>{const s=e.files?.[0];if(!s)return;const i=new FileReader;i.onload=()=>{const e=new window.Image;e.onload=()=>{const s=Math.min(1,480/Math.max(e.width,e.height)),i=document.createElement('canvas');i.width=Math.round(e.width*s),i.height=Math.round(e.height*s),i.getContext('2d').drawImage(e,0,0,i.width,i.height),t(i.toDataURL('image/jpeg',.8))},e.src=String(i.result)},i.readAsDataURL(s)},e.click()}}),e?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Remove photo",onPress:()=>t(void 0)}):null]})]})}function A({initial:e,onDone:s,edit:n}){const[l,o]=(0,i.useState)(n?.name??e),[p,g]=(0,i.useState)(n?String(n.packSize):''),[h,m]=(0,i.useState)(n?.packUnit??'kg'),[y,b]=(0,i.useState)(n?(n.packPrice/100).toFixed(2):''),[w,T]=(0,i.useState)(n?.wastePct?String(n.wastePct):''),[P,I]=(0,i.useState)(n?.allergens??[]),[$,S]=(0,i.useState)(n?.servings?String(n.servings):''),[D,k]=(0,i.useState)(n?.servingName??''),[A,M]=(0,i.useState)(n?.supplier??''),G=!(!l.trim()||!C(p)||null==v(y)||''!==$.trim()&&!C($)),B={id:'probe',name:l,packSize:C(p)??0,packUnit:h,packPrice:v(y)??0,wastePct:0,servings:C($)??void 0,servingName:D.trim()||void 0},V=B.packSize&&B.packPrice?(0,u.perBaseUnit)(B):null,z=B.packPrice?(0,u.perServing)(B):null,W={name:l.trim(),packSize:C(p),packUnit:h,packPrice:v(y),wastePct:Math.min(90,C(w)??0),allergens:P,servings:C($)??void 0,servingName:D.trim().toLowerCase()||void 0,supplier:A.trim()||void 0};return(0,f.jsxs)(r.default,{testID:n?`edit-ingredient-${n.id}`:'new-ingredient',style:{gap:8,padding:12,borderRadius:14,borderWidth:1,borderColor:x.colours.gold,width:'100%'},children:[(0,f.jsx)(a.T,{weight:"semibold",center:!0,accessibilityRole:"header",children:n?`Edit ${n.name}`:'New ingredient'}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Ingredient name",value:l,onChangeText:o,placeholder:"e.g. Haddock",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Pack price and what you get for it, e.g. \xa3110 for 1 stone, or \xa340 for 5 kg"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:"ing-pack-price",accessibilityLabel:"Pack price in pounds",value:y,onChangeText:e=>b((0,j.sanitiseMoneyTyping)(e)),placeholder:"\xa3 price",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110,textAlign:'center'}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"for"}),(0,f.jsx)(t.TextInput,{testID:"ing-pack-size",accessibilityLabel:"Pack size",value:p,onChangeText:g,placeholder:"size",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]})]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:u.PACK_UNITS.map(e=>(0,f.jsx)(R,{testID:`ing-unit-${e}`,label:(0,u.unitName)(e,2),selected:h===e,onPress:()=>m(e)},e))}),(0,f.jsx)(a.Muted,{center:!0,children:"Optional: roughly how many servings or pieces one pack gives"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"averages"}),(0,f.jsx)(t.TextInput,{testID:"ing-servings",accessibilityLabel:"Averages how many servings or pieces",value:$,onChangeText:S,placeholder:"e.g. 30",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),(0,f.jsx)(t.TextInput,{testID:"ing-serving-name",accessibilityLabel:"What one is called, for example serving, breast or piece",value:D,onChangeText:k,placeholder:"serving / breast",placeholderTextColor:"#7D776C",style:[a.styles.input,L,{width:150,textAlign:'center'}]})]}),V||null!=z?(0,f.jsx)(r.default,{testID:"ing-derived",accessible:!0,accessibilityLabel:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(', '),children:(0,f.jsx)(a.T,{center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(' \xb7 ')})}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Supplier (optional)",value:A,onChangeText:M,placeholder:"Supplier (optional)",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Yield loss or waste percent (optional)",value:w,onChangeText:T,placeholder:"Trim / waste % (optional, for weights)",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Allergens in this ingredient (if known)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:c.ALLERGENS.map(e=>(0,f.jsx)(a.Chip,{label:e.short,selected:P.includes(e.id),onPress:()=>I(P.includes(e.id)?P.filter(t=>t!==e.id):[...P,e.id])},e.id))}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"ing-save",label:n?'Save ingredient':'Add ingredient',disabled:!G,onPress:()=>{if(n){const e=d.useGpCalc.getState();W.packPrice!==n.packPrice&&e.addPricePaid(n.id,W.packPrice);const t=d.useGpCalc.getState().ingredients.find(e=>e.id===n.id)??n;e.saveIngredient({...t,...W,packPrice:t.packPrice}),s(n.id)}else s(d.useGpCalc.getState().addIngredient(W))}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Cancel",onPress:()=>s()})]})]})}const L={minHeight:48};function R({label:e,selected:t,onPress:s,testID:i,accessibilityLabel:n}){return(0,f.jsx)(l.default,{testID:i,accessibilityRole:"button",accessibilityState:{selected:!!t},accessibilityLabel:`${n??e}${t?', selected':''}`,onPress:s,style:{minHeight:48,minWidth:48,paddingHorizontal:14,justifyContent:'center',alignItems:'center',borderRadius:24,borderWidth:1,borderColor:t?x.colours.gold:x.colours.border,backgroundColor:t?x.colours.gold:x.colours.surface2,maxWidth:'100%'},children:(0,f.jsx)(a.T,{size:x.font.small,weight:"medium",center:!0,colour:t?x.colours.onGold:x.colours.text,children:e})})}const M={draft:{label:'Draft',kind:'neutral'},ready:{label:'Menu-ready',kind:'gold'},published:{label:'On the menu',kind:'ok'}};function G({rid:e,canPublish:t,onEdit:s}){const{dishes:n,ingredients:l,settings:c,saveDish:p}=(0,d.useGpCalcView)(),[g,h]=(0,i.useState)('low'),[m,b]=(0,i.useState)(''),j=(0,i.useMemo)(()=>n.map(e=>{const t=(0,u.portionCost)(e,l,n);return{d:e,cost:t,g:e.menuPrice?(0,u.gpOf)(t,e.menuPrice,c.vatPct):null,x:e.menuPrice?(0,u.multipleOf)(t,e.menuPrice,c.vatPct,c.multipleBasis):0}}).sort((e,t)=>(e.g?e.g.gpPct:999)-(t.g?t.g.gpPct:999)),[n,l,c]),w='low'===g?j:[...j].reverse(),v=j.filter(e=>e.g&&e.g.gpPct{const s={};(t.allergens??[]).forEach(e=>{s[e]='contains'});const i=o.useStore.getState().addMenuItem({restaurantId:e,section:t.category??'Specials',name:t.name,description:t.description??'',price:t.menuPrice??null,dietary:[],allergens:s,prepMins:12,soldOut:!1,signOff:null});p({...t,status:'published',menuItemId:i}),b(`Published \u201c${t.name}\u201d to the menu (${t.category??'Specials'}). It needs allergen sign-off in Menu & allergens.`)};return(0,f.jsxs)(y.Box,{testID:"menu-gp",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"Saved dishes and items \xb7 Menu GP"}),(0,f.jsxs)(a.Muted,{children:[j.length," saved \xb7 ",v," below target \xb7 multiples on the ",'inc'===c.multipleBasis?'inc-VAT menu price':'ex-VAT price']}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Lowest GP first",selected:'low'===g,onPress:()=>h('low')}),(0,f.jsx)(a.Chip,{label:"Highest GP first",selected:'high'===g,onPress:()=>h('high')})]}),w.map(({d:e,cost:i,g:n,x:l})=>{const o=n?(0,u.toneFor)(n.gpPct,e.target):null;return(0,f.jsxs)(r.default,{testID:"gp-row",style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:4},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between',alignItems:'flex-start'},children:[(0,f.jsxs)(r.default,{style:{flex:1,gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",children:e.name}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Badge,{kind:M[e.status??'draft'].kind,label:M[e.status??'draft'].label}),e.category?(0,f.jsx)(a.Muted,{children:e.category}):null]}),(0,f.jsxs)(a.Muted,{children:["Cost ",(0,u.money)(i),e.menuPrice?` \xb7 price ${(0,u.money)(e.menuPrice)}`:' \xb7 no price yet']})]}),(0,f.jsxs)(r.default,{style:{alignItems:'flex-end'},children:[(0,f.jsx)(a.T,{size:22,weight:"bold",colour:o?T[o]:x.colours.muted,children:n?(0,u.pct)(n.gpPct):'\u2014'}),(0,f.jsx)(a.T,{size:16,weight:"semibold",colour:x.colours.gold,children:n&&i>0?(0,u.fmtX)(l):''})]})]}),n&&n.gpPcts(e)}),t&&'ready'===e.status?(0,f.jsx)(a.Button,{small:!0,label:"Publish to menu",accessibilityLabel:`Publish ${e.name} to menu`,onPress:()=>C(e)}):null,t||'ready'!==e.status?null:(0,f.jsx)(a.Muted,{children:"Waiting for a manager to publish"})]})]},e.id)}),m?(0,f.jsx)(r.default,{testID:"publish-msg",children:(0,f.jsx)(a.T,{size:14,colour:x.colours.ok,children:m})}):null]})}function B(){const{settings:e,setSettings:t}=(0,d.useGpCalcView)(),s=e.priceBasis??'latest',i=e.avgOf??5;return(0,f.jsxs)(r.default,{testID:"price-basis",style:{gap:6},children:[(0,f.jsx)(a.T,{weight:"medium",children:"Cost dishes using"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Chip,{label:"Latest price paid",selected:'latest'===s,onPress:()=>t({priceBasis:'latest'})}),(0,f.jsx)(a.Chip,{label:`Average price (last ${i})`,selected:'average'===s,onPress:()=>t({priceBasis:'average'})})]}),'average'===s?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Muted,{children:"Average of the last"}),[3,5,10].map(e=>(0,f.jsx)(a.Chip,{label:`${e} prices`,selected:i===e,onPress:()=>t({avgOf:e})},e))]}):null,(0,f.jsx)(a.Muted,{children:'average'===s?'Averages smooth out price swings, so GP doesn\u2019t jump every delivery.':'Uses the most recent price you paid.'})]})}function V(){const{ingredients:e,dishes:s,settings:n,cardCosts:l}=(0,d.useGpCalcView)(),[o,c]=(0,i.useState)(''),[u,p]=(0,i.useState)(''),[g,h]=(0,i.useState)(!1),m=e.filter(e=>!u.trim()||`${e.name} ${e.supplier??''}`.toLowerCase().includes(u.trim().toLowerCase())).slice().sort((e,t)=>e.name.localeCompare(t.name));return(0,f.jsxs)(y.Box,{testID:"calc-items",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",center:!0,accessibilityRole:"header",children:"Ingredient prices"}),(0,f.jsx)(a.Muted,{center:!0,children:"What you pay and what a pack gives you. Recipe cards and dishes cost themselves from this list and update when a price changes."}),(0,f.jsx)(a.Button,{testID:"ing-add-new",label:"Add an ingredient",onPress:()=>{h(!0),c('')}}),g?(0,f.jsx)(A,{initial:u,onDone:e=>{h(!1),e&&c('Added to the price list.')}}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredient prices",value:u,onChangeText:p,placeholder:"Search ingredients or suppliers",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(B,{}),m.map(e=>{return(0,f.jsx)(z,{i:e,n:n.avgOf??5,basis:n.priceBasis??'latest',used:(t=e.id,s.filter(e=>e.lines.some(e=>e.ingId===t)).length+Object.values(l??{}).filter(e=>e.lines.some(e=>e.ingId===t)).length),onSaved:e=>c(e)},e.id);var t}),m.length?null:(0,f.jsx)(r.default,{testID:"ing-empty",style:{alignItems:'center',paddingVertical:12},children:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:e.length?'No ingredients match.':'No ingredient prices yet. Add the first one above.'})}),o?(0,f.jsx)(r.default,{testID:"items-msg",children:(0,f.jsx)(a.T,{size:14,center:!0,colour:x.colours.ok,children:o})}):null]})}function z({i:e,used:s,n:n,basis:l,onSaved:o}){const[c,p]=(0,i.useState)(String(e.wastePct)),[g,h]=(0,i.useState)(''),[m,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(!1),T=(0,u.priceStats)(e,n),P=c!==String(e.wastePct),I=v(g),$=(0,u.perBaseUnit)(e),S=(0,u.perServing)(e),D=`${e.name}, ${(0,u.money)(e.packPrice)} for ${e.packSize} ${(0,u.unitName)(e.packUnit,e.packSize)}${e.servings?`, averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}, ${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:''}${$?`, ${(0,u.money)($.pence)} a ${$.per}`:''}${e.supplier?`, from ${e.supplier}`:''}`;return m?(0,f.jsx)(A,{initial:"",edit:e,onDone:t=>{y(!1),t&&o(`Saved ${e.name}. Recipe cards and dishes re-costed.`)}}):(0,f.jsxs)(r.default,{testID:`item-${e.id}`,style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:6},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:D,style:{gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",size:18,center:!0,children:e.name}),(0,f.jsxs)(a.T,{testID:`pack-${e.id}`,center:!0,colour:x.colours.goldLight,children:[(0,u.money)(e.packPrice)," for ",e.packSize," ",(0,u.unitName)(e.packUnit,e.packSize),e.servings?` \xb7 averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}`:'']}),(0,f.jsx)(a.T,{testID:`derived-${e.id}`,center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=S?`${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:'',$?`${(0,u.money)($.pence)} a ${$.per}`:''].filter(Boolean).join(' \xb7 ')}),(0,f.jsx)(a.Muted,{center:!0,children:[s?`used in ${s}`:'not used yet',e.supplier,e.updatedAt?`updated ${new Date(e.updatedAt).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:''].filter(Boolean).join(' \xb7 ')})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsxs)(r.default,{testID:`latest-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'latest'===l?x.colours.gold:x.colours.border},children:[(0,f.jsx)(a.Muted,{children:"Latest"}),(0,f.jsx)(a.T,{weight:"bold",children:(0,u.money)(T.latest)})]}),(0,f.jsxs)(r.default,{testID:`avg-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'average'===l?x.colours.gold:x.colours.border},children:[(0,f.jsxs)(a.Muted,{children:["Average (",T.count,")"]}),(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.gold,children:(0,u.money)(T.avg)})]}),T.count>1?(0,f.jsxs)(r.default,{style:{paddingHorizontal:10,paddingVertical:6},children:[(0,f.jsx)(a.Muted,{children:"Range"}),(0,f.jsxs)(a.T,{size:14,children:[(0,u.money)(T.min),"\u2013",(0,u.money)(T.max)]})]}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:`Price paid for ${e.name}`,value:g,onChangeText:e=>h((0,j.sanitiseMoneyTyping)(e)),placeholder:"price paid",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110}]}),(0,f.jsx)(a.Button,{small:!0,label:"Add price paid",testID:`add-price-${e.id}`,disabled:!I,onPress:()=>{d.useGpCalc.getState().addPricePaid(e.id,I),h(''),o(`Recorded ${(0,u.money)(I)} for ${e.name}. Dishes re-costed.`)}})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${e.name}`,value:c,onChangeText:p,keyboardType:"decimal-pad",style:[a.styles.input,L,{width:60}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"% waste"}),P?(0,f.jsx)(a.Button,{small:!0,label:"Save",disabled:null==C(c),onPress:()=>{d.useGpCalc.getState().saveIngredient({...e,wastePct:Math.min(90,C(c))}),o(`Saved ${e.name}. Dishes updated.`)}}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:`ing-edit-${e.id}`,label:"Edit",accessibilityLabel:`Edit ${e.name}`,onPress:()=>y(!0)}),b?null:(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:`ing-delete-${e.id}`,label:"Delete",accessibilityLabel:`Delete ${e.name}`,onPress:()=>w(!0)})]}),b?(0,f.jsxs)(r.default,{testID:`ing-delete-confirm-${e.id}`,style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Delete ",e.name," from the price list?",s?` ${s} ${1===s?'dish or card uses':'dishes or cards use'} it and will show it as removed.`:'']}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"danger",testID:`ing-delete-yes-${e.id}`,label:"Yes, delete",accessibilityLabel:`Yes, delete ${e.name}`,onPress:()=>{d.useGpCalc.getState().removeIngredient(e.id),o(`Deleted ${e.name}.`)}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Keep it",onPress:()=>w(!1)})]})]}):null]})}function W(){const{settings:e,setSettings:s}=(0,d.useGpCalcView)(),[n,l]=(0,i.useState)(String(e.vatPct)),[r,o]=(0,i.useState)(String(e.defaultTarget));return(0,f.jsxs)(y.Box,{testID:"calc-settings",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"VAT and rounding"}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"VAT rate %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"VAT rate %",value:n,onChangeText:e=>{l(e);const t=C(e);null!=t&&t<=50&&s({vatPct:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(B,{}),(0,f.jsx)(a.Toggle,{label:"Round suggested prices up to .50 / .95",value:e.pricePoints,onChange:e=>s({pricePoints:e})}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Default target GP %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Default target GP %",value:r,onChangeText:e=>{o(e);const t=C(e);null!=t&&t<95&&s({defaultTarget:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(a.T,{weight:"medium",children:"Cost multiple (x) is based on"}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Inc VAT (menu price)",selected:'inc'===e.multipleBasis,onPress:()=>s({multipleBasis:'inc'})}),(0,f.jsx)(a.Chip,{label:"Ex VAT",selected:'ex'===e.multipleBasis,onPress:()=>s({multipleBasis:'ex'})})]}),(0,f.jsx)(a.Muted,{children:"GP % uses the ex-VAT price. The price multiple is the menu price divided by ingredient cost."})]})}const N='#3A2F1E';function O({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n,said:l}){return(0,f.jsxs)(r.default,{testID:i,accessible:!0,accessibilityLabel:l??`${e}, ${t}${n?`, ${n}`:''}`,style:{flexGrow:1,flexBasis:128,minWidth:0,padding:10,borderRadius:14,backgroundColor:x.colours.surface,borderWidth:1,borderColor:x.colours.accentBorder,alignItems:'center',gap:2},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:e}),(0,f.jsx)(a.T,{size:28,weight:"bold",center:!0,colour:s,children:t}),n?(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:n}):null]})}},1157,[812,779,17,319,219,385,85,777,816,905,845,906,909,876,920,867,804,889,907,840,8]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1665,7 +1665,7 @@ __d(function(g,_r,i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModu __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.reorder=function(t,n,i,f){const c=t.filter(t=>t.section===i&&t.id!==n).map(t=>t.id),o=f?c.indexOf(f):-1;return c.splice(o<0?c.length:o,0,n),c.map((t,n)=>({id:t,sort:10*(n+1)}))},e.moveSection=function(t,n,i){const f=t.filter(t=>t!==n),c=i?f.indexOf(i):-1;return f.splice(c<0?f.length:c,0,n),f},e.moveShift=function(n,i,f,c,o,s){const u=n.find(t=>t.id===i);if(!u)return n;if(!o&&u.staffId===f&&u.date===c)return n;const l={...u,staffId:f,date:c,day:(0,t.weekdayOf)(c)};return o?[...n,{...l,id:s(),published:!1,changed:!1}]:n.map(t=>t.id===i?{...l,changed:!!u.published||u.changed}:t)};var t=r(d[0])},1582,[876]); __d(function(g,r,_i,a,m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.RotaEditor=function({today:e}){const j=(0,i.useOwner)(e=>e.staff).filter(e=>e.active),S=(0,i.useOwner)(e=>e.shifts),[k,D]=(0,t.useState)((0,i.mondayOfDate)(e)),$=(0,h.useDateCalendar)(),[v,w]=(0,t.useState)(null),[B,O]=(0,t.useState)(''),P=(0,c.useHistory)(()=>i.useOwner.getState().shifts,e=>i.useOwner.getState().setShifts(e),'rota change'),I=x.map((e,t)=>(0,i.addDays)(k,t)),T=(e,t,o)=>{e.preventDefault(),w(null);const d=(0,u.readDrag)(e);if('shift'!==d?.kind)return;const s=S.find(e=>e.id===d.id);if(!s)return;const n=!!e.altKey,c=j.find(e=>e.id===t)?.name??'';(n||s.staffId!==t||s.date!==o)&&(S.some(e=>e.staffId===t&&e.date===o&&e.id!==s.id&&e.starte.date>=k&&e.date<=I[6]),z=_.filter(e=>!e.published||e.changed).length;return(0,b.jsxs)(d.default,{style:{flex:1,gap:10},testID:"desk-rota",children:[(0,b.jsx)(f.Tip,{children:"Drag a shift to another day or person. Hold Option (Alt) while you drop to copy it instead. Nothing goes to staff until you press Publish."}),(0,b.jsxs)(s.Row,{gap:8,children:[(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"\u2039 Week before",onPress:()=>D((0,i.addDays)(k,-7))}),(0,b.jsxs)(s.T,{weight:"semibold",children:["Week of ",new Date(k+'T12:00:00').toLocaleDateString('en-GB',{day:'numeric',month:'long'})]}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Next week \u203a",onPress:()=>D((0,i.addDays)(k,7))}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",testID:"desk-rota-cal",label:"Calendar",accessibilityLabel:"Pick a date from the calendar",onPress:$.openCal}),(0,b.jsx)(h.AppDateCalendar,{visible:$.calOpen,today:e,day:k,idPrefix:"desk-rota-cal",onClose:$.closeCal,onDay:t=>D((0,i.mondayOfDate)(t??e))}),(0,b.jsx)(d.default,{style:{flex:1}}),B?(0,b.jsx)(s.T,{size:13,colour:n.colours.goldLight,children:B}):null,(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Undo",disabled:!P.canUndo,onPress:P.undo,testID:"rota-undo"}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Redo",disabled:!P.canRedo,onPress:P.redo,testID:"rota-redo"}),(0,b.jsx)(s.Button,{small:!0,label:z?`Publish (${z})`:'Published',disabled:!z,onPress:()=>{P.record('published the week');const e=i.useOwner.getState().publishWeek(k);O(`${e} shifts published.`)},testID:"rota-publish"})]}),(0,b.jsx)("div",{style:(0,f.box)({flex:1,overflow:'auto',border:`1px solid ${n.colours.border}`,borderRadius:12}),"data-testid":"rota-grid",children:(0,b.jsxs)("div",{style:(0,f.box)({display:'grid',gridTemplateColumns:"180px repeat(7, minmax(110px, 1fr))",minWidth:960}),children:[(0,b.jsx)("div",{style:(0,f.box)({position:'sticky',top:0,background:n.colours.surface,padding:8,borderBottom:`1px solid ${n.colours.border}`,zIndex:1})}),I.map((t,o)=>(0,b.jsxs)("div",{style:(0,f.box)({position:'sticky',top:0,zIndex:1,background:t===e?n.colours.goldTint:n.colours.surface,padding:8,borderBottom:`1px solid ${n.colours.border}`,fontFamily:'Poppins_600SemiBold',fontSize:13,color:t===e?n.colours.gold:n.colours.text}),children:[x[o]," ",Number(t.slice(8))]},t)),j.map(e=>(0,b.jsxs)(o.default.Fragment,{children:[(0,b.jsxs)("div",{style:(0,f.box)({padding:8,borderBottom:`1px solid ${n.colours.hairline}`,fontSize:13}),children:[(0,b.jsx)("div",{style:(0,f.box)({fontFamily:'Poppins_600SemiBold'}),children:e.name}),(0,b.jsx)("div",{style:(0,f.box)({fontSize:11,color:n.colours.muted}),children:e.job})]}),I.map(t=>{const o=`${e.id}|${t}`,d=_.filter(o=>o.staffId===e.id&&o.date===t);return(0,b.jsx)("div",{"data-testid":`rota-cell-${e.id}-${t}`,onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect=e.altKey?'copy':'move',w(o)},onDragLeave:()=>w(null),onDrop:o=>T(o,e.id,t),style:(0,f.box)({padding:5,minHeight:54,borderBottom:`1px solid ${n.colours.hairline}`,borderLeft:`1px solid ${n.colours.hairline}`,background:v===o?n.colours.accentBg:void 0,outline:v===o?`2px dashed ${n.colours.gold}`:void 0,outlineOffset:-3}),children:d.map(e=>(0,b.jsxs)("div",{draggable:!0,onDragStart:t=>(0,u.dragData)(t,'shift',e.id),"data-testid":`rota-shift-${e.id}`,title:e.note??'',style:(0,f.box)({cursor:'grab',userSelect:'none',borderRadius:8,padding:'4px 6px',marginBottom:4,fontSize:12,fontFamily:'Poppins_600SemiBold',background:e.published&&!e.changed?n.colours.gold:n.colours.goldTint,color:e.published&&!e.changed?n.colours.onGold:n.colours.goldLight,border:`1px solid ${n.colours.accentBorder}`}),children:[(0,l.fmtH)(e.start),"\u2013",(0,l.fmtH)(e.end),!e.published||e.changed?' \u2022':'']},e.id))},o)})]},e.id))]})}),(0,b.jsx)(s.Muted,{size:12,children:"Solid gold = published. Outlined with a dot = not yet published (new or changed)."})]})};var t=r(_d[0]),o=e(t),d=e(r(_d[1])),s=r(_d[2]),i=r(_d[3]),l=r(_d[4]),n=r(_d[5]),u=r(_d[6]),c=r(_d[7]),f=r(_d[8]),h=r(_d[9]),p=r(_d[10]),b=r(_d[11]);const x=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],y=()=>`sh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`},1583,[17,85,777,876,1060,804,1578,1579,1580,1051,1582,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1584,[13,17,856,1585,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1585,[1460,1586,813,912,1072,1512,1209,1210,1028,1025,1026,1513,1547,1515,1153,891,978,1587,975,880,1031,1032,1496,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1420,1066,1084,1086,1081,1027,1010,1057,1506,1501,1528,1588,1428,920,219,1246,1182,1189,1458,1202,1185,1483,1186,878,1212,1213,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1585,[1460,1586,813,912,1072,1512,1209,1210,1028,1025,1026,1513,1547,1515,1153,891,978,1587,975,880,1031,1032,1496,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1420,1066,1084,1086,1081,1027,1010,1057,1506,1501,1528,1588,1428,920,219,1246,1182,1189,1458,1202,1185,1483,1186,878,1212,1213,884,776,899,8]); __d(function(g,_r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffBookingTimes=function(){const{r:e,rid:s}=(0,o.useCtx)(),[u,c]=(0,t.useState)(()=>Object.fromEntries(d.map(([t])=>[t,e.kitchenHours?.[t]??null]))),[h,b]=(0,t.useState)(String(e.settings.turnMins??'')),[v,y]=(0,t.useState)(String(e.settings.bookingCoversPerSlot??'')),[x,j]=(0,t.useState)(''),[k,S]=(0,t.useState)(!1),f=(e,t,s)=>c(n=>({...n,[e]:0===t?[s,n[e]?.[1]??'']:[n[e]?.[0]??'',s]})),p=Object.values(u).every(e=>!e||e.every(e=>/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(e))&&e[0]=30&&Number(h)<=360&&Number(v)>=1&&Number(v)<=1e3;return(0,r.jsxs)(n.default,{style:{gap:12,width:'100%',minWidth:0},testID:"staff-booking-times",children:[(0,r.jsx)(i.T,{center:!0,weight:"bold",children:"Booking times"}),(0,r.jsx)(i.Muted,{center:!0,children:"Change kitchen hours, table time and the Covers offered in each booking slot. Table layout and blocks have their own screens."}),d.map(([e,t])=>(0,r.jsxs)(i.Card,{children:[(0,r.jsx)(i.T,{center:!0,weight:"semibold",children:t}),(0,r.jsx)(i.Toggle,{label:`${t} open`,value:!!u[e],onChange:t=>c(s=>({...s,[e]:t?['','']:null}))}),u[e]?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i.Field,{label:`${t} opens (HH:MM)`,value:u[e][0],placeholder:"HH:MM",onChangeText:t=>f(e,0,t)}),(0,r.jsx)(i.Field,{label:`${t} closes (HH:MM)`,value:u[e][1],placeholder:"HH:MM",onChangeText:t=>f(e,1,t)})]}):(0,r.jsx)(i.Muted,{center:!0,children:"Closed"})]},e)),(0,r.jsxs)(i.Card,{children:[(0,r.jsx)(i.Field,{label:"Typical table time, minutes",value:h,onChangeText:b,keyboardType:"number-pad"}),(0,r.jsx)(i.Field,{label:"Covers per 30-minute booking slot",value:v,onChangeText:y,keyboardType:"number-pad"}),e.settings.bookingCoversPerStart||e.settings.bookingPartiesPerStart?(0,r.jsx)(i.Muted,{center:!0,children:"Online booking uses the covers and bookings caps at each start time (Settings \u203a Capacity & waitlist), not this half-hour figure."}):null]}),(0,r.jsx)(i.Button,{label:k?'Saving\u2026':'Save booking times',disabled:!p||k,accessibilityLabel:"Save booking times without changing other venue settings",onPress:async()=>{S(!0);try{await(0,l.saveStaffBookingTimes)(s,u,Number(h),Number(v)),j('Booking times saved.')}catch(e){j(e.message)}finally{S(!1)}}}),x?(0,r.jsx)(i.Muted,{center:!0,children:x}):null]})};var e,t=_r(_d[0]),s=_r(_d[1]),n=(e=s)&&e.__esModule?e:{default:e},i=_r(_d[2]),o=_r(_d[3]),l=_r(_d[4]),r=_r(_d[5]);const d=[[1,'Monday'],[2,'Tuesday'],[3,'Wednesday'],[4,'Thursday'],[5,'Friday'],[6,'Saturday'],[0,'Sunday']]},1586,[17,85,777,1057,899,8]); __d(function(g,_r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.newerRelease=r,_e.startForegroundRefresh=function(n={}){if('undefined'==typeof document)return()=>{};let o='hidden'===document.visibilityState?Date.now():0,c=!1;const s=n.reload??(()=>location.reload()),u=async()=>{if(!c){c=!0;try{await Promise.race([e.mutationQueue.retryNow(),new Promise(e=>setTimeout(e,4e3))]),n.onWake?.();const t=await(navigator.serviceWorker?.getRegistration?.().catch(()=>{}));if(await(t?.update?.().catch(()=>{})),t?.waiting){try{t.waiting.postMessage({type:'SKIP_WAITING'})}catch{}return void setTimeout(s,3e3)}await r().catch(()=>!1)&&s()}finally{c=!1}}},l=()=>{if('hidden'===document.visibilityState)return void(o=Date.now());const n=o?Date.now()-o:0;o=0,e.mutationQueue.retryNow(),n>=t&&u()},f=()=>{e.mutationQueue.retryNow()};document.addEventListener('visibilitychange',l);for(const e of['focus','online','pageshow'])window.addEventListener(e,f);return()=>{document.removeEventListener('visibilitychange',l);for(const e of['focus','online','pageshow'])window.removeEventListener(e,f)}},_r(d[0]);var e=_r(d[1]);const t=3e4,n=e=>(e.match(/_expo\/static\/js\/web\/[A-Za-z0-9_.-]+\.js(\?v=[0-9a-f]+)?/)??[])[0]??null;function o(){try{const e=[...document.querySelectorAll('script[src]')].map(e=>e.src).find(e=>/_expo\/static\/js\/web\//.test(e));return e?n(e):null}catch{return null}}async function r(e=fetch){const t=o();if(!t)return!1;const r=location.pathname.replace(/[^/]*$/,''),c=await e(`${r}index.html?fresh=${Date.now()}`,{cache:'no-store'});if(!c.ok)return!1;const s=n(await c.text());return!!s&&s!==t}},1587,[219,976]); __d(function(g,_r,i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ManagerFeaturesNote=function(){return(0,j.jsxs)(a.default,{testID:"manager-features-banner",style:{borderWidth:1,borderColor:b.colours.gold,borderRadius:12,padding:10,gap:4},children:[(0,j.jsx)(d.T,{weight:"semibold",colour:b.colours.gold,children:"Manager features are on"}),(0,j.jsx)(d.Muted,{children:"Open Me \u203a Manager features for bookings, tables, blocks, allergy checks, stock, who\u2019s clocked in and shift swaps."})]})},_e.ManagerFeaturesAbout=function(){return(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"semibold",children:"What manager features include"}),c.SHIFT_MANAGER_FEATURES.map(e=>(0,j.jsxs)(d.T,{size:14,children:["\u2022 ",e]},e)),(0,j.jsxs)(d.Muted,{children:["Not included: ",c.SHIFT_MANAGER_EXCLUDED_WORDS,". Those stay in the Managers app."]})]})},_e.ClockOverview=function({today:e,now:t}){const s=(0,o.useOwner)(e=>e.staff),n=(0,o.useOwner)(e=>e.attendance).filter(t=>t.date===e&&t.in),r=e=>x(s.find(t=>t.id===e)?.name)||'Team member',h=n.filter(e=>!e.out).sort((e,t)=>(e.in??'').localeCompare(t.in??'')),c=n.filter(e=>e.out).sort((e,t)=>(e.out??'').localeCompare(t.out??'')),u=e=>(e.breaks??[]).some(e=>!e.end);return(0,j.jsxs)(a.default,{style:{gap:10},testID:"clock-overview",children:[(0,j.jsxs)(d.T,{weight:"semibold",children:["Clocked in now (",h.length,")"]}),h.length?h.map(e=>(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"medium",children:r(e.staffId)}),(0,j.jsxs)(d.Muted,{children:["In at ",(0,l.hm)(new Date(e.in)),u(e)?' \xb7 on a break':'',!1===e.inSite?' \xb7 clocked in away from the venue':'']})]},e.id)):(0,j.jsx)(d.Muted,{children:"Nobody is clocked in right now."}),(0,j.jsxs)(d.T,{weight:"semibold",children:["Finished today (",c.length,")"]}),c.length?c.map(e=>(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"medium",children:r(e.staffId)}),(0,j.jsxs)(d.Muted,{children:[(0,l.hm)(new Date(e.in))," to ",(0,l.hm)(new Date(e.out))]})]},e.id)):(0,j.jsx)(d.Muted,{children:"Nobody has clocked out yet today."}),(0,j.jsxs)(d.Muted,{children:["Read only. To change someone\u2019s clock record, ask a manager in the Managers app. Checked at ",(0,l.hm)(t),"."]})]})},_e.TablesToClear=function({rid:e}){const s=(0,r.useFloor)(t=>t.live[e])??{},n=Object.entries(s).filter(([,e])=>e?.dirty).map(([e])=>e).sort((e,t)=>e.localeCompare(t,'en',{numeric:!0}));return(0,j.jsx)(a.default,{style:{gap:8},testID:"tables-to-clear",children:n.length?n.map(s=>(0,j.jsx)(d.Card,{children:(0,j.jsxs)(d.Row,{style:{justifyContent:'space-between'},children:[(0,j.jsx)(d.T,{weight:"semibold",children:(0,t.tableNumbers)(s)}),(0,j.jsx)(d.Button,{small:!0,kind:"success",label:"Mark cleared",accessibilityLabel:`Mark table ${s} cleared, table free`,testID:`clear-${s}`,onPress:()=>{r.useFloor.getState().setLive(e,s,{dirty:!1,stage:void 0}),(0,w.notify)({id:`clear-${s}`,title:`${(0,t.tableNumbers)(s)} is free`,timeoutMs:4e3})}})]})},s)):(0,j.jsx)(d.Muted,{children:"No tables need clearing."})})},_e.SwapApprovals=function({today:e,me:t}){const n=(0,o.useOwner)(e=>e.staff),r=(0,o.useOwner)(e=>e.shifts),y=(0,o.useOwner)(e=>e.swaps),[M,k]=(0,s.useState)(null),[I,v]=(0,s.useState)(null),[T,S]=(0,s.useState)(!1),C=e=>x(n.find(t=>t.id===e)?.name)||'Team member',D=(()=>{const t=(0,l.parseYmd)(e);return t.setDate(t.getDate()+13),t})(),N=r.filter(t=>{return!1!==t.published&&t.date>=e&&(0,l.parseYmd)(t.date)<=D&&(s=t.staffId,!('owner'===n.find(e=>e.id===s)?.role));var s}).sort((e,t)=>e.date.localeCompare(t.date)||e.start-t.start),O=e=>`${(0,l.niceDate)((0,l.parseYmd)(e.date))}, ${(0,h.fmtH)(e.start)} to ${(0,h.fmtH)(e.end)}`,R=async(e,s,n,a)=>{S(!0);const d=await(0,u.approveShiftSwap)(e.id,s,n);S(!1),d.ok?(o.useOwner.setState(t=>({shifts:t.shifts.map(t=>t.id===e.id?{...t,staffId:s}:t)})),a&&o.useOwner.getState().setSwap(a,'approved'),(0,w.notify)({id:'swap-ok',title:'Shift changed',body:`${C(e.staffId)}\u2019s shift on ${O(e)} is now ${C(s)}\u2019s. Approved by ${x(t)}.`,timeoutMs:6e3}),k(null),v(null)):(0,w.notify)({id:'swap-fail',title:'Not changed',body:d.message,timeoutMs:6e3})},$=y.filter(e=>'open'===e.status);return(0,j.jsxs)(a.default,{style:{gap:10},testID:"swap-approvals",children:[(0,j.jsxs)(d.T,{weight:"semibold",children:["Requests (",$.length,")"]}),$.length?$.map(e=>{const t=r.find(t=>t.id===e.shiftId);return(0,j.jsxs)(d.Card,{children:[(0,j.jsxs)(d.T,{weight:"medium",children:[C(e.fromId)," \xb7 ",'cover'===e.kind?'needs cover':'swap']}),(0,j.jsxs)(d.Muted,{children:[t?O(t):'Shift not found',e.toId?` \xb7 to ${C(e.toId)}`:'',e.note?` \xb7 ${e.note}`:'']}),(0,j.jsxs)(d.Row,{gap:6,children:[(0,j.jsx)(d.Button,{small:!0,label:"Approve",disabled:!t||!e.toId||T||!(0,p.canSwapWith)(n.find(t=>t.id===e.fromId),n.find(t=>t.id===e.toId),f.VENUE_RID),onPress:()=>t&&e.toId&&R(t,e.toId,e.kind,e.id)}),(0,j.jsx)(d.Button,{small:!0,kind:"ghost",label:"Decline",onPress:()=>o.useOwner.getState().setSwap(e.id,'declined')})]})]},e.id)}):(0,j.jsx)(d.Muted,{children:"No open requests on this phone. Swap requests made on other phones aren\u2019t shared yet, so if someone asks you in person, use Give a shift to someone else below."}),(0,j.jsx)(d.T,{weight:"semibold",children:"Give a shift to someone else"}),M?(0,j.jsxs)(d.Card,{highlight:b.colours.gold,children:[(0,j.jsxs)(d.T,{weight:"semibold",children:[C(M.staffId)," \xb7 ",O(M)]}),(0,j.jsx)(d.Muted,{children:"Who takes it? Only someone they are allowed to swap with."}),(0,j.jsx)(d.Row,{wrap:!0,gap:6,children:(0,c.swapTargets)(n,M.staffId,f.VENUE_RID).map(e=>(0,j.jsx)(d.Chip,{label:x(e.name),selected:I===e.id,onPress:()=>v(e.id)},e.id))}),(0,j.jsxs)(d.Row,{gap:6,children:[(0,j.jsx)(d.Button,{label:"Approve",disabled:!I||T,onPress:()=>I&&R(M,I,'swap'),testID:"swap-give"}),(0,j.jsx)(d.Button,{kind:"secondary",label:"Cancel",onPress:()=>{k(null),v(null)}})]})]}):N.length?N.map(e=>(0,j.jsxs)(d.Card,{onPress:()=>{k(e),v(null)},children:[(0,j.jsx)(d.T,{weight:"medium",children:C(e.staffId)}),(0,j.jsx)(d.Muted,{children:O(e)})]},e.id)):(0,j.jsx)(d.Muted,{children:"No published shifts in the next two weeks."}),(0,j.jsx)(d.Banner,{kind:"info",children:"Approving moves the shift on the rota for everyone and records who approved it. Writing or publishing the rota stays in the Managers app."})]})};var e,t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),a=(e=n)&&e.__esModule?e:{default:e},d=_r(_d[3]),o=_r(_d[4]),r=_r(_d[5]),l=_r(_d[6]),h=_r(_d[7]),c=_r(_d[8]),u=_r(_d[9]),p=_r(_d[10]),f=_r(_d[11]),w=_r(_d[12]),b=_r(_d[13]),j=_r(_d[14]);const x=e=>(e??'').replace(' (example)','')},1588,[843,17,85,777,876,998,863,1060,1058,899,1059,805,916,804,8]); @@ -1701,7 +1701,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0});var t=r(d[0]);Object.keys(t).forEach(function(n){'default'===n||Object.prototype.hasOwnProperty.call(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})})},1618,[1619]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.preventAutoHideAsync=async function(){return!1},e.setOptions=function(n){},e.hide=function(){},e.hideAsync=async function(){}},1619,[]); __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1620,[17,24,85,409,777,857,920,899,880,805,804,1561,1563,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1621,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1621,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1622,[813,779,17,974,385,85,856,899,976,804,777,1352,971,880,1623,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.SyncDeviceActions=function(){const e=(0,o.useSync)(),[f,p]=(0,s.useState)(!1),h='live'===e.mode||'offline'===e.mode;return e.venueId&&h?(0,b.jsxs)(b.Fragment,{children:[f?(0,b.jsxs)(c.default,{style:{gap:6,marginTop:6},children:[(0,b.jsx)(u.T,{size:12,children:"Disconnect this device? Your changes stay on it; open your personal invite link to connect again."}),(0,b.jsxs)(c.default,{style:{flexDirection:'row',gap:8},children:[(0,b.jsx)(t.default,{testID:"unpair-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, disconnect",onPress:()=>{p(!1),(0,o.disconnectStaff)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:l.colours.red},children:(0,b.jsx)(u.T,{size:12,weight:"semibold",children:"Yes, disconnect"})}),(0,b.jsx)(t.default,{accessibilityRole:"button",accessibilityLabel:"Keep connected",onPress:()=>p(!1),style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,b.jsx)(u.T,{size:12,children:"Keep"})})]})]}):(0,b.jsx)(t.default,{testID:"unpair",accessibilityRole:"button",accessibilityLabel:"Disconnect this device",onPress:()=>p(!0),style:{marginTop:6,alignSelf:'flex-start'},children:(0,b.jsx)(u.T,{size:12,colour:l.colours.gold,children:"Disconnect this device\u2026"})}),(0,b.jsx)(n.WipeDevice,{compact:!0})]}):null};var s=r(d[0]),n=r(d[1]),t=e(r(d[2])),c=e(r(d[3])),o=r(d[4]),l=r(d[5]),u=r(d[6]),b=r(d[7])},1623,[17,1461,385,85,899,804,777,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1624,[]); diff --git a/owner-app/admin.html b/owner-app/admin.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/admin.html +++ b/owner-app/admin.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer.html b/owner-app/customer.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer.html +++ b/owner-app/customer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage.html b/owner-app/customer/anchorage.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage.html +++ b/owner-app/customer/anchorage.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/book.html b/owner-app/customer/anchorage/book.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/book.html +++ b/owner-app/customer/anchorage/book.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/feedback.html b/owner-app/customer/anchorage/feedback.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/feedback.html +++ b/owner-app/customer/anchorage/feedback.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/gift.html b/owner-app/customer/anchorage/gift.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/gift.html +++ b/owner-app/customer/anchorage/gift.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/lost.html b/owner-app/customer/anchorage/lost.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/lost.html +++ b/owner-app/customer/anchorage/lost.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/loyalty.html b/owner-app/customer/anchorage/loyalty.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/loyalty.html +++ b/owner-app/customer/anchorage/loyalty.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/merch.html b/owner-app/customer/anchorage/merch.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/merch.html +++ b/owner-app/customer/anchorage/merch.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/offers.html b/owner-app/customer/anchorage/offers.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/offers.html +++ b/owner-app/customer/anchorage/offers.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/refer.html b/owner-app/customer/anchorage/refer.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/refer.html +++ b/owner-app/customer/anchorage/refer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/waitlist.html b/owner-app/customer/anchorage/waitlist.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/waitlist.html +++ b/owner-app/customer/anchorage/waitlist.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/anchorage/whatson.html b/owner-app/customer/anchorage/whatson.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/anchorage/whatson.html +++ b/owner-app/customer/anchorage/whatson.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/basket.html b/owner-app/customer/basket.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/basket.html +++ b/owner-app/customer/basket.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/customer/profile.html b/owner-app/customer/profile.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/customer/profile.html +++ b/owner-app/customer/profile.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/demo.html b/owner-app/demo.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/demo.html +++ b/owner-app/demo.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/display.html b/owner-app/display.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/display.html +++ b/owner-app/display.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/index.html b/owner-app/index.html index dcb58a545a285cb97339b4a3c2dfecc501adc093..30f05c9e79f6482a881e94573b672af683b40811 100644 --- a/owner-app/index.html +++ b/owner-app/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/kitchen.html b/owner-app/kitchen.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/kitchen.html +++ b/owner-app/kitchen.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/owner.html b/owner-app/owner.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/owner.html +++ b/owner-app/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/staff.html b/owner-app/staff.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/staff.html +++ b/owner-app/staff.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-app/sw.js b/owner-app/sw.js index 282bc4602058335b8002b07a31e0108422359db3..6e827f9895b4d82b55c30f40ab797fb66bd9e9b4 100644 --- a/owner-app/sw.js +++ b/owner-app/sw.js @@ -1,7 +1,7 @@ // Anchorage Manager service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-owner-840133f7f1"; +const V = "cc-owner-ab72f096b5"; const BASE = "/owner-app/"; -const PRECACHE = ["/owner-app/apple-touch-icon.png", "/owner-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/owner-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/owner-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/owner-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/owner-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/owner-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/owner-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/owner-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/owner-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/owner-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/owner-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/owner-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/owner-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/owner-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/owner-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/owner-app/brand-logo.png", "/owner-app/favicon.ico", "/owner-app/icon-192.png", "/owner-app/icon-512.png", "/owner-app/icon-maskable-192.png", "/owner-app/icon-maskable-512.png", "/owner-app/manifest.webmanifest", "/owner-app/index.html", "/owner-app/_expo/static/js/web/bundle.js?v=840133f7f1292c61d8b09498e84f026d0b8546c38da05d97ad28fe74eda9f4d7"]; +const PRECACHE = ["/owner-app/apple-touch-icon.png", "/owner-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/owner-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/owner-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/owner-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/owner-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/owner-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/owner-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/owner-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/owner-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/owner-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/owner-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/owner-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/owner-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/owner-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/owner-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/owner-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/owner-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/owner-app/brand-logo.png", "/owner-app/favicon.ico", "/owner-app/icon-192.png", "/owner-app/icon-512.png", "/owner-app/icon-maskable-192.png", "/owner-app/icon-maskable-512.png", "/owner-app/manifest.webmanifest", "/owner-app/index.html", "/owner-app/_expo/static/js/web/bundle.js?v=ab72f096b552ed92741d17a8191b7359a4db1cc0f985fdb70e88bab79a924e2e"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/owner-app/team.html b/owner-app/team.html index 978e707d86e346a1e02c689d396e29daf1b16c6b..84f7184a54bf706efc000bfb3258d29d3a383d6f 100644 --- a/owner-app/team.html +++ b/owner-app/team.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-desktop/_expo/static/js/web/bundle.js b/owner-desktop/_expo/static/js/web/bundle.js index bd9b09fb2c80a5270673967e27fa750183a42b83..c8abc451232a9460361f0d645c7eec8860dc72e1 100644 --- a/owner-desktop/_expo/static/js/web/bundle.js +++ b/owner-desktop/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?`
    ${n.map(t=>`
  • ${p(t)}
  • `).join('')}
`:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/owner-desktop/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(_g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"CREATOR_TITLE",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"pounds",{enumerable:!0,get:function(){return v}}),Object.defineProperty(_e,"numIn",{enumerable:!0,get:function(){return C}}),_e.useOwnCosting=I,_e.DishCreator=function({rid:e,canPublish:t,initial:n="create"}){const l=I(),o=(0,d.useGpCalcView)(),[c,p]=(0,i.useState)(n),[g,h]=(0,i.useState)(()=>P(o.settings.defaultTarget));return l?(0,f.jsxs)(r.default,{style:{gap:12},testID:"dish-creator",children:[o.alerts.map(e=>(0,f.jsx)(r.default,{testID:"margin-alert",children:(0,f.jsx)(a.Banner,{kind:"danger",title:`Margin dropped: ${e.ingredient} ${e.change}`,children:(0,f.jsxs)(r.default,{style:{gap:4},children:[e.dishes.map(e=>(0,f.jsxs)(a.T,{size:14,colour:"#FFE3DF",children:[e.name,": ",(0,u.pct)(e.before)," \u2192 ",(0,u.pct)(e.after),e.belowTarget?' \xb7 below target':'']},e.id)),(0,f.jsx)(s.ToastClose,{label:"Dismiss alert",testID:`margin-alert-close-${e.id}`,onPress:()=>o.dismissAlert(e.id),size:"sm",style:{alignSelf:'flex-end'}})]})})},e.id)),(0,f.jsx)(y.Tabs,{value:c,onChange:p,options:[{id:'create',label:g.name&&o.dishes.some(e=>e.id===g.id)?'Edit dish':'Create'},{id:'saved',label:'Saved dishes & GP'},{id:'items',label:'Ingredient prices'},{id:'settings',label:'VAT & rounding'}]}),'create'===c?(0,f.jsx)(D,{draft:g,setDraft:h,onNew:()=>h(P(o.settings.defaultTarget)),onSaved:()=>p('saved')},g.id):null,'saved'===c?(0,f.jsx)(G,{rid:e,canPublish:t,onEdit:e=>{h({...e,allergens:[...e.allergens??[]]}),p('create')}}):null,'items'===c?(0,f.jsx)(V,{}):null,'settings'===c?(0,f.jsx)(W,{}):null,(0,f.jsx)(a.Muted,{children:"Costs are visible to Managers and the Head Chef only. Prices you enter, not supplier quotes."})]}):(0,f.jsx)(r.default,{testID:"dish-creator-no-access",style:{alignItems:'center',paddingVertical:16},children:(0,f.jsx)(a.Muted,{center:!0,children:"Ingredient prices and dish costs are for the Head Chef, owners and managers."})})},_e.NewIngredient=A,Object.defineProperty(_e,"TALL",{enumerable:!0,get:function(){return L}}),_e.Pick=R,_e.Items=V,_e.useCardCosting=function(e,t,s="edit"){const{ingredients:n,settings:l,cardCosts:r}=(0,d.useGpCalcView)(),a=I();return(0,i.useMemo)(()=>{if(!e||!a||!(0,p.cardCostsVisible)(t,s))return null;const i=r?.[e.id];if(!i?.lines.length)return null;const o=(0,u.cardCostSummary)(i,n,l,e.price),d={};return o.lines.forEach(e=>{e.line.recipeIngId&&(d[e.line.recipeIngId]={cost:(d[e.line.recipeIngId]?.cost??0)+e.cost,label:e.label})}),{summary:o,byRecipeIng:d}},[e,t,s,a,n,l,r])},_e.CardGpPanel=function({card:e,actor:s,mode:n="edit"}){const{ingredients:l,settings:o,cardCosts:c,saveCardCost:g}=(0,d.useGpCalcView)(),h=I()&&(0,p.cardCostsVisible)(s.role,n),y=h&&'staff'!==s.role,w=c?.[e.id]??{lines:[],portions:1},P=(0,u.cardCostSummary)(w,l,o,e.price),[$,S]=(0,i.useState)(''),[D,k]=(0,i.useState)(),[M,G]=(0,i.useState)(!1),[B,V]=(0,i.useState)(w.menuPrice?(w.menuPrice/100).toFixed(2):''),[z,W]=(0,i.useState)(!1),[F,E]=(0,i.useState)(null),[U,H]=(0,i.useState)(!w.lines.length),[q,_]=(0,i.useState)(!1),[Y,X]=(0,i.useState)(null!=w.target?String(w.target):'');if(!h)return null;const K=t=>g(e.id,{...d.useGpCalc.getState().cardCosts[e.id]??w,...t}),J=(e,t)=>{if(t){const s=(0,b.suggestAmount)(t.qty,t.unit,e);if(s.qty>0)return s}const s=e.servings?'serving':(0,u.unitsFor)(e.packUnit)[0];return{qty:'serving'===s||'each'===s?1:0,unit:s}},Q=(t,s=D)=>{const i=e.ingredients.find(e=>e.id===s),n={ingId:t.id,...J(t,i),...s?{recipeIngId:s}:{}},l=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...l.lines,n]}),S(''),k(void 0),G(!1),_(!1)},Z=(e,t)=>K({lines:w.lines.map((s,i)=>i===e?{...s,...t}:s)}),ee=new Set(w.lines.map(e=>e.recipeIngId).filter(Boolean)),te=e.ingredients.filter(e=>e.name.trim()&&!ee.has(e.id)),se=te.map(e=>({ri:e,i:(0,b.matchIngredient)(e.name,l)})).filter(e=>!!e.i),ie=P.price?P.price/(1+o.vatPct/100):null,ne=l.filter(e=>!$.trim()||$.trim().toLowerCase().split(/\s+/).some(t=>t.length>2&&e.name.toLowerCase().includes(t))||e.name.toLowerCase().includes($.trim().toLowerCase())).slice(0,12),le=v(B),re=P.tone?T[P.tone]:x.colours.muted,ae=null!=e.price&&P.price===e.price;return(0,f.jsxs)(r.default,{testID:"card-gp",accessibilityLabel:"GP calculator",style:{width:'100%',gap:10,padding:14,borderRadius:18,borderWidth:1.5,borderColor:x.colours.gold,backgroundColor:N},children:[(0,f.jsx)(a.T,{size:20,weight:"bold",center:!0,colour:x.colours.gold,accessibilityRole:"header",children:"GP calculator"}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["Costs from the price list (latest delivery prices) \xb7 target ",P.target,"% GP"]}),P.price?(0,f.jsxs)(r.default,{testID:"gp-vat-line",accessible:!0,accessibilityLabel:`Menu price ${(0,u.money)(P.price)} including VAT, ${(0,u.money)(ie)} without VAT. GP is worked out on the price without VAT.`,style:{alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,weight:"semibold",children:[(0,u.money)(P.price)," inc VAT \xb7 ",(0,u.money)(ie)," ex VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:[P.priceIsSuggested?'Suggested price':w.menuPrice?'The price you typed':'Menu price on the card'," \xb7 GP is on the ex-VAT price"]})]}):null,w.lines.length?(0,f.jsx)(r.default,{testID:"card-gp-lines",style:{gap:8},children:P.lines.map((e,s)=>{const i=l.find(t=>t.id===e.line.ingId);return(0,f.jsxs)(r.default,{testID:"card-gp-line",style:{gap:6,paddingVertical:8,borderTopWidth:s?1:0,borderColor:x.colours.accentBorder},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}, ${e.label}, ${i?`${(0,u.money)(e.cost)}, ${(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}`:'not on the price list'}`,style:{flexDirection:'row',gap:8,alignItems:'center',minHeight:32},children:[(0,f.jsxs)(r.default,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(a.T,{weight:"medium",children:e.name}),(0,f.jsx)(a.T,{size:x.font.small,colour:x.colours.muted,children:e.label}),i?(0,f.jsx)(a.T,{testID:"card-gp-line-rates",size:x.font.small,colour:x.colours.goldLight,children:(0,u.lineRatesText)((0,u.lineRates)(e.cost,w.portions||1,i))}):null]}),(0,f.jsx)(a.T,{weight:"semibold",colour:i?x.colours.goldLight:x.colours.amber,children:i?(0,u.money)(e.cost):'Removed'})]}),U&&y&&i?(()=>{const n=(0,u.unitsFor)(i.packUnit,i.servings),l=t=>(0,f.jsx)(R,{testID:`gp-unit-${s}-${t}`,label:'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2),accessibilityLabel:`${e.name} by ${'serving'===t?(0,u.servingWord)(i,2):(0,u.unitName)(t,2)}`,selected:e.line.unit===t,onPress:()=>Z(s,{unit:t})},t);return(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:`gp-qty-${s}`,accessibilityLabel:`Amount of ${e.name}`,value:e.line.qty?String(e.line.qty):'',onChangeText:e=>Z(s,{qty:C(e)??0}),placeholder:"amount",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),n.slice(0,-1).map(l),(0,f.jsxs)(r.default,{testID:`gp-unit-end-${s}`,style:{flexDirection:'row',flexWrap:'nowrap',alignItems:'center',gap:6},children:[n.slice(-1).map(l),(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})]})]})})():U&&y?(0,f.jsx)(a.Row,{gap:6,style:{justifyContent:'center'},children:(0,f.jsx)(R,{testID:`gp-remove-${s}`,label:"Remove",accessibilityLabel:`Remove ${e.name} from the costing`,onPress:()=>K({lines:w.lines.filter((e,t)=>t!==s)})})}):null]},s)})}):(0,f.jsx)(r.default,{testID:"card-gp-empty",style:{alignItems:'center',paddingVertical:6},children:(0,f.jsxs)(a.T,{center:!0,colour:x.colours.goldLight,children:["Not costed yet.",y?' Add the ingredients from your price list below.':'']})}),y&&w.lines.length?(0,f.jsx)(a.Button,{small:!0,kind:U?'primary':'secondary',testID:"gp-edit",label:U?'Done':'Change amounts or ingredients',accessibilityLabel:U?'Done changing the costing':`Change the costing for ${e.dish}`,onPress:()=>{H(!U),G(!1)}}):null,y&&U?(0,f.jsxs)(r.default,{style:{gap:8,alignItems:'center'},children:[se.length?(0,f.jsx)(a.Button,{testID:"gp-link-all",label:`Link ${se.length} matching price${1===se.length?'':'s'}`,accessibilityLabel:`Link ${se.length} of this card's ingredients to matching items on the price list`,onPress:()=>{const t=d.useGpCalc.getState().cardCosts[e.id]??w;K({lines:[...t.lines,...se.map(({ri:e,i:t})=>({ingId:t.id,...J(t,e),recipeIngId:e.id}))]}),E(`Linked ${se.length} ingredient${1===se.length?'':'s'} to the price list. Check the amounts below.`)},style:{minHeight:52}}):null,te.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Cost this card\u2019s ingredients"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:te.slice(0,10).map(e=>(0,f.jsx)(R,{testID:`gp-cost-${e.id}`,label:e.name.split(',')[0].slice(0,28),accessibilityLabel:`Cost ${e.name}`,selected:D===e.id,onPress:()=>{k(e.id),S(e.name.split(/[,(]/)[0].trim()),G(!0)}},e.id))})]}):null,M?(0,f.jsxs)(r.default,{style:{width:'100%',gap:6},children:[(0,f.jsx)(t.TextInput,{testID:"gp-search",accessibilityLabel:"Search ingredient prices",value:$,onChangeText:S,placeholder:"Search the price list",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[ne.map(e=>{const t=(0,u.perServing)(e),s=(0,u.perBaseUnit)(e),i=null!=t?`${(0,u.money)(t)} a ${(0,u.servingWord)(e,1)}`:s?`${(0,u.money)(s.pence)} a ${s.per}`:(0,u.money)(e.packPrice);return(0,f.jsx)(R,{testID:`gp-pick-${e.id}`,label:`${e.name} \xb7 ${i}`,accessibilityLabel:`Add ${e.name}, ${i}`,onPress:()=>Q(e)},e.id)}),ne.length?null:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:l.length?'Nothing on the price list matches.':'The price list is empty. Add a price here, or record a delivery.'})]}),q?(0,f.jsx)(A,{initial:$.trim(),onDone:e=>{_(!1);const t=e?d.useGpCalc.getState().ingredients.find(t=>t.id===e):void 0;t&&Q(t)}}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add-price",label:$.trim()?`Add a price for ${$.trim().slice(0,30)}`:'Add a new price',accessibilityLabel:`Add ${$.trim()||'a new ingredient'} to the price list and cost it on this card`,onPress:()=>_(!0)}),(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>{G(!1),k(void 0),S(''),_(!1)}})]}):(0,f.jsx)(a.Button,{small:!0,testID:"gp-add",kind:"secondary",label:"Add from ingredient prices",onPress:()=>{G(!0),k(void 0)}}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Target GP %"}),(0,f.jsx)(t.TextInput,{testID:"gp-target",accessibilityLabel:`Target GP percent for this dish, now ${P.target}`,value:Y,onChangeText:e=>{X(e);const t=C(e);null!=t&&t>0&&t<95?K({target:t}):e.trim()||K({target:void 0})},placeholder:String(o.defaultTarget),placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]}),(0,f.jsxs)(a.Row,{gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{testID:"gp-portions",accessibilityLabel:"Portions this recipe makes",value:String(w.portions||1),onChangeText:e=>K({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,L,{width:72,textAlign:'center'}]})]})]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost",label:"Food cost per portion",value:(0,u.money)(P.perPortion),colour:x.colours.goldLight,sub:(w.portions||1)>1?`Batch ${(0,u.money)(P.batch)} \xf7 ${w.portions}`:P.missing?`${P.missing} line${1===P.missing?'':'s'} not costed`:void 0}),(0,f.jsx)(O,{testID:"gp-suggested",label:`Suggested at ${P.target}% GP`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?"inc VAT"+(o.pricePoints?', rounded up':''):'Add amounts first'})]}),y?(0,f.jsxs)(r.default,{style:{gap:6,alignItems:'center'},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"Your menu price (inc VAT)"}),(0,f.jsxs)(a.Row,{gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{size:24,style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{testID:"gp-price",accessibilityLabel:"Your menu price in pounds, including VAT",value:B,onChangeText:e=>{const t=(0,j.sanitiseMoneyTyping)(e);V(t);const s=v(t);null!=s&&s>0?K({menuPrice:s}):t.trim()||K({menuPrice:void 0})},placeholder:P.price?(P.price/100).toFixed(2):'0.00',placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{minHeight:56,width:150,fontSize:24,textAlign:'center'}]})]}),(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:le?'GP below uses the price you typed.':e.price?`Blank uses the menu price, ${(0,u.money)(e.price)}.`:'Blank uses the suggested price.'}),P.suggested&&!le?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:"gp-use-suggested",label:`Use suggested ${(0,u.money)(P.suggested)}`,accessibilityLabel:`Use the suggested price, ${(0,u.money)(P.suggested)}`,onPress:()=>{V((P.suggested/100).toFixed(2)),K({menuPrice:P.suggested})}}):null]}):null,(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-gp",label:`GP on ${P.price?(0,u.money)(P.price):'the price'}`,value:null!=P.gp?(0,u.pct)(P.gp):'\u2014',colour:re,sub:null!=P.gp?'ok'===P.tone?'On target':'amber'===P.tone?'Just under target':'Below target':void 0}),(0,f.jsx)(O,{testID:"gp-cash",label:"Cash GP per portion",value:null!=P.cashGp?(0,u.money)(P.cashGp):'\u2014',colour:re,sub:P.price?`${(0,u.money)(P.price/(1+o.vatPct/100))} ex VAT`:void 0})]}),(()=>{const e=(0,u.foodCostTargetOf)(P.target),t=null!=P.foodCostPct?(0,u.foodCostTone)(P.foodCostPct,e):null,s=t?T[t]:x.colours.muted,i=P.price&&P.perPortion>0?(0,u.vatAwareGp)(P.perPortion,P.price,o.vatPct):null;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(O,{testID:"gp-food-cost-pct",label:"Food cost %",value:null!=P.foodCostPct?(0,u.pct)(P.foodCostPct):'\u2014',colour:s,sub:null!=P.foodCostPct?`Target ${e}% \xb7 ${'ok'===t?'on target':'amber'===t?'just over':'over target'}`:`Target ${e}%`}),(0,f.jsx)(O,{testID:"gp-suggested-target",label:`Price for ${e}% food cost`,value:P.suggested?(0,u.money)(P.suggested):'\u2014',colour:x.colours.gold,sub:P.suggested?'inc VAT':'Add amounts first'})]}),i?(0,f.jsxs)(r.default,{testID:"gp-vat-aware",accessible:!0,accessibilityLabel:`VAT ${(0,u.money)(i.vatPence)} of the ${(0,u.money)(P.price)} goes to the tax office. GP on the price without VAT is ${(0,u.pct)(i.gpPct)}. With VAT left in it would wrongly look like ${(0,u.pct)(i.naiveGpPct)}.`,style:{alignItems:'center',gap:2},children:[(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.goldLight,children:["VAT ",o.vatPct,"%: ",(0,u.money)(i.vatPence)," of each ",(0,u.money)(P.price)," is VAT"]}),(0,f.jsxs)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:["True GP ",(0,u.pct)(i.gpPct)," (ex VAT) \xb7 would look like ",(0,u.pct)(i.naiveGpPct)," with VAT left in"]})]}):null]})})(),y&&P.price&&!ae?z?(0,f.jsxs)(r.default,{testID:"gp-menu-confirm",style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Put ",(0,u.money)(P.price)," on the menu? The card goes back to Awaiting sign-off until a chef signs it again."]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"gp-menu-yes",label:`Yes, use ${(0,u.money)(P.price)}`,onPress:async()=>{if(P.price)try{await(0,m.recipeCards)().update(e.id,{price:P.price},s),E(`Menu price set to ${(0,u.money)(P.price)}. The card now waits for sign-off again.`),W(!1)}catch(e){E(e?.message??'Could not change the menu price.')}}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Not now",onPress:()=>W(!1)})]})]}):(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:"gp-menu",label:`Use ${(0,u.money)(P.price)} on the menu`,accessibilityLabel:`Use ${(0,u.money)(P.price)} as the menu price for ${e.dish}`,onPress:()=>W(!0)}):null,F?(0,f.jsx)(a.T,{center:!0,size:x.font.small,colour:x.colours.goldLight,children:F}):null,(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:"GP is worked out on the price without VAT. Only the Head Chef and managers see costs."})]})};var t=_r(_d[0]),s=_r(_d[1]),i=_r(_d[2]),n=e(_r(_d[3]));_r(_d[4]);var l=e(_r(_d[5])),r=e(_r(_d[6])),a=_r(_d[7]),o=_r(_d[8]),d=_r(_d[9]),c=_r(_d[10]),u=_r(_d[11]),p=_r(_d[12]),g=_r(_d[13]),h=_r(_d[14]),m=_r(_d[15]),x=_r(_d[16]),y=_r(_d[17]),b=_r(_d[18]),j=_r(_d[19]),f=_r(_d[20]);const w='New dish creator',T={ok:x.colours.ok,amber:x.colours.amber,red:x.colours.red},v=e=>{const t=(0,j.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):null},C=e=>{const t=e.trim().replace(',','.');return/^\d*\.?\d+$/.test(t)?Number(t):null},P=e=>({id:(0,d.gid)('gd'),name:'',lines:[],portions:1,target:e,status:'draft',allergens:[],description:''});function I(){const e=(0,h.useSession)(e=>e.meId),t=(0,g.useOwner)(t=>e?t.staff.find(t=>t.id===e):void 0);return!e||!!t&&t.active&&(0,p.costsAllowedFor)(t)}function $({n:e,title:t,children:s,testID:i}){return(0,f.jsxs)(y.Box,{testID:i,children:[(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(r.default,{style:{width:30,height:30,borderRadius:15,backgroundColor:x.colours.gold,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.onGold,children:e})}),(0,f.jsx)(a.T,{size:18,weight:"semibold",style:{flex:1},children:t})]}),s]})}function S({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n}){return(0,f.jsxs)(r.default,{testID:i,style:{flexGrow:1,flexBasis:140,padding:12,borderRadius:14,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border,gap:2},children:[(0,f.jsx)(a.Muted,{children:e}),(0,f.jsx)(a.T,{size:30,weight:"bold",colour:s,children:t}),n?(0,f.jsx)(a.Muted,{children:n}):null]})}function D({draft:e,setDraft:n,onNew:l,onSaved:o}){const{ingredients:p,dishes:g,settings:h,saveDish:m}=(0,d.useGpCalcView)(),[b,w]=(0,i.useState)(''),[P,I]=(0,i.useState)(!1),[D,L]=(0,i.useState)(''),[R,M]=(0,i.useState)(e.menuPrice?'price':'gp'),[G,B]=(0,i.useState)(e.menuPrice?(e.menuPrice/100).toFixed(2):''),[V,z]=(0,i.useState)(String(e.target)),[W,N]=(0,i.useState)(String(e.targetX??4)),O=t=>n({...e,...t}),F=g.filter(t=>t.id!==e.id),E=(0,u.portionCost)(e,p,g),U=h.vatPct,H=C(V)??e.target,q=C(W)??4,_='price'===R?v(G):E>0?'gp'===R?(0,u.suggestPrice)(E,H,U,h.pricePoints):(0,u.suggestForMultiple)(E,q,U,h.multipleBasis,h.pricePoints):null,Y=_?(0,u.gpOf)(E,_,U):null,X=_?(0,u.multipleOf)(E,_,U,h.multipleBasis):0,K=Y?(0,u.toneFor)(Y.gpPct,H):'ok',J=(0,u.suggestAllergens)(e,p,g),Q=t=>{const s=p.find(e=>e.id===t),i=t.startsWith('dish:')?'each':(0,u.unitsFor)(s.packUnit,s.servings)[0],l=[...e.lines,{ingId:t,qty:t.startsWith('dish:')?1:0,unit:i}],r={...e,lines:l},a=(0,u.suggestAllergens)(r,p,g);n({...r,allergens:Array.from(new Set([...e.allergens??[],...a]))})},Z=(t,s)=>O({lines:e.lines.map((e,i)=>i===t?{...e,...s}:e)}),ee=p.filter(e=>!b.trim()||e.name.toLowerCase().includes(b.trim().toLowerCase())),te=t=>{if(!e.name.trim())return L('Give the dish a name first.');if('ready'===t){if(!e.category)return L('Pick a category to make it menu-ready.');if(!e.lines.length||E<=0)return L('Add ingredients with quantities to make it menu-ready.');if(!_)return L('Set a price to make it menu-ready.')}const s='published'===e.status?'published':t;m({...e,name:e.name.trim(),target:H,targetX:q,menuPrice:_??void 0,status:s}),L('ready'===t?`Saved \u201c${e.name.trim()}\u201d as menu-ready. A manager can publish it to the menu.`:`Saved \u201c${e.name.trim()}\u201d as a draft.`)};return(0,f.jsxs)(r.default,{style:{gap:12},children:[(0,f.jsxs)($,{n:1,title:"Name and category",testID:"step-name",children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:"Dish name",value:e.name,onChangeText:e=>O({name:e.slice(0,60)}),placeholder:"e.g. Cullen skink",placeholderTextColor:"#7D776C",style:[a.styles.input,{fontSize:20}]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:u.DISH_CATEGORIES.map(t=>(0,f.jsx)(a.Chip,{label:t,selected:e.category===t,onPress:()=>O({category:t})},t))})]}),(0,f.jsxs)($,{n:2,title:"Add saved items and ingredients",testID:"step-ingredients",children:[F.length?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(a.Muted,{children:"Saved items (tap to add a portion)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:F.map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(`dish:${e.id}`)},e.id))})]}):null,(0,f.jsx)(a.Muted,{children:"Ingredients"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredients",value:b,onChangeText:w,placeholder:"Search ingredients",placeholderTextColor:"#7D776C",style:a.styles.input}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[ee.slice(0,24).map(e=>(0,f.jsx)(a.Chip,{label:`${e.name}`,onPress:()=>Q(e.id)},e.id)),(0,f.jsx)(a.Chip,{label:"New ingredient",onPress:()=>I(!0)})]}),P?(0,f.jsx)(A,{initial:b,onDone:e=>{I(!1),w(''),e&&Q(e)}}):null,e.lines.length?(0,f.jsx)(r.default,{style:{gap:8},testID:"dish-lines",children:e.lines.map((i,n)=>{const l=i.ingId.startsWith('dish:'),o=p.find(e=>e.id===i.ingId),d=(c=i.ingId).startsWith('dish:')?g.find(e=>e.id===c.slice(5))?.name??'Saved item':p.find(e=>e.id===c)?.name??'?';var c;return(0,f.jsxs)(r.default,{testID:"dish-line",style:{gap:6,padding:10,borderRadius:12,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:x.colours.border},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between'},children:[(0,f.jsxs)(a.T,{weight:"medium",style:{flex:1},children:[d,l?' (saved item)':'']}),(0,f.jsx)(a.T,{weight:"semibold",children:(0,u.money)((0,u.lineCost)(i,p,g))}),(0,f.jsx)(s.GoldClose,{size:"sm",label:`Remove ${d}`,onPress:()=>O({lines:e.lines.filter((e,t)=>t!==n)})})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Quantity of ${d}`,value:i.qty?String(i.qty):'',onChangeText:e=>Z(n,{qty:C(e)??0}),placeholder:"qty",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:90}]}),l?(0,f.jsx)(a.Muted,{children:"portion(s)"}):(0,u.unitsFor)(o.packUnit,o.servings).map(e=>(0,f.jsx)(a.Chip,{label:'serving'===e?(0,u.servingWord)(o,2):(0,u.unitName)(e,2),selected:i.unit===e,onPress:()=>Z(n,{unit:e})},e)),l?null:(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${d}`,value:null==i.wastePct?'':String(i.wastePct),onChangeText:e=>Z(n,{wastePct:''===e.trim()?void 0:C(e)??0}),placeholder:`waste ${o.wastePct}%`,placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,{width:110}]})]})]},n)})}):(0,f.jsx)(a.Muted,{children:"Nothing added yet. Tap a saved item or an ingredient above."}),(0,f.jsxs)(a.Row,{gap:10,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Portions this makes"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Portions per batch",value:String(e.portions),onChangeText:e=>O({portions:Math.max(1,Math.round(C(e)??1))}),keyboardType:"number-pad",style:[a.styles.input,{width:80,textAlign:'center'}]})]}),(0,f.jsx)(S,{testID:"cost-per-plate",label:"Cost per plate",value:(0,u.money)(E),sub:e.portions>1?`Batch cost ${(0,u.money)(E*e.portions)} \xf7 ${e.portions}`:'Live: updates as you type'})]}),(0,f.jsxs)($,{n:3,title:"Price it",testID:"step-price",children:[(0,f.jsx)(y.Tabs,{value:R,onChange:M,options:[{id:'gp',label:'Target GP %'},{id:'x',label:'Target multiple'},{id:'price',label:'Type a price'}]}),'gp'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[65,70,75].map(e=>(0,f.jsx)(a.Chip,{label:`${e}%`,selected:H===e,onPress:()=>z(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target GP %",value:V,onChangeText:z,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'x'===R?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[[3,4,5].map(e=>(0,f.jsx)(a.Chip,{label:`${e}x`,selected:q===e,onPress:()=>N(String(e))},e)),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Target multiple",value:W,onChangeText:N,keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}):null,'price'===R?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{size:24,children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Menu price (inc VAT)",value:G,onChangeText:e=>B((0,j.sanitiseMoneyTyping)(e)),placeholder:"0.00",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,{width:140,fontSize:24}]}),(0,f.jsx)(a.Muted,{children:"inc VAT"})]}):null,'price'!==R?(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"suggested-price",label:`Suggested menu price (inc ${U}% VAT)`,value:_?(0,u.money)(_):'\u2014',colour:x.colours.gold,sub:_?`${(0,u.money)(_/(1+U/100))} ex VAT${h.pricePoints?' \xb7 rounded up to .50 / .95':''}`:'Add ingredients first'}),_?(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Type my own price",onPress:()=>{B((_/100).toFixed(2)),M('price')}}):null]}):null,(()=>{const t=(0,u.avgMenuPrice)(g,e.category,e.id);return e.category?(0,f.jsx)(r.default,{testID:"avg-menu-price",children:(0,f.jsx)(a.Muted,{children:t?`Average menu price for ${e.category}: ${(0,u.money)(t.avg)} (${t.count} dish${1===t.count?'':'es'})${_?` \xb7 this dish ${_>=t.avg?'+':'\u2212'}${(0,u.money)(Math.abs(_-t.avg))}`:''}`:`No other priced ${e.category.toLowerCase()} yet to compare with.`})}):null})(),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(S,{testID:"big-gp",label:`GP (target ${H}%)`,value:Y?(0,u.pct)(Y.gpPct):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-x",label:`Multiple (${'inc'===h.multipleBasis?'inc VAT price':'ex VAT price'} \xf7 cost)`,value:Y&&E>0?(0,u.fmtX)(X):'\u2014',colour:x.colours.gold}),(0,f.jsx)(S,{testID:"big-profit",label:"Profit per plate (cash GP)",value:Y?(0,u.money)(Y.cashGp):'\u2014',colour:Y?T[K]:x.colours.muted}),(0,f.jsx)(S,{testID:"big-foodcost",label:"Food cost",value:Y?(0,u.pct)(Y.foodCostPct):'\u2014'})]}),(0,f.jsxs)(a.Muted,{children:["GP is worked out on the price without VAT (",U,"% VAT). Gold: at or above target \xb7 amber: up to 5 points under \xb7 red: more than 5 under."]})]}),(0,f.jsxs)($,{n:4,title:"Photo, allergens and description",testID:"step-details",children:[(0,f.jsx)(k,{value:e.photo,onChange:e=>O({photo:e})}),(0,f.jsx)(a.T,{weight:"medium",children:"Allergens (14 UK allergens)"}),J.length?(0,f.jsx)(r.default,{testID:"allergen-suggest",children:(0,f.jsxs)(a.Muted,{children:["Suggested from the ingredients: ",J.map(e=>c.ALLERGENS.find(t=>t.id===e).short).join(', '),". Check before it goes on the menu."]})}):(0,f.jsx)(a.Muted,{children:"No allergens known from these ingredients yet. Tick any that apply."}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,children:c.ALLERGENS.map(t=>{const s=(e.allergens??[]).includes(t.id);return(0,f.jsx)(a.Chip,{label:`${s?'\u2713 ':''}${t.short}`,sub:J.includes(t.id)?'suggested':void 0,selected:s,onPress:()=>O({allergens:s?e.allergens.filter(e=>e!==t.id):[...e.allergens??[],t.id]})},t.id)})}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Short description",value:e.description??'',onChangeText:e=>O({description:e.slice(0,160)}),multiline:!0,placeholder:"Short description for the menu (up to 160 characters)",placeholderTextColor:"#7D776C",style:[a.styles.input,{minHeight:70,textAlignVertical:'top'}]}),(0,f.jsxs)(a.Muted,{children:[(e.description??'').length,"/160"]})]}),(0,f.jsxs)($,{n:5,title:"Save",testID:"step-save",children:[(0,f.jsxs)(a.Row,{wrap:!0,gap:8,children:[(0,f.jsx)(a.Button,{label:"Save as draft",kind:"secondary",testID:"save-draft",onPress:()=>te('draft'),style:{flexGrow:1}}),(0,f.jsx)(a.Button,{label:"Save as menu-ready dish",testID:"save-ready",onPress:()=>te('ready'),style:{flexGrow:1}})]}),D?(0,f.jsx)(r.default,{testID:"creator-msg",children:(0,f.jsx)(a.T,{size:15,colour:D.startsWith('Saved')?x.colours.ok:x.colours.amber,children:D})}):null,D.startsWith('Saved')?(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.Button,{small:!0,label:"See saved dishes",onPress:o}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Start a new dish",onPress:()=>{l(),L(''),B(''),M('gp')}})]}):null]})]})}function k({value:e,onChange:t}){return(0,f.jsxs)(a.Row,{gap:10,children:[e?(0,f.jsx)(n.default,{testID:"dish-photo",source:{uri:e},style:{width:96,height:72,borderRadius:10}}):(0,f.jsx)(r.default,{style:{width:96,height:72,borderRadius:10,borderWidth:1,borderStyle:'dashed',borderColor:x.colours.border,alignItems:'center',justifyContent:'center'},children:(0,f.jsx)(a.Muted,{children:"No photo"})}),(0,f.jsxs)(r.default,{style:{gap:6},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:e?'Change photo':'Add photo (optional)',onPress:()=>{if('undefined'==typeof document)return;const e=document.createElement('input');e.type='file',e.accept='image/*',e.onchange=()=>{const s=e.files?.[0];if(!s)return;const i=new FileReader;i.onload=()=>{const e=new window.Image;e.onload=()=>{const s=Math.min(1,480/Math.max(e.width,e.height)),i=document.createElement('canvas');i.width=Math.round(e.width*s),i.height=Math.round(e.height*s),i.getContext('2d').drawImage(e,0,0,i.width,i.height),t(i.toDataURL('image/jpeg',.8))},e.src=String(i.result)},i.readAsDataURL(s)},e.click()}}),e?(0,f.jsx)(a.Button,{small:!0,kind:"ghost",label:"Remove photo",onPress:()=>t(void 0)}):null]})]})}function A({initial:e,onDone:s,edit:n}){const[l,o]=(0,i.useState)(n?.name??e),[p,g]=(0,i.useState)(n?String(n.packSize):''),[h,m]=(0,i.useState)(n?.packUnit??'kg'),[y,b]=(0,i.useState)(n?(n.packPrice/100).toFixed(2):''),[w,T]=(0,i.useState)(n?.wastePct?String(n.wastePct):''),[P,I]=(0,i.useState)(n?.allergens??[]),[$,S]=(0,i.useState)(n?.servings?String(n.servings):''),[D,k]=(0,i.useState)(n?.servingName??''),[A,M]=(0,i.useState)(n?.supplier??''),G=!(!l.trim()||!C(p)||null==v(y)||''!==$.trim()&&!C($)),B={id:'probe',name:l,packSize:C(p)??0,packUnit:h,packPrice:v(y)??0,wastePct:0,servings:C($)??void 0,servingName:D.trim()||void 0},V=B.packSize&&B.packPrice?(0,u.perBaseUnit)(B):null,z=B.packPrice?(0,u.perServing)(B):null,W={name:l.trim(),packSize:C(p),packUnit:h,packPrice:v(y),wastePct:Math.min(90,C(w)??0),allergens:P,servings:C($)??void 0,servingName:D.trim().toLowerCase()||void 0,supplier:A.trim()||void 0};return(0,f.jsxs)(r.default,{testID:n?`edit-ingredient-${n.id}`:'new-ingredient',style:{gap:8,padding:12,borderRadius:14,borderWidth:1,borderColor:x.colours.gold,width:'100%'},children:[(0,f.jsx)(a.T,{weight:"semibold",center:!0,accessibilityRole:"header",children:n?`Edit ${n.name}`:'New ingredient'}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Ingredient name",value:l,onChangeText:o,placeholder:"e.g. Haddock",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Pack price and what you get for it, e.g. \xa3110 for 1 stone, or \xa340 for 5 kg"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{testID:"ing-pack-price",accessibilityLabel:"Pack price in pounds",value:y,onChangeText:e=>b((0,j.sanitiseMoneyTyping)(e)),placeholder:"\xa3 price",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110,textAlign:'center'}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"for"}),(0,f.jsx)(t.TextInput,{testID:"ing-pack-size",accessibilityLabel:"Pack size",value:p,onChangeText:g,placeholder:"size",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]})]}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:u.PACK_UNITS.map(e=>(0,f.jsx)(R,{testID:`ing-unit-${e}`,label:(0,u.unitName)(e,2),selected:h===e,onPress:()=>m(e)},e))}),(0,f.jsx)(a.Muted,{center:!0,children:"Optional: roughly how many servings or pieces one pack gives"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"averages"}),(0,f.jsx)(t.TextInput,{testID:"ing-servings",accessibilityLabel:"Averages how many servings or pieces",value:$,onChangeText:S,placeholder:"e.g. 30",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L,{width:90,textAlign:'center'}]}),(0,f.jsx)(t.TextInput,{testID:"ing-serving-name",accessibilityLabel:"What one is called, for example serving, breast or piece",value:D,onChangeText:k,placeholder:"serving / breast",placeholderTextColor:"#7D776C",style:[a.styles.input,L,{width:150,textAlign:'center'}]})]}),V||null!=z?(0,f.jsx)(r.default,{testID:"ing-derived",accessible:!0,accessibilityLabel:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(', '),children:(0,f.jsx)(a.T,{center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=z?`${(0,u.money)(z)} a ${(0,u.servingWord)(B,1)}`:'',V?`${(0,u.money)(V.pence)} a ${V.per}`:''].filter(Boolean).join(' \xb7 ')})}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Supplier (optional)",value:A,onChangeText:M,placeholder:"Supplier (optional)",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Yield loss or waste percent (optional)",value:w,onChangeText:T,placeholder:"Trim / waste % (optional, for weights)",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",style:[a.styles.input,L]}),(0,f.jsx)(a.Muted,{center:!0,children:"Allergens in this ingredient (if known)"}),(0,f.jsx)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:c.ALLERGENS.map(e=>(0,f.jsx)(a.Chip,{label:e.short,selected:P.includes(e.id),onPress:()=>I(P.includes(e.id)?P.filter(t=>t!==e.id):[...P,e.id])},e.id))}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,testID:"ing-save",label:n?'Save ingredient':'Add ingredient',disabled:!G,onPress:()=>{if(n){const e=d.useGpCalc.getState();W.packPrice!==n.packPrice&&e.addPricePaid(n.id,W.packPrice);const t=d.useGpCalc.getState().ingredients.find(e=>e.id===n.id)??n;e.saveIngredient({...t,...W,packPrice:t.packPrice}),s(n.id)}else s(d.useGpCalc.getState().addIngredient(W))}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Cancel",onPress:()=>s()})]})]})}const L={minHeight:48};function R({label:e,selected:t,onPress:s,testID:i,accessibilityLabel:n}){return(0,f.jsx)(l.default,{testID:i,accessibilityRole:"button",accessibilityState:{selected:!!t},accessibilityLabel:`${n??e}${t?', selected':''}`,onPress:s,style:{minHeight:48,minWidth:48,paddingHorizontal:14,justifyContent:'center',alignItems:'center',borderRadius:24,borderWidth:1,borderColor:t?x.colours.gold:x.colours.border,backgroundColor:t?x.colours.gold:x.colours.surface2,maxWidth:'100%'},children:(0,f.jsx)(a.T,{size:x.font.small,weight:"medium",center:!0,colour:t?x.colours.onGold:x.colours.text,children:e})})}const M={draft:{label:'Draft',kind:'neutral'},ready:{label:'Menu-ready',kind:'gold'},published:{label:'On the menu',kind:'ok'}};function G({rid:e,canPublish:t,onEdit:s}){const{dishes:n,ingredients:l,settings:c,saveDish:p}=(0,d.useGpCalcView)(),[g,h]=(0,i.useState)('low'),[m,b]=(0,i.useState)(''),j=(0,i.useMemo)(()=>n.map(e=>{const t=(0,u.portionCost)(e,l,n);return{d:e,cost:t,g:e.menuPrice?(0,u.gpOf)(t,e.menuPrice,c.vatPct):null,x:e.menuPrice?(0,u.multipleOf)(t,e.menuPrice,c.vatPct,c.multipleBasis):0}}).sort((e,t)=>(e.g?e.g.gpPct:999)-(t.g?t.g.gpPct:999)),[n,l,c]),w='low'===g?j:[...j].reverse(),v=j.filter(e=>e.g&&e.g.gpPct{const s={};(t.allergens??[]).forEach(e=>{s[e]='contains'});const i=o.useStore.getState().addMenuItem({restaurantId:e,section:t.category??'Specials',name:t.name,description:t.description??'',price:t.menuPrice??null,dietary:[],allergens:s,prepMins:12,soldOut:!1,signOff:null});p({...t,status:'published',menuItemId:i}),b(`Published \u201c${t.name}\u201d to the menu (${t.category??'Specials'}). It needs allergen sign-off in Menu & allergens.`)};return(0,f.jsxs)(y.Box,{testID:"menu-gp",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"Saved dishes and items \xb7 Menu GP"}),(0,f.jsxs)(a.Muted,{children:[j.length," saved \xb7 ",v," below target \xb7 multiples on the ",'inc'===c.multipleBasis?'inc-VAT menu price':'ex-VAT price']}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Lowest GP first",selected:'low'===g,onPress:()=>h('low')}),(0,f.jsx)(a.Chip,{label:"Highest GP first",selected:'high'===g,onPress:()=>h('high')})]}),w.map(({d:e,cost:i,g:n,x:l})=>{const o=n?(0,u.toneFor)(n.gpPct,e.target):null;return(0,f.jsxs)(r.default,{testID:"gp-row",style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:4},children:[(0,f.jsxs)(a.Row,{style:{justifyContent:'space-between',alignItems:'flex-start'},children:[(0,f.jsxs)(r.default,{style:{flex:1,gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",children:e.name}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Badge,{kind:M[e.status??'draft'].kind,label:M[e.status??'draft'].label}),e.category?(0,f.jsx)(a.Muted,{children:e.category}):null]}),(0,f.jsxs)(a.Muted,{children:["Cost ",(0,u.money)(i),e.menuPrice?` \xb7 price ${(0,u.money)(e.menuPrice)}`:' \xb7 no price yet']})]}),(0,f.jsxs)(r.default,{style:{alignItems:'flex-end'},children:[(0,f.jsx)(a.T,{size:22,weight:"bold",colour:o?T[o]:x.colours.muted,children:n?(0,u.pct)(n.gpPct):'\u2014'}),(0,f.jsx)(a.T,{size:16,weight:"semibold",colour:x.colours.gold,children:n&&i>0?(0,u.fmtX)(l):''})]})]}),n&&n.gpPcts(e)}),t&&'ready'===e.status?(0,f.jsx)(a.Button,{small:!0,label:"Publish to menu",accessibilityLabel:`Publish ${e.name} to menu`,onPress:()=>C(e)}):null,t||'ready'!==e.status?null:(0,f.jsx)(a.Muted,{children:"Waiting for a manager to publish"})]})]},e.id)}),m?(0,f.jsx)(r.default,{testID:"publish-msg",children:(0,f.jsx)(a.T,{size:14,colour:x.colours.ok,children:m})}):null]})}function B(){const{settings:e,setSettings:t}=(0,d.useGpCalcView)(),s=e.priceBasis??'latest',i=e.avgOf??5;return(0,f.jsxs)(r.default,{testID:"price-basis",style:{gap:6},children:[(0,f.jsx)(a.T,{weight:"medium",children:"Cost dishes using"}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Chip,{label:"Latest price paid",selected:'latest'===s,onPress:()=>t({priceBasis:'latest'})}),(0,f.jsx)(a.Chip,{label:`Average price (last ${i})`,selected:'average'===s,onPress:()=>t({priceBasis:'average'})})]}),'average'===s?(0,f.jsxs)(a.Row,{wrap:!0,gap:6,children:[(0,f.jsx)(a.Muted,{children:"Average of the last"}),[3,5,10].map(e=>(0,f.jsx)(a.Chip,{label:`${e} prices`,selected:i===e,onPress:()=>t({avgOf:e})},e))]}):null,(0,f.jsx)(a.Muted,{children:'average'===s?'Averages smooth out price swings, so GP doesn\u2019t jump every delivery.':'Uses the most recent price you paid.'})]})}function V(){const{ingredients:e,dishes:s,settings:n,cardCosts:l}=(0,d.useGpCalcView)(),[o,c]=(0,i.useState)(''),[u,p]=(0,i.useState)(''),[g,h]=(0,i.useState)(!1),m=e.filter(e=>!u.trim()||`${e.name} ${e.supplier??''}`.toLowerCase().includes(u.trim().toLowerCase())).slice().sort((e,t)=>e.name.localeCompare(t.name));return(0,f.jsxs)(y.Box,{testID:"calc-items",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",center:!0,accessibilityRole:"header",children:"Ingredient prices"}),(0,f.jsx)(a.Muted,{center:!0,children:"What you pay and what a pack gives you. Recipe cards and dishes cost themselves from this list and update when a price changes."}),(0,f.jsx)(a.Button,{testID:"ing-add-new",label:"Add an ingredient",onPress:()=>{h(!0),c('')}}),g?(0,f.jsx)(A,{initial:u,onDone:e=>{h(!1),e&&c('Added to the price list.')}}):null,(0,f.jsx)(t.TextInput,{accessibilityLabel:"Search ingredient prices",value:u,onChangeText:p,placeholder:"Search ingredients or suppliers",placeholderTextColor:"#7D776C",style:[a.styles.input,L]}),(0,f.jsx)(B,{}),m.map(e=>{return(0,f.jsx)(z,{i:e,n:n.avgOf??5,basis:n.priceBasis??'latest',used:(t=e.id,s.filter(e=>e.lines.some(e=>e.ingId===t)).length+Object.values(l??{}).filter(e=>e.lines.some(e=>e.ingId===t)).length),onSaved:e=>c(e)},e.id);var t}),m.length?null:(0,f.jsx)(r.default,{testID:"ing-empty",style:{alignItems:'center',paddingVertical:12},children:(0,f.jsx)(a.T,{center:!0,colour:x.colours.muted,children:e.length?'No ingredients match.':'No ingredient prices yet. Add the first one above.'})}),o?(0,f.jsx)(r.default,{testID:"items-msg",children:(0,f.jsx)(a.T,{size:14,center:!0,colour:x.colours.ok,children:o})}):null]})}function z({i:e,used:s,n:n,basis:l,onSaved:o}){const[c,p]=(0,i.useState)(String(e.wastePct)),[g,h]=(0,i.useState)(''),[m,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(!1),T=(0,u.priceStats)(e,n),P=c!==String(e.wastePct),I=v(g),$=(0,u.perBaseUnit)(e),S=(0,u.perServing)(e),D=`${e.name}, ${(0,u.money)(e.packPrice)} for ${e.packSize} ${(0,u.unitName)(e.packUnit,e.packSize)}${e.servings?`, averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}, ${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:''}${$?`, ${(0,u.money)($.pence)} a ${$.per}`:''}${e.supplier?`, from ${e.supplier}`:''}`;return m?(0,f.jsx)(A,{initial:"",edit:e,onDone:t=>{y(!1),t&&o(`Saved ${e.name}. Recipe cards and dishes re-costed.`)}}):(0,f.jsxs)(r.default,{testID:`item-${e.id}`,style:{paddingVertical:10,borderTopWidth:1,borderColor:x.colours.border,gap:6},children:[(0,f.jsxs)(r.default,{accessible:!0,accessibilityLabel:D,style:{gap:2},children:[(0,f.jsx)(a.T,{weight:"semibold",size:18,center:!0,children:e.name}),(0,f.jsxs)(a.T,{testID:`pack-${e.id}`,center:!0,colour:x.colours.goldLight,children:[(0,u.money)(e.packPrice)," for ",e.packSize," ",(0,u.unitName)(e.packUnit,e.packSize),e.servings?` \xb7 averages ${e.servings} ${(0,u.servingWord)(e,e.servings)}`:'']}),(0,f.jsx)(a.T,{testID:`derived-${e.id}`,center:!0,weight:"semibold",colour:x.colours.gold,children:[null!=S?`${(0,u.money)(S)} a ${(0,u.servingWord)(e,1)}`:'',$?`${(0,u.money)($.pence)} a ${$.per}`:''].filter(Boolean).join(' \xb7 ')}),(0,f.jsx)(a.Muted,{center:!0,children:[s?`used in ${s}`:'not used yet',e.supplier,e.updatedAt?`updated ${new Date(e.updatedAt).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:''].filter(Boolean).join(' \xb7 ')})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsxs)(r.default,{testID:`latest-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'latest'===l?x.colours.gold:x.colours.border},children:[(0,f.jsx)(a.Muted,{children:"Latest"}),(0,f.jsx)(a.T,{weight:"bold",children:(0,u.money)(T.latest)})]}),(0,f.jsxs)(r.default,{testID:`avg-${e.id}`,style:{paddingHorizontal:10,paddingVertical:6,borderRadius:10,backgroundColor:x.colours.surface2,borderWidth:1,borderColor:'average'===l?x.colours.gold:x.colours.border},children:[(0,f.jsxs)(a.Muted,{children:["Average (",T.count,")"]}),(0,f.jsx)(a.T,{weight:"bold",colour:x.colours.gold,children:(0,u.money)(T.avg)})]}),T.count>1?(0,f.jsxs)(r.default,{style:{paddingHorizontal:10,paddingVertical:6},children:[(0,f.jsx)(a.Muted,{children:"Range"}),(0,f.jsxs)(a.T,{size:14,children:[(0,u.money)(T.min),"\u2013",(0,u.money)(T.max)]})]}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"\xa3"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:`Price paid for ${e.name}`,value:g,onChangeText:e=>h((0,j.sanitiseMoneyTyping)(e)),placeholder:"price paid",placeholderTextColor:"#7D776C",keyboardType:"decimal-pad",inputMode:"decimal",style:[a.styles.input,L,{width:110}]}),(0,f.jsx)(a.Button,{small:!0,label:"Add price paid",testID:`add-price-${e.id}`,disabled:!I,onPress:()=>{d.useGpCalc.getState().addPricePaid(e.id,I),h(''),o(`Recorded ${(0,u.money)(I)} for ${e.name}. Dishes re-costed.`)}})]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,f.jsx)(t.TextInput,{accessibilityLabel:`Waste % for ${e.name}`,value:c,onChangeText:p,keyboardType:"decimal-pad",style:[a.styles.input,L,{width:60}]}),(0,f.jsx)(a.T,{style:{alignSelf:'center'},children:"% waste"}),P?(0,f.jsx)(a.Button,{small:!0,label:"Save",disabled:null==C(c),onPress:()=>{d.useGpCalc.getState().saveIngredient({...e,wastePct:Math.min(90,C(c))}),o(`Saved ${e.name}. Dishes updated.`)}}):null]}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"secondary",testID:`ing-edit-${e.id}`,label:"Edit",accessibilityLabel:`Edit ${e.name}`,onPress:()=>y(!0)}),b?null:(0,f.jsx)(a.Button,{small:!0,kind:"ghost",testID:`ing-delete-${e.id}`,label:"Delete",accessibilityLabel:`Delete ${e.name}`,onPress:()=>w(!0)})]}),b?(0,f.jsxs)(r.default,{testID:`ing-delete-confirm-${e.id}`,style:{gap:6,alignItems:'center'},children:[(0,f.jsxs)(a.T,{center:!0,colour:x.colours.amber,children:["Delete ",e.name," from the price list?",s?` ${s} ${1===s?'dish or card uses':'dishes or cards use'} it and will show it as removed.`:'']}),(0,f.jsxs)(a.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[(0,f.jsx)(a.Button,{small:!0,kind:"danger",testID:`ing-delete-yes-${e.id}`,label:"Yes, delete",accessibilityLabel:`Yes, delete ${e.name}`,onPress:()=>{d.useGpCalc.getState().removeIngredient(e.id),o(`Deleted ${e.name}.`)}}),(0,f.jsx)(a.Button,{small:!0,kind:"secondary",label:"Keep it",onPress:()=>w(!1)})]})]}):null]})}function W(){const{settings:e,setSettings:s}=(0,d.useGpCalcView)(),[n,l]=(0,i.useState)(String(e.vatPct)),[r,o]=(0,i.useState)(String(e.defaultTarget));return(0,f.jsxs)(y.Box,{testID:"calc-settings",children:[(0,f.jsx)(a.T,{size:18,weight:"semibold",children:"VAT and rounding"}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"VAT rate %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"VAT rate %",value:n,onChangeText:e=>{l(e);const t=C(e);null!=t&&t<=50&&s({vatPct:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(B,{}),(0,f.jsx)(a.Toggle,{label:"Round suggested prices up to .50 / .95",value:e.pricePoints,onChange:e=>s({pricePoints:e})}),(0,f.jsxs)(a.Row,{gap:8,children:[(0,f.jsx)(a.T,{style:{flex:1},children:"Default target GP %"}),(0,f.jsx)(t.TextInput,{accessibilityLabel:"Default target GP %",value:r,onChangeText:e=>{o(e);const t=C(e);null!=t&&t<95&&s({defaultTarget:t})},keyboardType:"decimal-pad",style:[a.styles.input,{width:80}]})]}),(0,f.jsx)(a.T,{weight:"medium",children:"Cost multiple (x) is based on"}),(0,f.jsxs)(a.Row,{gap:6,children:[(0,f.jsx)(a.Chip,{label:"Inc VAT (menu price)",selected:'inc'===e.multipleBasis,onPress:()=>s({multipleBasis:'inc'})}),(0,f.jsx)(a.Chip,{label:"Ex VAT",selected:'ex'===e.multipleBasis,onPress:()=>s({multipleBasis:'ex'})})]}),(0,f.jsx)(a.Muted,{children:"GP % uses the ex-VAT price. The price multiple is the menu price divided by ingredient cost."})]})}const N='#3A2F1E';function O({label:e,value:t,colour:s=x.colours.text,testID:i,sub:n,said:l}){return(0,f.jsxs)(r.default,{testID:i,accessible:!0,accessibilityLabel:l??`${e}, ${t}${n?`, ${n}`:''}`,style:{flexGrow:1,flexBasis:128,minWidth:0,padding:10,borderRadius:14,backgroundColor:x.colours.surface,borderWidth:1,borderColor:x.colours.accentBorder,alignItems:'center',gap:2},children:[(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:e}),(0,f.jsx)(a.T,{size:28,weight:"bold",center:!0,colour:s,children:t}),n?(0,f.jsx)(a.T,{size:x.font.small,center:!0,colour:x.colours.muted,children:n}):null]})}},1157,[812,779,17,319,219,385,85,777,816,905,845,906,909,876,920,867,804,889,907,840,8]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1665,7 +1665,7 @@ __d(function(g,_r,i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModu __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.reorder=function(t,n,i,f){const c=t.filter(t=>t.section===i&&t.id!==n).map(t=>t.id),o=f?c.indexOf(f):-1;return c.splice(o<0?c.length:o,0,n),c.map((t,n)=>({id:t,sort:10*(n+1)}))},e.moveSection=function(t,n,i){const f=t.filter(t=>t!==n),c=i?f.indexOf(i):-1;return f.splice(c<0?f.length:c,0,n),f},e.moveShift=function(n,i,f,c,o,s){const u=n.find(t=>t.id===i);if(!u)return n;if(!o&&u.staffId===f&&u.date===c)return n;const l={...u,staffId:f,date:c,day:(0,t.weekdayOf)(c)};return o?[...n,{...l,id:s(),published:!1,changed:!1}]:n.map(t=>t.id===i?{...l,changed:!!u.published||u.changed}:t)};var t=r(d[0])},1582,[876]); __d(function(g,r,_i,a,m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.RotaEditor=function({today:e}){const j=(0,i.useOwner)(e=>e.staff).filter(e=>e.active),S=(0,i.useOwner)(e=>e.shifts),[k,D]=(0,t.useState)((0,i.mondayOfDate)(e)),$=(0,h.useDateCalendar)(),[v,w]=(0,t.useState)(null),[B,O]=(0,t.useState)(''),P=(0,c.useHistory)(()=>i.useOwner.getState().shifts,e=>i.useOwner.getState().setShifts(e),'rota change'),I=x.map((e,t)=>(0,i.addDays)(k,t)),T=(e,t,o)=>{e.preventDefault(),w(null);const d=(0,u.readDrag)(e);if('shift'!==d?.kind)return;const s=S.find(e=>e.id===d.id);if(!s)return;const n=!!e.altKey,c=j.find(e=>e.id===t)?.name??'';(n||s.staffId!==t||s.date!==o)&&(S.some(e=>e.staffId===t&&e.date===o&&e.id!==s.id&&e.starte.date>=k&&e.date<=I[6]),z=_.filter(e=>!e.published||e.changed).length;return(0,b.jsxs)(d.default,{style:{flex:1,gap:10},testID:"desk-rota",children:[(0,b.jsx)(f.Tip,{children:"Drag a shift to another day or person. Hold Option (Alt) while you drop to copy it instead. Nothing goes to staff until you press Publish."}),(0,b.jsxs)(s.Row,{gap:8,children:[(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"\u2039 Week before",onPress:()=>D((0,i.addDays)(k,-7))}),(0,b.jsxs)(s.T,{weight:"semibold",children:["Week of ",new Date(k+'T12:00:00').toLocaleDateString('en-GB',{day:'numeric',month:'long'})]}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Next week \u203a",onPress:()=>D((0,i.addDays)(k,7))}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",testID:"desk-rota-cal",label:"Calendar",accessibilityLabel:"Pick a date from the calendar",onPress:$.openCal}),(0,b.jsx)(h.AppDateCalendar,{visible:$.calOpen,today:e,day:k,idPrefix:"desk-rota-cal",onClose:$.closeCal,onDay:t=>D((0,i.mondayOfDate)(t??e))}),(0,b.jsx)(d.default,{style:{flex:1}}),B?(0,b.jsx)(s.T,{size:13,colour:n.colours.goldLight,children:B}):null,(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Undo",disabled:!P.canUndo,onPress:P.undo,testID:"rota-undo"}),(0,b.jsx)(s.Button,{small:!0,kind:"secondary",label:"Redo",disabled:!P.canRedo,onPress:P.redo,testID:"rota-redo"}),(0,b.jsx)(s.Button,{small:!0,label:z?`Publish (${z})`:'Published',disabled:!z,onPress:()=>{P.record('published the week');const e=i.useOwner.getState().publishWeek(k);O(`${e} shifts published.`)},testID:"rota-publish"})]}),(0,b.jsx)("div",{style:(0,f.box)({flex:1,overflow:'auto',border:`1px solid ${n.colours.border}`,borderRadius:12}),"data-testid":"rota-grid",children:(0,b.jsxs)("div",{style:(0,f.box)({display:'grid',gridTemplateColumns:"180px repeat(7, minmax(110px, 1fr))",minWidth:960}),children:[(0,b.jsx)("div",{style:(0,f.box)({position:'sticky',top:0,background:n.colours.surface,padding:8,borderBottom:`1px solid ${n.colours.border}`,zIndex:1})}),I.map((t,o)=>(0,b.jsxs)("div",{style:(0,f.box)({position:'sticky',top:0,zIndex:1,background:t===e?n.colours.goldTint:n.colours.surface,padding:8,borderBottom:`1px solid ${n.colours.border}`,fontFamily:'Poppins_600SemiBold',fontSize:13,color:t===e?n.colours.gold:n.colours.text}),children:[x[o]," ",Number(t.slice(8))]},t)),j.map(e=>(0,b.jsxs)(o.default.Fragment,{children:[(0,b.jsxs)("div",{style:(0,f.box)({padding:8,borderBottom:`1px solid ${n.colours.hairline}`,fontSize:13}),children:[(0,b.jsx)("div",{style:(0,f.box)({fontFamily:'Poppins_600SemiBold'}),children:e.name}),(0,b.jsx)("div",{style:(0,f.box)({fontSize:11,color:n.colours.muted}),children:e.job})]}),I.map(t=>{const o=`${e.id}|${t}`,d=_.filter(o=>o.staffId===e.id&&o.date===t);return(0,b.jsx)("div",{"data-testid":`rota-cell-${e.id}-${t}`,onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect=e.altKey?'copy':'move',w(o)},onDragLeave:()=>w(null),onDrop:o=>T(o,e.id,t),style:(0,f.box)({padding:5,minHeight:54,borderBottom:`1px solid ${n.colours.hairline}`,borderLeft:`1px solid ${n.colours.hairline}`,background:v===o?n.colours.accentBg:void 0,outline:v===o?`2px dashed ${n.colours.gold}`:void 0,outlineOffset:-3}),children:d.map(e=>(0,b.jsxs)("div",{draggable:!0,onDragStart:t=>(0,u.dragData)(t,'shift',e.id),"data-testid":`rota-shift-${e.id}`,title:e.note??'',style:(0,f.box)({cursor:'grab',userSelect:'none',borderRadius:8,padding:'4px 6px',marginBottom:4,fontSize:12,fontFamily:'Poppins_600SemiBold',background:e.published&&!e.changed?n.colours.gold:n.colours.goldTint,color:e.published&&!e.changed?n.colours.onGold:n.colours.goldLight,border:`1px solid ${n.colours.accentBorder}`}),children:[(0,l.fmtH)(e.start),"\u2013",(0,l.fmtH)(e.end),!e.published||e.changed?' \u2022':'']},e.id))},o)})]},e.id))]})}),(0,b.jsx)(s.Muted,{size:12,children:"Solid gold = published. Outlined with a dot = not yet published (new or changed)."})]})};var t=r(_d[0]),o=e(t),d=e(r(_d[1])),s=r(_d[2]),i=r(_d[3]),l=r(_d[4]),n=r(_d[5]),u=r(_d[6]),c=r(_d[7]),f=r(_d[8]),h=r(_d[9]),p=r(_d[10]),b=r(_d[11]);const x=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],y=()=>`sh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`},1583,[17,85,777,876,1060,804,1578,1579,1580,1051,1582,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1584,[13,17,856,1585,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1585,[1460,1586,813,912,1072,1512,1209,1210,1028,1025,1026,1513,1547,1515,1153,891,978,1587,975,880,1031,1032,1496,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1420,1066,1084,1086,1081,1027,1010,1057,1506,1501,1528,1588,1428,920,219,1246,1182,1189,1458,1202,1185,1483,1186,878,1212,1213,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1585,[1460,1586,813,912,1072,1512,1209,1210,1028,1025,1026,1513,1547,1515,1153,891,978,1587,975,880,1031,1032,1496,914,1008,915,17,1155,1241,1245,1203,356,385,278,85,409,19,777,857,876,804,1161,1420,1066,1084,1086,1081,1027,1010,1057,1506,1501,1528,1588,1428,920,219,1246,1182,1189,1458,1202,1185,1483,1186,878,1212,1213,884,776,899,8]); __d(function(g,_r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffBookingTimes=function(){const{r:e,rid:s}=(0,o.useCtx)(),[u,c]=(0,t.useState)(()=>Object.fromEntries(d.map(([t])=>[t,e.kitchenHours?.[t]??null]))),[h,b]=(0,t.useState)(String(e.settings.turnMins??'')),[v,y]=(0,t.useState)(String(e.settings.bookingCoversPerSlot??'')),[x,j]=(0,t.useState)(''),[k,S]=(0,t.useState)(!1),f=(e,t,s)=>c(n=>({...n,[e]:0===t?[s,n[e]?.[1]??'']:[n[e]?.[0]??'',s]})),p=Object.values(u).every(e=>!e||e.every(e=>/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(e))&&e[0]=30&&Number(h)<=360&&Number(v)>=1&&Number(v)<=1e3;return(0,r.jsxs)(n.default,{style:{gap:12,width:'100%',minWidth:0},testID:"staff-booking-times",children:[(0,r.jsx)(i.T,{center:!0,weight:"bold",children:"Booking times"}),(0,r.jsx)(i.Muted,{center:!0,children:"Change kitchen hours, table time and the Covers offered in each booking slot. Table layout and blocks have their own screens."}),d.map(([e,t])=>(0,r.jsxs)(i.Card,{children:[(0,r.jsx)(i.T,{center:!0,weight:"semibold",children:t}),(0,r.jsx)(i.Toggle,{label:`${t} open`,value:!!u[e],onChange:t=>c(s=>({...s,[e]:t?['','']:null}))}),u[e]?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i.Field,{label:`${t} opens (HH:MM)`,value:u[e][0],placeholder:"HH:MM",onChangeText:t=>f(e,0,t)}),(0,r.jsx)(i.Field,{label:`${t} closes (HH:MM)`,value:u[e][1],placeholder:"HH:MM",onChangeText:t=>f(e,1,t)})]}):(0,r.jsx)(i.Muted,{center:!0,children:"Closed"})]},e)),(0,r.jsxs)(i.Card,{children:[(0,r.jsx)(i.Field,{label:"Typical table time, minutes",value:h,onChangeText:b,keyboardType:"number-pad"}),(0,r.jsx)(i.Field,{label:"Covers per 30-minute booking slot",value:v,onChangeText:y,keyboardType:"number-pad"}),e.settings.bookingCoversPerStart||e.settings.bookingPartiesPerStart?(0,r.jsx)(i.Muted,{center:!0,children:"Online booking uses the covers and bookings caps at each start time (Settings \u203a Capacity & waitlist), not this half-hour figure."}):null]}),(0,r.jsx)(i.Button,{label:k?'Saving\u2026':'Save booking times',disabled:!p||k,accessibilityLabel:"Save booking times without changing other venue settings",onPress:async()=>{S(!0);try{await(0,l.saveStaffBookingTimes)(s,u,Number(h),Number(v)),j('Booking times saved.')}catch(e){j(e.message)}finally{S(!1)}}}),x?(0,r.jsx)(i.Muted,{center:!0,children:x}):null]})};var e,t=_r(_d[0]),s=_r(_d[1]),n=(e=s)&&e.__esModule?e:{default:e},i=_r(_d[2]),o=_r(_d[3]),l=_r(_d[4]),r=_r(_d[5]);const d=[[1,'Monday'],[2,'Tuesday'],[3,'Wednesday'],[4,'Thursday'],[5,'Friday'],[6,'Saturday'],[0,'Sunday']]},1586,[17,85,777,1057,899,8]); __d(function(g,_r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.newerRelease=r,_e.startForegroundRefresh=function(n={}){if('undefined'==typeof document)return()=>{};let o='hidden'===document.visibilityState?Date.now():0,c=!1;const s=n.reload??(()=>location.reload()),u=async()=>{if(!c){c=!0;try{await Promise.race([e.mutationQueue.retryNow(),new Promise(e=>setTimeout(e,4e3))]),n.onWake?.();const t=await(navigator.serviceWorker?.getRegistration?.().catch(()=>{}));if(await(t?.update?.().catch(()=>{})),t?.waiting){try{t.waiting.postMessage({type:'SKIP_WAITING'})}catch{}return void setTimeout(s,3e3)}await r().catch(()=>!1)&&s()}finally{c=!1}}},l=()=>{if('hidden'===document.visibilityState)return void(o=Date.now());const n=o?Date.now()-o:0;o=0,e.mutationQueue.retryNow(),n>=t&&u()},f=()=>{e.mutationQueue.retryNow()};document.addEventListener('visibilitychange',l);for(const e of['focus','online','pageshow'])window.addEventListener(e,f);return()=>{document.removeEventListener('visibilitychange',l);for(const e of['focus','online','pageshow'])window.removeEventListener(e,f)}},_r(d[0]);var e=_r(d[1]);const t=3e4,n=e=>(e.match(/_expo\/static\/js\/web\/[A-Za-z0-9_.-]+\.js(\?v=[0-9a-f]+)?/)??[])[0]??null;function o(){try{const e=[...document.querySelectorAll('script[src]')].map(e=>e.src).find(e=>/_expo\/static\/js\/web\//.test(e));return e?n(e):null}catch{return null}}async function r(e=fetch){const t=o();if(!t)return!1;const r=location.pathname.replace(/[^/]*$/,''),c=await e(`${r}index.html?fresh=${Date.now()}`,{cache:'no-store'});if(!c.ok)return!1;const s=n(await c.text());return!!s&&s!==t}},1587,[219,976]); __d(function(g,_r,i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ManagerFeaturesNote=function(){return(0,j.jsxs)(a.default,{testID:"manager-features-banner",style:{borderWidth:1,borderColor:b.colours.gold,borderRadius:12,padding:10,gap:4},children:[(0,j.jsx)(d.T,{weight:"semibold",colour:b.colours.gold,children:"Manager features are on"}),(0,j.jsx)(d.Muted,{children:"Open Me \u203a Manager features for bookings, tables, blocks, allergy checks, stock, who\u2019s clocked in and shift swaps."})]})},_e.ManagerFeaturesAbout=function(){return(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"semibold",children:"What manager features include"}),c.SHIFT_MANAGER_FEATURES.map(e=>(0,j.jsxs)(d.T,{size:14,children:["\u2022 ",e]},e)),(0,j.jsxs)(d.Muted,{children:["Not included: ",c.SHIFT_MANAGER_EXCLUDED_WORDS,". Those stay in the Managers app."]})]})},_e.ClockOverview=function({today:e,now:t}){const s=(0,o.useOwner)(e=>e.staff),n=(0,o.useOwner)(e=>e.attendance).filter(t=>t.date===e&&t.in),r=e=>x(s.find(t=>t.id===e)?.name)||'Team member',h=n.filter(e=>!e.out).sort((e,t)=>(e.in??'').localeCompare(t.in??'')),c=n.filter(e=>e.out).sort((e,t)=>(e.out??'').localeCompare(t.out??'')),u=e=>(e.breaks??[]).some(e=>!e.end);return(0,j.jsxs)(a.default,{style:{gap:10},testID:"clock-overview",children:[(0,j.jsxs)(d.T,{weight:"semibold",children:["Clocked in now (",h.length,")"]}),h.length?h.map(e=>(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"medium",children:r(e.staffId)}),(0,j.jsxs)(d.Muted,{children:["In at ",(0,l.hm)(new Date(e.in)),u(e)?' \xb7 on a break':'',!1===e.inSite?' \xb7 clocked in away from the venue':'']})]},e.id)):(0,j.jsx)(d.Muted,{children:"Nobody is clocked in right now."}),(0,j.jsxs)(d.T,{weight:"semibold",children:["Finished today (",c.length,")"]}),c.length?c.map(e=>(0,j.jsxs)(d.Card,{children:[(0,j.jsx)(d.T,{weight:"medium",children:r(e.staffId)}),(0,j.jsxs)(d.Muted,{children:[(0,l.hm)(new Date(e.in))," to ",(0,l.hm)(new Date(e.out))]})]},e.id)):(0,j.jsx)(d.Muted,{children:"Nobody has clocked out yet today."}),(0,j.jsxs)(d.Muted,{children:["Read only. To change someone\u2019s clock record, ask a manager in the Managers app. Checked at ",(0,l.hm)(t),"."]})]})},_e.TablesToClear=function({rid:e}){const s=(0,r.useFloor)(t=>t.live[e])??{},n=Object.entries(s).filter(([,e])=>e?.dirty).map(([e])=>e).sort((e,t)=>e.localeCompare(t,'en',{numeric:!0}));return(0,j.jsx)(a.default,{style:{gap:8},testID:"tables-to-clear",children:n.length?n.map(s=>(0,j.jsx)(d.Card,{children:(0,j.jsxs)(d.Row,{style:{justifyContent:'space-between'},children:[(0,j.jsx)(d.T,{weight:"semibold",children:(0,t.tableNumbers)(s)}),(0,j.jsx)(d.Button,{small:!0,kind:"success",label:"Mark cleared",accessibilityLabel:`Mark table ${s} cleared, table free`,testID:`clear-${s}`,onPress:()=>{r.useFloor.getState().setLive(e,s,{dirty:!1,stage:void 0}),(0,w.notify)({id:`clear-${s}`,title:`${(0,t.tableNumbers)(s)} is free`,timeoutMs:4e3})}})]})},s)):(0,j.jsx)(d.Muted,{children:"No tables need clearing."})})},_e.SwapApprovals=function({today:e,me:t}){const n=(0,o.useOwner)(e=>e.staff),r=(0,o.useOwner)(e=>e.shifts),y=(0,o.useOwner)(e=>e.swaps),[M,k]=(0,s.useState)(null),[I,v]=(0,s.useState)(null),[T,S]=(0,s.useState)(!1),C=e=>x(n.find(t=>t.id===e)?.name)||'Team member',D=(()=>{const t=(0,l.parseYmd)(e);return t.setDate(t.getDate()+13),t})(),N=r.filter(t=>{return!1!==t.published&&t.date>=e&&(0,l.parseYmd)(t.date)<=D&&(s=t.staffId,!('owner'===n.find(e=>e.id===s)?.role));var s}).sort((e,t)=>e.date.localeCompare(t.date)||e.start-t.start),O=e=>`${(0,l.niceDate)((0,l.parseYmd)(e.date))}, ${(0,h.fmtH)(e.start)} to ${(0,h.fmtH)(e.end)}`,R=async(e,s,n,a)=>{S(!0);const d=await(0,u.approveShiftSwap)(e.id,s,n);S(!1),d.ok?(o.useOwner.setState(t=>({shifts:t.shifts.map(t=>t.id===e.id?{...t,staffId:s}:t)})),a&&o.useOwner.getState().setSwap(a,'approved'),(0,w.notify)({id:'swap-ok',title:'Shift changed',body:`${C(e.staffId)}\u2019s shift on ${O(e)} is now ${C(s)}\u2019s. Approved by ${x(t)}.`,timeoutMs:6e3}),k(null),v(null)):(0,w.notify)({id:'swap-fail',title:'Not changed',body:d.message,timeoutMs:6e3})},$=y.filter(e=>'open'===e.status);return(0,j.jsxs)(a.default,{style:{gap:10},testID:"swap-approvals",children:[(0,j.jsxs)(d.T,{weight:"semibold",children:["Requests (",$.length,")"]}),$.length?$.map(e=>{const t=r.find(t=>t.id===e.shiftId);return(0,j.jsxs)(d.Card,{children:[(0,j.jsxs)(d.T,{weight:"medium",children:[C(e.fromId)," \xb7 ",'cover'===e.kind?'needs cover':'swap']}),(0,j.jsxs)(d.Muted,{children:[t?O(t):'Shift not found',e.toId?` \xb7 to ${C(e.toId)}`:'',e.note?` \xb7 ${e.note}`:'']}),(0,j.jsxs)(d.Row,{gap:6,children:[(0,j.jsx)(d.Button,{small:!0,label:"Approve",disabled:!t||!e.toId||T||!(0,p.canSwapWith)(n.find(t=>t.id===e.fromId),n.find(t=>t.id===e.toId),f.VENUE_RID),onPress:()=>t&&e.toId&&R(t,e.toId,e.kind,e.id)}),(0,j.jsx)(d.Button,{small:!0,kind:"ghost",label:"Decline",onPress:()=>o.useOwner.getState().setSwap(e.id,'declined')})]})]},e.id)}):(0,j.jsx)(d.Muted,{children:"No open requests on this phone. Swap requests made on other phones aren\u2019t shared yet, so if someone asks you in person, use Give a shift to someone else below."}),(0,j.jsx)(d.T,{weight:"semibold",children:"Give a shift to someone else"}),M?(0,j.jsxs)(d.Card,{highlight:b.colours.gold,children:[(0,j.jsxs)(d.T,{weight:"semibold",children:[C(M.staffId)," \xb7 ",O(M)]}),(0,j.jsx)(d.Muted,{children:"Who takes it? Only someone they are allowed to swap with."}),(0,j.jsx)(d.Row,{wrap:!0,gap:6,children:(0,c.swapTargets)(n,M.staffId,f.VENUE_RID).map(e=>(0,j.jsx)(d.Chip,{label:x(e.name),selected:I===e.id,onPress:()=>v(e.id)},e.id))}),(0,j.jsxs)(d.Row,{gap:6,children:[(0,j.jsx)(d.Button,{label:"Approve",disabled:!I||T,onPress:()=>I&&R(M,I,'swap'),testID:"swap-give"}),(0,j.jsx)(d.Button,{kind:"secondary",label:"Cancel",onPress:()=>{k(null),v(null)}})]})]}):N.length?N.map(e=>(0,j.jsxs)(d.Card,{onPress:()=>{k(e),v(null)},children:[(0,j.jsx)(d.T,{weight:"medium",children:C(e.staffId)}),(0,j.jsx)(d.Muted,{children:O(e)})]},e.id)):(0,j.jsx)(d.Muted,{children:"No published shifts in the next two weeks."}),(0,j.jsx)(d.Banner,{kind:"info",children:"Approving moves the shift on the rota for everyone and records who approved it. Writing or publishing the rota stays in the Managers app."})]})};var e,t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),a=(e=n)&&e.__esModule?e:{default:e},d=_r(_d[3]),o=_r(_d[4]),r=_r(_d[5]),l=_r(_d[6]),h=_r(_d[7]),c=_r(_d[8]),u=_r(_d[9]),p=_r(_d[10]),f=_r(_d[11]),w=_r(_d[12]),b=_r(_d[13]),j=_r(_d[14]);const x=e=>(e??'').replace(' (example)','')},1588,[843,17,85,777,876,998,863,1060,1058,899,1059,805,916,804,8]); @@ -1701,7 +1701,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0});var t=r(d[0]);Object.keys(t).forEach(function(n){'default'===n||Object.prototype.hasOwnProperty.call(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[n]}})})},1618,[1619]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.preventAutoHideAsync=async function(){return!1},e.setOptions=function(n){},e.hide=function(){},e.hideAsync=async function(){}},1619,[]); __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1620,[17,24,85,409,777,857,920,899,880,805,804,1561,1563,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1621,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1621,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1622,[813,779,17,974,385,85,856,899,976,804,777,1352,971,880,1623,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.SyncDeviceActions=function(){const e=(0,o.useSync)(),[f,p]=(0,s.useState)(!1),h='live'===e.mode||'offline'===e.mode;return e.venueId&&h?(0,b.jsxs)(b.Fragment,{children:[f?(0,b.jsxs)(c.default,{style:{gap:6,marginTop:6},children:[(0,b.jsx)(u.T,{size:12,children:"Disconnect this device? Your changes stay on it; open your personal invite link to connect again."}),(0,b.jsxs)(c.default,{style:{flexDirection:'row',gap:8},children:[(0,b.jsx)(t.default,{testID:"unpair-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, disconnect",onPress:()=>{p(!1),(0,o.disconnectStaff)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:l.colours.red},children:(0,b.jsx)(u.T,{size:12,weight:"semibold",children:"Yes, disconnect"})}),(0,b.jsx)(t.default,{accessibilityRole:"button",accessibilityLabel:"Keep connected",onPress:()=>p(!1),style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,b.jsx)(u.T,{size:12,children:"Keep"})})]})]}):(0,b.jsx)(t.default,{testID:"unpair",accessibilityRole:"button",accessibilityLabel:"Disconnect this device",onPress:()=>p(!0),style:{marginTop:6,alignSelf:'flex-start'},children:(0,b.jsx)(u.T,{size:12,colour:l.colours.gold,children:"Disconnect this device\u2026"})}),(0,b.jsx)(n.WipeDevice,{compact:!0})]}):null};var s=r(d[0]),n=r(d[1]),t=e(r(d[2])),c=e(r(d[3])),o=r(d[4]),l=r(d[5]),u=r(d[6]),b=r(d[7])},1623,[17,1461,385,85,899,804,777,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1624,[]); diff --git a/owner-desktop/index.html b/owner-desktop/index.html index 51290114e46a6da688aa146f629752f47dee15ff..180e8f40a659a0272e694bf23e0308eb146303b3 100644 --- a/owner-desktop/index.html +++ b/owner-desktop/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-desktop/owner.html b/owner-desktop/owner.html index aed5fc9dcee8c479b24b6bd8c99f28a2be104479..df0d165a2879bf594f07f9316d783719c88440c6 100644 --- a/owner-desktop/owner.html +++ b/owner-desktop/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/owner-desktop/sw.js b/owner-desktop/sw.js index daad13b50b8cba1b8259ff368b02600bc408159d..dd7b30395d606f3b93b40b6f268b71e9487d6f4a 100644 --- a/owner-desktop/sw.js +++ b/owner-desktop/sw.js @@ -1,7 +1,7 @@ // Anchorage owners desktop service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-desk-ab49ae75c5"; +const V = "cc-desk-234afef24d"; const BASE = "/owner-desktop/"; -const PRECACHE = ["/owner-desktop/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/owner-desktop/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/owner-desktop/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/owner-desktop/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/owner-desktop/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/owner-desktop/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/owner-desktop/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/owner-desktop/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/owner-desktop/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/owner-desktop/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/owner-desktop/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/owner-desktop/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/owner-desktop/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/owner-desktop/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/owner-desktop/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/owner-desktop/favicon.ico", "/owner-desktop/index.html", "/owner-desktop/_expo/static/js/web/bundle.js?v=ab49ae75c5ecd0b1751873123ff530791cf9e2bea0f6e7df76be297af281d693"]; +const PRECACHE = ["/owner-desktop/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/owner-desktop/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/owner-desktop/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/owner-desktop/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/owner-desktop/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/owner-desktop/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/owner-desktop/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/owner-desktop/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/owner-desktop/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/owner-desktop/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/owner-desktop/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/owner-desktop/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/owner-desktop/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/owner-desktop/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/owner-desktop/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/owner-desktop/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/owner-desktop/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/owner-desktop/favicon.ico", "/owner-desktop/index.html", "/owner-desktop/_expo/static/js/web/bundle.js?v=234afef24dc2d24e5a8935dc6a27b389d55afa5adc28ad0e01acd32d7cfaf82c"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/staff-app/_expo/static/js/web/bundle.js b/staff-app/_expo/static/js/web/bundle.js index e93d3dda20f80f938227a2f8751993ea475d2908..190ecb3150079532eb82b8b6aab1d770edbb721f 100644 --- a/staff-app/_expo/static/js/web/bundle.js +++ b/staff-app/_expo/static/js/web/bundle.js @@ -927,7 +927,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";function t(t){const n=String(t??'').tri __d(function(e,a,l,r,t,o,s){t.exports={venue:"The Anchorage",note:"From Gordon 28 Oct 2026; layout from Gordon's floor-plan photo 29 Oct 2026 (positions, sizes, shapes, labels scaled from the photo, one scale for all areas). Photo shows MT12 and no MT8: table 8 replaced by 12. Gordon confirmed 29 Oct: no table 8; MT11 and MT12 both exist, MT11 keeps 2 seats, MT12 = 2 seats. No tables 4 or 8. No joined tables: Gordon confirmed 29 Oct that DT1 and DT2 are not joined.",areas:[{name:"Public Bar",label:"Dog friendly area (Public Bar), Area 1",colour:"#CFA45F",server:"BR",dogFriendly:!0,tables:[[1,4],[2,4],[3,5],[5,2],[6,4]],layout:{1:{label:"DT1",shape:"rect",x:600,y:125,w:205,h:90},2:{label:"DT2",shape:"rect",x:395,y:130,w:100,h:190},3:{label:"DT3",shape:"rect",x:205,y:120,w:110,h:245},5:{label:"DT5",shape:"square",x:500,y:395,w:105,h:105},6:{label:"DT6",shape:"rect",x:195,y:395,w:205,h:110}},best:[1,3]},{name:"Main Restaurant",label:"Main restaurant (no pets)",colour:"#8EC5FF",server:"SV",dogFriendly:!1,tables:[[7,5],[9,7],[10,4],[11,2],[12,2],[13,4],[14,4],[15,4],[16,2]],layout:{7:{label:"MT7",shape:"rect",x:590,y:410,w:225,h:115},9:{label:"MT9",shape:"rect",x:560,y:105,w:260,h:110},10:{label:"MT10",shape:"square",x:430,y:400,w:130,h:130},11:{label:"MT11",shape:"rect",x:545,y:270,w:115,h:90},12:{label:"MT12",shape:"rect",x:400,y:270,w:120,h:95},13:{label:"MT13",shape:"rect",x:400,y:100,w:90,h:115},14:{label:"MT14",shape:"rect",x:185,y:420,w:230,h:100},15:{label:"MT15",shape:"rect",x:190,y:220,w:165,h:145},16:{label:"MT16",shape:"rect",x:185,y:105,w:125,h:80}},best:[7,9]},{name:"Sitooterie",label:"Sitooterie (fully covered conservatory, no pets)",colour:"#C79BE8",server:"DM",dogFriendly:!1,tables:[[17,2],[18,6],[19,4],[20,6],[21,4],[22,4],[23,4]],layout:{17:{label:"ST17",shape:"square",x:760,y:325,w:110,h:110},18:{label:"ST18",shape:"rect",x:605,y:135,w:270,h:115},19:{label:"ST19",shape:"rect",x:460,y:160,w:105,h:150},20:{label:"ST20",shape:"rect",x:135,y:125,w:265,h:120},21:{label:"ST21",shape:"rect",x:120,y:305,w:110,h:175},22:{label:"ST22",shape:"rect",x:255,y:310,w:115,h:175},23:{label:"ST23",shape:"rect",x:410,y:350,w:110,h:155}},best:[19,21]},{name:"Beer Garden",label:"Outdoor beer garden (weather permitting, no shelter, pets allowed)",colour:"#B08D57",server:"GD",dogFriendly:!0,outdoor:!0,weatherDependent:!0,tables:[[24,4],[25,4],[26,4],[27,6],[28,6],[29,4],[30,4],[31,4]],layout:{24:{label:"BGT24",shape:"round",x:740,y:70,w:130,h:130},25:{label:"BGT25",shape:"round",x:515,y:50,w:135,h:135},26:{label:"BGT26",shape:"round",x:310,y:50,w:135,h:135},27:{label:"BGT27",shape:"rect",x:560,y:235,w:280,h:115},28:{label:"BGT28",shape:"rect",x:245,y:235,w:270,h:110},29:{label:"BGT29",shape:"rect",x:210,y:365,w:190,h:60},30:{label:"BGT30",shape:"rect",x:180,y:445,w:190,h:55},31:{label:"BGT31",shape:"rect",x:130,y:520,w:215,h:60}},best:[27,28]}],photoScale:1.8,joins:[],bestNote:"Best tables per area from Gordon, 1 Nov 2026: Bar 1 and 3; Restaurant 7 and 9; Sitooterie 19 and 21; Outside (Beer Garden) 27 and 28. Shown as BEST for walk-ins and bookings when they fit; editable per area in the table plan."}},844,[]); __d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ALLERGENS",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"allergenLabel",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"SEVERITIES",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"severityLabel",{enumerable:!0,get:function(){return s}}),e.effectiveAllergens=function(l,n=[]){const t={...l.allergens};for(const s of l.optionGroups??[])for(const l of s.choices)if(n.includes(l.id)&&l.allergens)for(const[n,s]of Object.entries(l.allergens))'contains'!==t[n]&&(t[n]=s);return t},e.conflictsFor=function(l,n){const t=[],s=[];for(const a of n)'contains'===l[a.allergen]?t.push(a.allergen):'may'===l[a.allergen]&&s.push(a.allergen);return{contains:t,may:s}},Object.defineProperty(e,"hasConflict",{enumerable:!0,get:function(){return a}});const l=[{id:'gluten',label:'Cereals containing gluten',short:'Gluten'},{id:'crustaceans',label:'Crustaceans',short:'Crustaceans'},{id:'molluscs',label:'Molluscs',short:'Molluscs'},{id:'eggs',label:'Eggs',short:'Eggs'},{id:'fish',label:'Fish',short:'Fish'},{id:'peanuts',label:'Peanuts',short:'Peanuts'},{id:'treenuts',label:'Tree nuts',short:'Tree nuts'},{id:'soya',label:'Soya',short:'Soya'},{id:'milk',label:'Milk',short:'Milk'},{id:'celery',label:'Celery',short:'Celery'},{id:'mustard',label:'Mustard',short:'Mustard'},{id:'sesame',label:'Sesame',short:'Sesame'},{id:'sulphites',label:'Sulphur dioxide / sulphites',short:'Sulphites'},{id:'lupin',label:'Lupin',short:'Lupin'}],n=n=>l.find(l=>l.id===n)?.short??n,t=[{id:'intolerance',label:'Intolerance'},{id:'allergy',label:'Allergy'},{id:'coeliac',label:'Coeliac disease'},{id:'anaphylaxis',label:'Severe \u2014 anaphylaxis risk'}],s=l=>t.find(n=>n.id===l)?.label??l;const a=l=>l.contains.length>0||l.may.length>0},845,[]); __d(function(g,r,_i,_a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"setMenuCardBridge",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"menuCardBridge",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"resolveItem",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"resolveMenu",{enumerable:!0,get:function(){return m}}),e.sortMenu=c;var t=r(d[0]);let n=null;const o=t=>{n=t},u=()=>n,i=o=>(0,t.overlayItem)(o,n?.cardFor(o.id)),m=t=>c(t.map(i));function c(t){return t.some(t=>'number'==typeof t.sort)?t.map((t,n)=>({m:t,i:n,k:'number'==typeof t.sort?t.sort:10*n})).sort((t,n)=>t.k-n.k||t.i-n.i).map(t=>t.m):t}},846,[847]); -__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return r}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return o}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return a}}),e.cardPhotos=s,e.suggestForIngredient=d,e.suggestAllergens=u,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return f}}),e.unresolved=g,e.applySuggestions=function(t){const n={...t.allergens};for(const r of g(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return h}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=g(t);return n.length?`Check the suggested allergens first: ${n.map(p).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return y}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,l={...a};l.photos&&_(s({photo:l.photo??t.photo,photos:l.photos}),s(t))&&(delete l.photos,void 0!==l.photo&&l.photo!==(t.photo??s(t)[0])||delete l.photo);const c=Object.keys(l).filter(n=>!_(l[n],t[n]));let d={...t};for(const t of c)d[t]=l[t];const f=c.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);f&&!_(u(d.ingredients),u(t.ingredients))&&(d.allergensConfirmed=void 0);f&&(c.includes('allergens')||c.includes('dismissed'))&&(d.allergensConfirmed=void 0);let m=!1;!o||d.allergensConfirmed||g(d).length||(d.allergensConfirmed={by:r,at:i},m=!0);const h=c.length>0||m,p=c.length>0&&!!t.signOff;if(!h)return{card:t,changed:!1,resetSignOff:!1};c.length&&(d={...d,signOff:null,version:t.version+1});return{card:{...d,updatedAt:i,updatedBy:r},changed:h,resetSignOff:p}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return O}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||O(t.id)||O(n.menuItemId),recipeCardId:n.id}:O(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return S}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(w),allergens:b(t.allergens,'contains'),may_contain:b(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(w).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=t=>'head-chef'===t||'manager'===t||'owner'===t;const i={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},o=t=>`${t.name}, ${i[t.actual??t.role]}`;const a=5;function s(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,a)}const l=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],c=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function d(n){const r=new Set(n.allergens??[]);for(const[t,i]of l)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of c)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function u(n){const r=new Set(n.flatMap(d));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const f=(t,n)=>t.filter(t=>d(t).includes(n)).map(t=>t.name);function g(t){return u(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const m=t=>t.signOff?'signed-off':'awaiting',h={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const p=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,b=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),y=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],_=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const O=t=>'a-mini'===t;const v={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},w='\n',E=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,C='recipe-photos',S='recipe_cards'},847,[845]); +__d(function(_g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"canEditCards",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ownsCard",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"mayEditCard",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"mayCreateCard",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"canSignOffCards",{enumerable:!0,get:function(){return a}}),e.maySignOff=function(t,n){return'staff'!==t.role&&('head-chef'===t.role||('head-chef'===t.actual||!('owner'!==t.role&&'manager'!==t.role||'owner'!==t.actual&&'manager'!==t.actual)||!!n.createdBy&&t.name.trim()===n.createdBy.trim()&&'head-chef'===n.createdByRole))},Object.defineProperty(e,"SIGNER_ROLE_LABEL",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"signerLabel",{enumerable:!0,get:function(){return l}}),e.cardActorFor=function(t,n,r){const i=r?'Head Chef'===r.level&&'staff'===r.role?'head-chef':r.role:n;return{name:t,role:n,actual:i}},Object.defineProperty(e,"MAX_RECIPE_PHOTOS",{enumerable:!0,get:function(){return c}}),e.cardPhotos=d,e.suggestForIngredient=g,e.suggestAllergens=m,Object.defineProperty(e,"suggestedBy",{enumerable:!0,get:function(){return h}}),e.unresolved=p,e.applySuggestions=function(t){const n={...t.allergens};for(const r of p(t))n[r]='contains';return n},Object.defineProperty(e,"cardState",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"STATE_LABEL",{enumerable:!0,get:function(){return y}}),e.signOffBlock=function(t){if(!t.dish.trim())return'Give the dish a name first.';const n=p(t);return n.length?`Check the suggested allergens first: ${n.map(_).join(', ')}.`:t.allergensConfirmed?null:'Confirm the allergen list first.'},Object.defineProperty(e,"allergenList",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"CONTENT_FIELDS",{enumerable:!0,get:function(){return w}}),e.editCard=function(t,n,r,i){const{confirmAllergens:o,...a}=n,s={...a};s.photos&&C(d({photo:s.photo??t.photo,photos:s.photos}),d(t))&&(delete s.photos,void 0!==s.photo&&s.photo!==(t.photo??d(t)[0])||delete s.photo);const l=Object.keys(s).filter(n=>!C(s[n],t[n]));let c={...t};for(const t of l)c[t]=s[t];const u=l.some(t=>'allergens'===t||'dismissed'===t||'ingredients'===t);u&&!C(m(c.ingredients),m(t.ingredients))&&(c.allergensConfirmed=void 0);u&&(l.includes('allergens')||l.includes('dismissed'))&&(c.allergensConfirmed=void 0);let f=!1;!o||c.allergensConfirmed||p(c).length||(c.allergensConfirmed={by:r,at:i},f=!0);const g=l.length>0||f,h=l.length>0&&!!t.signOff;if(!g)return{card:t,changed:!1,resetSignOff:!1};l.length&&(c={...c,signOff:null,version:t.version+1});return{card:{...c,updatedAt:i,updatedBy:r},changed:g,resetSignOff:h}},e.signOffCard=function(t,n,r){return{...t,signOff:{by:n,at:r},wasLive:!0,updatedAt:r,updatedBy:n}},e.unsignedOldestFirst=function(t,n){return t.filter(t=>!t.signOff).map((t,r)=>{const i=n(t);return{item:t,card:i,at:i?.createdAt||null,order:r}}).sort((t,n)=>(t.at&&n.at?t.at.localeCompare(n.at):t.at?-1:n.at?1:0)||t.order-n.order)},e.addedLabel=function(t){const n=t?new Date(t.length<=10?`${t}T12:00:00`:t):null;return n&&!isNaN(+n)?`Added ${n.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})}`:'Date not recorded'},e.allergenSentence=function(n){const r=t.ALLERGENS.filter(t=>'contains'===n[t.id]).map(t=>t.short.toLowerCase()),i=t.ALLERGENS.filter(t=>'may'===n[t.id]).map(t=>t.short.toLowerCase());return r.length||i.length?[r.length?`Contains ${r.join(', ')}.`:'',i.length?`May contain ${i.join(', ')}.`:''].filter(Boolean).join(' '):'No allergens listed yet.'},Object.defineProperty(e,"isRetiredMiniAnchors",{enumerable:!0,get:function(){return v}}),e.overlayItem=function(t,n){return n?{...t,name:n.dish,section:n.section,price:n.price,allergens:n.allergens,allergenNotes:n.allergenNotes,signOff:n.signOff?{by:n.signOff.by,at:n.signOff.at.slice(0,10)}:null,hidden:t.hidden||!n.signOff&&!n.wasLive||v(t.id)||v(n.menuItemId),recipeCardId:n.id}:v(t.id)?{...t,hidden:!0}:t},e.dishesFor=function(t,n){const r=t.filter(t=>!t.hidden),i=r.filter(t=>n.some(n=>'contains'===t.allergens[n])),o=r.filter(t=>!i.includes(t)&&n.some(n=>'may'===t.allergens[n])),a=r.filter(t=>!i.includes(t)&&!o.includes(t));return{contains:i,may:o,free:a}},e.filterCards=function(t,n,r,i="free-from"){const o=n.toLowerCase().split(/\s+/).filter(Boolean);return t.filter(t=>{const n=[t.dish,t.section,...t.ingredients.map(t=>t.name)].join(' ').toLowerCase();return!!o.every(t=>n.includes(t))&&(!r.length||('free-from'===i?r.every(n=>!t.allergens[n]):r.some(n=>!!t.allergens[n])))})},e.uuid=function(){const t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();const n=Array.from({length:16},()=>Math.floor(256*Math.random()));n[6]=15&n[6]|64,n[8]=63&n[8]|128;const r=n.map(t=>t.toString(16).padStart(2,'0')).join('');return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`},e.uuidFrom=function(t){let n='';for(let r=0;r<4;r++){let i=2166136261^2654435761*r;for(let n=0;n>>0;n+=i.toString(16).padStart(8,'0')}const r=n.slice(0,12)+'4'+n.slice(13,16)+(3&parseInt(n[16],16)|8).toString(16)+n.slice(17,32);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`},Object.defineProperty(e,"RECIPE_CARD_EXTRA_COLUMNS",{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,"STEP_SEP",{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,"photoPath",{enumerable:!0,get:function(){return L}}),Object.defineProperty(e,"RECIPE_PHOTO_BUCKET",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"RECIPE_CARD_TABLE",{enumerable:!0,get:function(){return P}}),e.cardToRow=function(t,n){return{row:{id:t.id,venue_id:n,dish:t.dish,ingredients:t.ingredients.map(({name:t,qty:n,unit:r,allergens:i})=>({name:t,qty:n,unit:r,...i?.length?{allergens:i}:{}})),method:t.steps.join(S),allergens:O(t.allergens,'contains'),may_contain:O(t.allergens,'may'),photo_url:!t.photo||t.photo.startsWith('local:')||t.photo.startsWith('asset:')?null:t.photo,signed_off_by:t.signOff?.by??null,signed_off_at:t.signOff?.at??null,updated_at:t.updatedAt},extra:{menu_item_id:t.menuItemId,section:t.section,price_pence:t.price,dismissed:t.dismissed,allergen_notes:t.allergenNotes??null,allergens_confirmed_by:t.allergensConfirmed?.by??null,allergens_confirmed_at:t.allergensConfirmed?.at??null,was_live:t.wasLive,origin:t.origin,version:t.version,updated_by:t.updatedBy}}},e.rowToCard=function(t,n,r={}){const i={};t.may_contain.forEach(t=>{i[t]='may'}),t.allergens.forEach(t=>{i[t]='contains'});const o=t.updated_at??(new Date).toISOString();return{id:t.id,restaurantId:n,menuItemId:r.menu_item_id??t.id,dish:t.dish,section:r.section??'Mains',price:r.price_pence??null,photo:t.photo_url??void 0,ingredients:t.ingredients.map((n,r)=>({id:`${t.id}-i${r}`,...n})),steps:t.method?t.method.split(S).filter(t=>t.trim()):[],allergens:i,dismissed:r.dismissed??[],allergenNotes:r.allergen_notes??void 0,allergensConfirmed:r.allergens_confirmed_by?{by:r.allergens_confirmed_by,at:r.allergens_confirmed_at}:void 0,signOff:t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:t.signed_off_at}:null,wasLive:r.was_live??!!t.signed_off_by,origin:r.origin??'new',version:r.version??1,createdAt:o,updatedAt:o,updatedBy:r.updated_by??''}};var t=_r(_d[0]);const n=t=>'head-chef'===t||'manager'===t||'owner'===t,r=(t,n)=>!!t.ownRef&&!!n?.authorRef&&t.ownRef===n.authorRef,i=(t,i)=>n(t.role)||!!t.ownRef&&(!i||r(t,i)),o=t=>n(t.role)||!!t.ownRef,a=t=>'head-chef'===t||'manager'===t||'owner'===t;const s={'head-chef':'Head Chef',manager:'Manager',owner:'Owner',staff:'Staff'},l=t=>`${t.name}, ${s[t.actual??t.role]}`;const c=5;function d(t){const n=(t.photos??[]).filter(t=>!!t);return[...t.photo&&!n.includes(t.photo)?[t.photo]:[],...n].slice(0,c)}const u=[[/\b(flour(?!y)|wheat|bread|crumb|panko|pastry|brioche|buns?\b|crouton|crostini|batter|beer|ale\b|lager|stout|barley|malt|rye|spelt|oat|couscous|semolina|pasta|penne|macaroni|spaghetti|noodle|biscuit|sponge|crumble|roux|tempura|digestive|self.raising)/i,['gluten']],[/\b(prawn|langoustine|lobster|crab|shrimp|crayfish|scampi|shellfish)/i,['crustaceans']],[/\b(mussel|scallop|clam|cockle|squid|calamari|octopus|whelk|winkle|oyster(?! mushroom)|oyster sauce)/i,['molluscs']],[/\b(egg|mayonnaise|mayo|aioli|tartare|hollandaise|meringue|custard|brioche|bearnaise)/i,['eggs']],[/\b(fish(?!er)|haddock|cod|salmon|hake|anchov|tuna|mackerel|trout|sea bass|monkfish|pollock|halibut|kipper|worcester|fish sauce|caesar)/i,['fish']],[/\b(peanut|groundnut|satay)/i,['peanuts']],[/\b(almond|hazelnut|walnut|cashew|pecan|pistachio|macadamia|brazil nut|praline|frangipane|marzipan|pesto)/i,['treenuts']],[/\b(soy|soya|tofu|edamame|miso|tamari|tempeh)/i,['soya']],[/\b(milk|butter(?!nut)|cream|cheese|cheddar|parmesan|mozzarella|brie|yoghurt|yogurt|cr[e\xe8]me|ghee|ice cream|custard|butterscotch|toffee|fudge|buttermilk|mascarpone|ricotta|whey)/i,['milk']],[/\b(celery|celeriac|stock cube|beef stock|chicken stock|veg(etable)? stock)/i,['celery']],[/\b(mustard|dijon|vinaigrette|piccalilli)/i,['mustard']],[/\b(sesame|tahini|hummus|houmous)/i,['sesame']],[/\b(wine|vinegar|dried apricot|dried fruit|sulphite|sulfite|prosecco|cider|port\b|sherry|dates?\b|raisin|sultana)/i,['sulphites']],[/\blupin/i,['lupin']]],f=[[/gluten.free|\bgf\b/i,'gluten'],[/dairy.free|vegan (butter|cheese|cream)|oat milk|plant.based/i,'milk'],[/egg.free|vegan mayo/i,'eggs']];function g(n){const r=new Set(n.allergens??[]);for(const[t,i]of u)t.test(n.name)&&i.forEach(t=>r.add(t));for(const[t,i]of f)t.test(n.name)&&!(n.allergens??[]).includes(i)&&r.delete(i);return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}function m(n){const r=new Set(n.flatMap(g));return t.ALLERGENS.map(t=>t.id).filter(t=>r.has(t))}const h=(t,n)=>t.filter(t=>g(t).includes(n)).map(t=>t.name);function p(t){return m(t.ingredients).filter(n=>!t.allergens[n]&&!t.dismissed.includes(n))}const b=t=>t.signOff?'signed-off':'awaiting',y={'signed-off':'Signed off',awaiting:'Awaiting sign-off'};const _=n=>t.ALLERGENS.find(t=>t.id===n)?.short??n,O=(n,r)=>t.ALLERGENS.filter(t=>r?n[t.id]===r:!!n[t.id]).map(t=>t.id),w=['dish','section','price','photo','photos','createdBy','ingredients','steps','allergens','dismissed','allergenNotes'],C=(t,n)=>JSON.stringify(t??null)===JSON.stringify(n??null);const v=t=>'a-mini'===t;const E={menu_item_id:'text',section:'text',price_pence:'integer null',dismissed:'text[]',allergen_notes:'text',allergens_confirmed_by:'text',allergens_confirmed_at:'timestamptz',was_live:'boolean',origin:'text',version:'integer',updated_by:'text'},S='\n',L=(t,n)=>`${t}/${n.id}-v${n.version}.jpg`,j='recipe-photos',P='recipe_cards'},847,[845]); __d(function(g,_r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.quoteDetailsWords=s,e.templatesFor=function(t){const o={...r.DEFAULT_TEMPLATES};for(const n of Object.keys(r.DEFAULT_TEMPLATES)){const u={...r.DEFAULT_TEMPLATES[n],...t?.[n]??{}},c='order'===n?'order':'booking';o[n]={sms:s(u.sms,c),subject:u.subject,body:s(u.body,c)}}return o},e.composeBooking=function(t,o,n,s,c){if(o.walkIn)return[];return u(t,'booking-confirmation'===t?'booking':'booking-request'===t?'request':'declined',(0,r.bookingVars)(o,n),{phone:o.phone,email:o.email,name:o.name},{refType:'booking',refId:o.id,ref:o.ref},n,s,c)},e.composeOrder=function(t,o,n,s){return'takeaway'!==t.type?[]:u('order-confirmation','order',(0,r.orderVars)(t,o),{phone:t.phone,email:t.email,name:t.customerName},{refType:'order',refId:t.id,ref:t.ref},o,n,s)},e.deliverQueued=async function(r,o){if(!(0,t.isLive)())return;const n=(0,t.activeProvider)();for(const t of r){const r=await n.deliver(t);o(t.id,r.ok?{status:'sent'}:{status:'failed',error:r.error})}},e.statusLabel=function(t){const r='sms'===t.channel?'Text':'Email';return'preview'===t.status?`${r}: Ready (preview mode)`:'queued'===t.status?`${r}: Sending\u2026`:'sent'===t.status?`${r} sent`:`${r}: Not sent (failed)`},Object.defineProperty(e,"PREVIEW_BANNER",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);Object.keys(t).forEach(function(r){'default'===r||Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[r]}})});var r=_r(d[1]);Object.keys(r).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return r[t]}})});var o=_r(d[2]);Object.keys(o).forEach(function(t){'default'===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}})});const n=()=>`msg-${Math.random().toString(36).slice(2,8)}${Date.now().toString(36).slice(-4)}`;function s(t,r="booking"){return t.replace(/\bplease quote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))\.?/gi,`Please quote your ${r} details.`).replace(/\bquote (\{ref\}|your (booking |order )?ref(erence)?(?!\w))/gi,`quote your ${r} details`)}function u(o,s,u,c,l,f,m,b){const p=[],y=(0,t.isLive)()?'queued':'preview',v=(0,t.activeProvider)().id;if(c.email?.trim()){const t=(0,r.fillEmailText)(m[s].body,u.email),k=(0,r.fill)(m[s].subject,u.email);p.push({id:n(),restaurantId:f.id,at:b,channel:'email',kind:o,to:c.email.trim(),toName:c.name,subject:k,body:t,html:(0,r.emailHtml)(t,{venue:f.name,preheader:k}),...l,status:y,provider:v})}return p}const c='Preview mode, not sent yet. Connect a text and email service to go live.'},848,[849,850,852]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MESSAGING_CONFIG",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"previewProvider",{enumerable:!0,get:function(){return t}}),_e.relayProvider=n,Object.defineProperty(_e,"isLive",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"activeProvider",{enumerable:!0,get:function(){return s}});const e={mode:'preview',endpoint:'',smsService:'Twilio',emailService:'Postmark',smsSenderId:'ANCHORAGE',fromEmail:'bookings@your-venue.co.uk'},t={id:'preview',label:'Preview mode (nothing is sent)',live:!1,deliver:async()=>({ok:!0})};function n(e){return{id:'relay',label:'Your messaging server',live:!0,deliver:async t=>{try{const n=await fetch(e,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({channel:t.channel,to:t.to,subject:t.subject,body:t.body,html:t.html,ref:t.ref,kind:t.kind,restaurantId:t.restaurantId})});if(!n.ok)return{ok:!1,error:`Server said ${n.status}`};return{ok:!0,providerId:(await n.json().catch(()=>({}))).id}}catch(e){return{ok:!1,error:e?.message??'Network error'}}}}}const o=()=>'live'===e.mode&&!!e.endpoint,s=()=>o()?n(e.endpoint):t},849,[]); __d(function(g,_r,_i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TEMPLATE_LABEL",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"DEFAULT_TEMPLATES",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"PLACEHOLDERS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"teamName",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"longDate",{enumerable:!0,get:function(){return u}}),e.bookingVars=function(n,r){const o=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen).toLowerCase()}`).join(', '),a=n.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),i=`${n.partySize} ${1===n.partySize?'person':'people'}`,s={...c(r),first:l(n.name),name:n.name.trim(),date:u(n.date),time:n.time,covers:i,ref:n.ref};return{sms:{...s,allergy:n.allergies.length?` We\u2019ve noted the allergy (${o}) and the team will check it with you when you arrive.`:'',note:'',details:''},email:{...s,allergy:n.allergies.length?`Thank you for telling us about: ${a}. Our team will go through this with you when you arrive, and every dish for your table is checked at each step, from the kitchen to your table.`:'',note:n.notes.trim()?`Your note to us: "${n.notes.trim()}". We\u2019ll make sure the team sees it.`:'',details:[`Date: ${u(n.date)}`,`Time: ${n.time}`,`Table for: ${i}`,`Reference: ${n.ref}`].join('\n')}}},e.orderVars=function(r,o){const a=r.lines.reduce((t,n)=>t+n.qty,0),i=r.readyBy??r.slotTime,s=i?`at ${m(i)}`:'time to be confirmed',d=r.allergies.map(n=>(0,t.allergenLabel)(n.allergen).toLowerCase()).join(', '),u=r.allergies.map(n=>`${(0,t.allergenLabel)(n.allergen)} (${(0,t.severityLabel)(n.severity).toLowerCase()})`).join(', '),y={...c(o),first:l(r.customerName),name:r.customerName,ref:r.ref,items:`${a} ${1===a?'item':'items'}`,total:(0,n.gbp)(r.total),collect:s,date:'',time:i?m(i):'',covers:''};return{sms:{...y,allergy:r.allergies.length?` We\u2019ve noted your allergy (${d}); the kitchen checks every item.`:'',itemList:'',details:'',note:''},email:{...y,allergy:r.allergies.length?`You told us about: ${u}. The kitchen signs off every item against it before your order leaves the pass.`:'',itemList:r.lines.map(t=>`${t.qty} \xd7 ${t.name}${t.choices.length?` (${t.choices.join(', ')})`:''}`).join('\n'),details:[`Order: ${r.ref}`,`Collection: ${i?m(i):'time to be confirmed'}`,`Items: ${a}`,`Total: ${(0,n.gbp)(r.total)}`].join('\n'),note:''}}},e.fill=y,Object.defineProperty(e,"fillEmailText",{enumerable:!0,get:function(){return h}}),e.emailHtml=function(t,n){const r=n.accent??'#B8893E',o=t.split(/\n{2,}/).map(t=>{const n=t.split('\n');return n.length>1&&n.every(t=>/^[^:]{2,22}:\s.+/.test(t))?`${n.map(t=>{const n=t.indexOf(':');return``}).join('')}
${p(t.slice(0,n))}${p(t.slice(n+1).trim())}
`:n.length>1&&n.every(t=>/^\d+ \xd7/.test(t))?`
    ${n.map(t=>`
  • ${p(t)}
  • `).join('')}
`:`

${n.map(p).join('
')}

`}).join('');return`${p(n.preheader??'')}
${p(n.venue.toUpperCase())}
${o}
You\u2019re getting this because you made a booking or order with ${p(n.venue)}. It\u2019s about your booking only, not marketing.
`},e.smsParts=function(t){const n=b(t),r=!f.test(n),o=n.length,a=r?o<=70?1:Math.ceil(o/67):o<=160?1:Math.ceil(o/153);return{chars:o,parts:a,unicode:r}},Object.defineProperty(e,"toGsm",{enumerable:!0,get:function(){return b}});var t=_r(_d[0]),n=_r(_d[1]);const r={booking:{title:'Booking confirmed',when:'Every booking: online, phone or in person (and when you confirm a request)'},request:{title:'Booking request received',when:'Online bookings that need you to confirm them first'},declined:{title:'Booking request declined',when:'When you decline a booking request'},order:{title:'Takeaway order confirmed',when:'Every takeaway order from the app (and phone orders with a number)'}},o={booking:{sms:'Hi {first}, you\u2019re booked in at {venue}: {date} at {time}, {covers}. Ref {ref}.{allergy} Need to change or cancel? Just call {venuePhone}. See you soon, {team}',subject:'You\u2019re booked in at {venue}: {date} at {time}',body:'Hi {first},\n\nThank you for booking with us. We\u2019re really looking forward to welcoming you.\n\n{details}\n\n{allergy}\n\n{note}\n\nNeed to change or cancel? Use the link in this email, or call us on {venuePhone} and quote your booking details.\n\nYou\u2019ll find us at {address}.\n\nWarm wishes,\n{team}'},request:{sms:'Hi {first}, thanks for your booking request at {venue} for {date} at {time}, {covers}. CoverCharge will email you shortly to confirm. Ref {ref}. Questions? Call {venuePhone}. {team}',subject:'We\u2019ve got your booking request for {date}',body:'Hi {first},\n\nThank you for your booking request. A member of the team will look at it and confirm with you very shortly.\n\n{details}\n\n{allergy}\n\n{note}\n\nIf you have any questions in the meantime, call us on {venuePhone} and quote your booking details.\n\nWarm wishes,\n{team}'},declined:{sms:'Hi {first}, we\u2019re so sorry, we can\u2019t fit {covers} in on {date} at {time}. Please call {venuePhone} and we\u2019ll do our best to find another time. {team}',subject:'About your booking request for {date}',body:'Hi {first},\n\nThank you for asking to book with us. We\u2019re really sorry, but we can\u2019t fit your party in on {date} at {time}.\n\nWe\u2019d love to find another time that works. Give us a ring on {venuePhone} and we\u2019ll do our best.\n\nWith apologies and warm wishes,\n{team}'},order:{sms:'Hi {first}, thanks for your order {ref} from {venue}: {items}, {total}. Collection {collect}.{allergy} Questions? Call {venuePhone}. {team}',subject:'Your {venue} order {ref}',body:'Hi {first},\n\nThank you for your order. The kitchen has it and we\u2019ll have it ready for you.\n\n{details}\n\n{itemList}\n\n{allergy}\n\nAny questions? Call us on {venuePhone} and quote your order details.\n\nYou\u2019ll find us at {address}.\n\nEnjoy!\n{team}'}},a=[{key:'first',what:'Guest\u2019s first name'},{key:'name',what:'Name on the booking'},{key:'venue',what:'Venue name'},{key:'date',what:'Day and date'},{key:'time',what:'Time'},{key:'covers',what:'e.g. 4 people'},{key:'ref',what:'Reference'},{key:'venuePhone',what:'Venue phone'},{key:'address',what:'Venue address'},{key:'team',what:'e.g. The Anchorage team'},{key:'allergy',what:'Allergy reassurance (only if one was noted)'},{key:'note',what:'Their note (email only)'},{key:'details',what:'Details box (email only)'},{key:'items',what:'Orders: e.g. 3 items'},{key:'total',what:'Orders: total'},{key:'collect',what:'Orders: collection time'},{key:'itemList',what:'Orders: list of items (email)'}],i=t=>/^the\s/i.test(t.trim())?`${t.trim()} team`:`The ${t.trim()} team`,l=t=>t.trim().replace(/^(mr|mrs|ms|miss|dr)\.?\s+/i,'').split(/\s+/)[0]||'there',s=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d=['January','February','March','April','May','June','July','August','September','October','November','December'],u=t=>{const[n,r,o]=t.split('-').map(Number),a=new Date(n,r-1,o,12);return`${s[a.getDay()]} ${o} ${d[r-1]}`},m=t=>{const n=new Date(t);return`${String(n.getHours()).padStart(2,'0')}:${String(n.getMinutes()).padStart(2,'0')}`};function c(t){return{venue:t.name,venuePhone:t.phone||'the restaurant',address:t.address||t.location,team:i(t.name)}}function y(t,n){return t.replace(/\{(\w+)\}/g,(t,r)=>r in n?n[r]:t).replace(/[ \t]{2,}/g,' ').replace(/ +([.,])/g,'$1').trim()}const h=(t,n)=>y(t,n).split(/\n{2,}/).map(t=>t.trim()).filter(Boolean).join('\n\n'),p=t=>t.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');const f=/^[A-Za-z0-9 \r\n@\xa3$\xa5\xe8\xe9\xf9\xec\xf2\xc7\xd8\xf8\xc5\xe5\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\xc6\xe6\xdf\xc9!"#\xa4%&'()*+,\-./:;<=>?\xa1\xc4\xd6\xd1\xdc\xa7\xbf\xe4\xf6\xf1\xfc\xe0^{}\\[~\]|\u20ac]*$/;const b=t=>t.replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,'-').replace(/\u2026/g,'...').replace(/\xd7/g,'x')},850,[845,851]); @@ -948,7 +948,7 @@ __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule', __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"shallow",{enumerable:!0,get:function(){return c}});const t=t=>Symbol.iterator in t,n=t=>"entries"in t,o=(t,n)=>{const o=t instanceof Map?t:new Map(t.entries()),s=n instanceof Map?n:new Map(n.entries());if(o.size!==s.size)return!1;for(const[t,n]of o)if(!s.has(t)||!Object.is(n,s.get(t)))return!1;return!0},s=(t,n)=>{const o=t[Symbol.iterator](),s=n[Symbol.iterator]();let c=o.next(),u=s.next();for(;!c.done&&!u.done;){if(!Object.is(c.value,u.value))return!1;c=o.next(),u=s.next()}return!!c.done&&!!u.done};function c(c,u){return!!Object.is(c,u)||"object"==typeof c&&null!==c&&"object"==typeof u&&null!==u&&(Object.getPrototypeOf(c)===Object.getPrototypeOf(u)&&(t(c)&&t(u)?n(c)&&n(u)?o(c,u):s(c,u):o({entries:()=>Object.entries(c)},{entries:()=>Object.entries(u)})))}},865,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"orderAtTableOn",{enumerable:!0,get:function(){return t}});const t=t=>!!t&&(t.settings.orderAtTable??!0)},866,[]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setRecipeCardRepository=function(n){t=n,r.forEach(t=>t())},e.recipeCards=function(){if(!t)throw new Error('Recipe card repository not set up');return t},Object.defineProperty(e,"hasRecipeCards",{enumerable:!0,get:function(){return n}}),e.onRepositorySwap=function(t){return r.add(t),()=>{r.delete(t)}};let t=null;const r=new Set;const n=()=>!!t},867,[]); -__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){V=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return $}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return M}}),_e.ensureCards=F;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const I='covercharge-recipecards-v1',y='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:I,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:y,storage:(0,l.createJSONStorage)(()=>v),version:1})),_={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let A=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(A++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,D=null;function U(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!D||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);D={cards:r,byRid:t,byItem:n}}return D}const N=[];function R(e){if(!(0,f.canEditCards)(e.role))throw new Error('Only the head chef and managers can edit recipe cards.')}let V=null;const $=e=>E.getState().photos[e],M={mode:'local',list:e=>U().byRid.get(e)??N,get:e=>U().cards.find(t=>t.id===e),byMenuItem:e=>U().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){R(r);const n=O().toISOString();k=!0;let s=t.menuItemId;try{s||(s=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const a=(0,f.cardPhotos)(t),o=t.createdBy?.trim()||r.name,c={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:s,dish:t.dish,section:t.section,price:t.price,photo:a[0],photos:a,createdBy:o,createdByRole:t.createdByRole??(o===r.name?r.role:void 0),ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:n,updatedAt:n,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==c.menuItemId),c]})),B(c,r.name,'card created, awaiting sign-off'),c}finally{k=!1}},async update(e,t,r){R(r);const n=M.get(e);if(!n)throw new Error('Card not found');const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=M.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){R(t);const r=M.get(e);r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return _[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=V?.(e);return r?{uri:r}:null}};let k=!1,j=!1;function F(){if(k)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>U().byItem.get(e),menuItemAdded:e=>{if(k||!j)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=U().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=U().byItem.get(e);r&&M.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(M);const x=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([x(S.useStore.persist),x(w.persist)]).then(()=>{j=!0,F(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&F()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(I)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(y)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); +__d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"useCardStore",{enumerable:!0,get:function(){return w}}),Object.defineProperty(_e,"photoStorageFull",{enumerable:!0,get:function(){return C}}),_e.setStoragePhotoResolver=function(e){$=e},_e.cachePhotoAs=function(e,t){if(E.getState().photos[e]===t)return;E.setState(r=>({photos:{...r.photos,[e]:t}}))},Object.defineProperty(_e,"readLocalPhoto",{enumerable:!0,get:function(){return M}}),Object.defineProperty(_e,"localRecipeCards",{enumerable:!0,get:function(){return k}}),_e.ensureCards=x;var e,t=_r(d[0]),r=_r(d[1]),n=_r(d[2]),s=_r(d[3]),a=_r(d[4]),o=_r(d[5]),c=(e=o)&&e.__esModule?e:{default:e};_r(d[6]);var u=_r(d[7]),l=_r(d[8]),f=_r(d[9]),m=_r(d[10]),h=_r(d[11]),p=_r(d[12]),S=_r(d[13]);const y='covercharge-recipecards-v1',I='covercharge-recipephotos-v1',O=()=>{try{return(0,S.nowFrom)(S.useStore.getState().clock)}catch{return new Date}},w=(0,u.create)()((0,l.persist)(()=>({cards:[],removed:[],log:[]}),{name:y,storage:(0,l.createJSONStorage)(()=>c.default),version:3,migrate:async e=>{const n=e;return t.LIVE_VENUE_BUILD?(await(0,r.archiveChefCache)('recipe-cards',n),{...n,cards:n.cards.filter(e=>!(0,s.isDemoCard)(e)),log:n.log.filter(e=>!(0,s.demoActor)(e.by))}):n}}));let b=!1;const v={getItem:e=>c.default.getItem(e),setItem:async(e,t)=>{try{await c.default.setItem(e,t),b=!1}catch{b=!0}},removeItem:e=>c.default.removeItem(e)},C=()=>b,E=(0,u.create)()((0,l.persist)(()=>({photos:{}}),{name:I,storage:(0,l.createJSONStorage)(()=>v),version:1})),A={lobster:_r(d[14]),skink:_r(d[15]),fishsupper:_r(d[16]),moules:_r(d[17]),stp:_r(d[18])};let _=0;const B=(e,t,r,n=t)=>{const s={id:`cl-${Date.now().toString(36)}${(_++).toString(36)}`,cardId:e.id,rid:e.restaurantId,at:O().toISOString(),by:t,text:n===t?r:`${r} (${n})`};w.setState(e=>({log:[s,...e.log].slice(0,300)}));try{S.useStore.getState().addAudit(e.restaurantId,'menu',`Recipe card: ${e.dish}: ${r} (${n})`)}catch{}},L=e=>w.setState(t=>({cards:t.cards.some(t=>t.id===e.id)?t.cards.map(t=>t.id===e.id?e:t):[...t.cards,e]}));let P=null,R=null;function D(){const e=w.getState().cards,r=t.LIVE_VENUE_BUILD?e.filter(e=>!(0,s.isDemoCard)(e)).map(e=>({...e,signOff:(0,s.demoActor)(e.signOff?.by)?null:e.signOff,allergensConfirmed:(0,s.demoActor)(e.allergensConfirmed?.by)?void 0:e.allergensConfirmed})):e;if(!R||P!==e){P=e;const t=new Map,n=new Map;for(const e of r)t.set(e.restaurantId,[...t.get(e.restaurantId)??[],e]),n.set(e.menuItemId,e);R={cards:r,byRid:t,byItem:n}}return R}const U=[];function N(e,t){if(!((0,f.canEditCards)(e.role)||e.ownRef&&(void 0===t?(0,f.mayCreateCard)(e):(0,f.mayEditCard)(e,t))))throw new Error(e.ownRef?'You can only change recipe cards you created.':'Only the head chef and managers can edit recipe cards.')}const V=e=>!(0,f.canEditCards)(e.role)&&!!e.ownRef;let $=null;const M=e=>E.getState().photos[e],k={mode:'local',list:e=>D().byRid.get(e)??U,get:e=>D().cards.find(t=>t.id===e),byMenuItem:e=>D().byItem.get(e),subscribe:e=>{const t=w.subscribe(e),r=E.subscribe(e);return()=>{t(),r()}},async create(e,t,r){N(r);const n=V(r),s=O().toISOString();j=!0;let a=t.menuItemId;try{a||(a=S.useStore.getState().addMenuItem({restaurantId:e,section:t.section,name:t.dish,description:t.description??'',price:t.price,dietary:[],allergens:t.allergens??{},prepMins:12,soldOut:!1,signOff:null}));const o=(0,f.cardPhotos)(t),c=n?r.name:t.createdBy?.trim()||r.name,u={id:t.id??(0,f.uuid)(),restaurantId:e,menuItemId:a,dish:t.dish,section:t.section,price:t.price,photo:o[0],photos:o,createdBy:c,createdByRole:n?'staff':t.createdByRole??(c===r.name?r.role:void 0),...n?{authorRef:r.ownRef}:{},ingredients:t.ingredients??[],steps:t.steps??[],allergens:t.allergens??{},dismissed:t.dismissed??[],allergenNotes:t.allergenNotes,signOff:null,wasLive:!1,origin:'new',version:1,createdAt:s,updatedAt:s,updatedBy:r.name};return w.setState(e=>({cards:[...e.cards.filter(e=>e.menuItemId!==u.menuItemId),u]})),B(u,r.name,'card created, awaiting sign-off'),u}finally{j=!1}},async update(e,t,r){const n=k.get(e);if(N(r,n??null),!n)throw new Error('Card not found');if(V(r)){const{createdBy:e,confirmAllergens:r,...n}=t;t=n}const s=(0,f.editCard)(n,t,r.name,O().toISOString());return s.changed&&(L(s.card),B(s.card,r.name,s.resetSignOff?'edited, sign-off reset to Awaiting sign-off':t.confirmAllergens&&1===Object.keys(t).length?'allergens confirmed':'edited')),s.card},async signOff(e,t){const r=k.get(e);if(!r)throw new Error('Card not found');if(!(0,f.maySignOff)(t,r))throw new Error('Only the Head Chef, an owner or a manager can sign it off.');const n=(0,f.signOffBlock)(r);if(n)throw new Error(n);const s=(0,f.signOffCard)(r,t.name,O().toISOString());return L(s),B(s,t.name,'signed off',(0,f.signerLabel)(t)),s},async remove(e,t){const r=k.get(e);N(t,r??null),r&&(w.setState(t=>({cards:t.cards.filter(t=>t.id!==e),removed:[...t.removed,r.menuItemId]})),S.useStore.setState(e=>({menu:e.menu.map(e=>e.id===r.menuItemId?{...e,hidden:!0}:e)})),B(r,t.name,'card removed (dish hidden from the menu)'))},async savePhoto(e,t,r){const n=`local:${t}:${Date.now().toString(36)}`;return E.setState(e=>({photos:{...e.photos,[n]:r.dataUrl}})),n},photoSource(e){if(!e)return null;if(e.startsWith('asset:'))return A[e.slice(6)]??null;if(e.startsWith('local:')){const t=E.getState().photos[e];return t?{uri:t}:null}if(/^(https?:|data:)/.test(e))return{uri:e};const t=E.getState().photos[e];if(t)return{uri:t};const r=$?.(e);return r?{uri:r}:null}};let j=!1,F=!1;function x(){if(j)return;const e=S.useStore.getState().menu,{cards:r,removed:o}=w.getState(),c=new Set(r.map(e=>e.menuItemId)),u=e.filter(e=>!c.has(e.id)&&!o.includes(e.id)),l=O().toISOString();if(r.some(e=>(0,s.isPlaceholderCard)(e))&&w.setState(e=>({cards:e.cards.filter(e=>!(0,s.isPlaceholderCard)(e))})),!u.length)return;const f=a.IS_ISOLATED_VENUE||t.LIVE_VENUE_BUILD||!(0,n.examplesAllowed)()?[]:(0,p.exampleCards)(u),m=new Set(f.map(e=>e.menuItemId)),h=[...f,...u.filter(e=>!m.has(e.id)).map(e=>(0,p.importedCard)(t.LIVE_VENUE_BUILD&&(0,s.demoActor)(e.signOff?.by)?{...e,signOff:null}:e,l))];w.setState(e=>({cards:[...e.cards,...h]}))}(0,h.setMenuCardBridge)({cardFor:e=>D().byItem.get(e),menuItemAdded:e=>{if(j||!F)return;const t=O().toISOString(),r={...(0,p.importedCard)(e,t),id:(0,f.uuid)(),signOff:null,allergensConfirmed:void 0,wasLive:!1,origin:'new',updatedBy:'Added to the menu'};L(r),B(r,r.updatedBy,'card created from the menu, awaiting sign-off')},menuEdited:(e,t,r,n)=>{const s=D().byItem.get(e);if(!s)return;let a=(0,f.editCard)(s,t,r,O().toISOString()).card;n&&a.signOff&&(a={...a,signOff:null,version:a.version+1,updatedAt:O().toISOString(),updatedBy:r}),a!==s&&(L(a),B(a,r,s.signOff&&!a.signOff?'edited from the menu, sign-off reset':'edited from the menu'))},signOff:(e,t)=>{const r=D().byItem.get(e);r&&k.signOff(r.id,{name:t,role:'head-chef'}).catch(()=>{})}}),(0,m.setRecipeCardRepository)(k);const H=e=>new Promise(t=>{e.hasHydrated()?t():e.onFinishHydration(()=>t())});Promise.all([H(S.useStore.persist),H(w.persist)]).then(()=>{F=!0,x(),S.useStore.subscribe((e,t)=>{e.menu!==t.menu&&x()})}),'undefined'!=typeof window&&window.addEventListener('storage',e=>{e.key===(0,a.venueKey)(y)&&w.persist.rehydrate(),e.key===(0,a.venueKey)(I)&&E.persist.rehydrate()})},868,[822,823,869,820,805,824,219,831,834,847,867,846,870,816,871,872,873,874,875]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setLiveData=c,e.requireRealData=function(){t=!0,c(!0)},Object.defineProperty(e,"liveData",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"examplesAllowed",{enumerable:!0,get:function(){return l}}),e.onDataModeChange=function(n){return s.add(n),()=>{s.delete(n)}},Object.defineProperty(e,"EXAMPLE_LABEL",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"notEnoughTip",{enumerable:!0,get:function(){return b}});const n=['anchorage','souters','kirkmichael','wildings','kirkton','abbotsford','greenside',"3idiots","cecchinis","mrbasrais","yasmins","williewastles","rupeeroom","smokinggoat","pizzaioli","drunkencoo"].includes("anchorage");let t=n,o=n;const s=new Set;function c(n){o!==(n=t||n)&&(o=n,s.forEach(n=>n()))}const u=()=>o,l=()=>!o;const f='Example figures',b=n=>`Forecasts start once CoverCharge has ${1===n?'1 week':`${n} weeks`} of your bookings and cash-ups.`},869,[]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"EXAMPLE_TAG",{enumerable:!0,get:function(){return t}}),_e.exampleCards=function(t){return l.flatMap(l=>{const h=t.find(e=>e.id===l.menuItemId);if(!h)return[];return[{id:(0,e.uuidFrom)(`card:${h.restaurantId}:${h.id}`),restaurantId:h.restaurantId,menuItemId:h.id,dish:h.name,section:h.section,price:h.price,photo:l.photo,ingredients:o(l.menuItemId,l.ings),steps:l.steps,allergens:l.allergens,dismissed:l.dismissed??[],allergenNotes:l.notes,allergensConfirmed:{by:s.by,at:s.at},signOff:l.awaiting?null:s,wasLive:!0,origin:'example',version:l.awaiting?2:1,createdAt:n,updatedAt:l.awaiting?'2026-10-28T15:20:00.000Z':n,updatedBy:l.awaiting?'Example edit (demo)':s.by}]})},_e.importedCard=function(t,s){return{id:(0,e.uuidFrom)(`card:${t.restaurantId}:${t.id}`),restaurantId:t.restaurantId,menuItemId:t.id,dish:t.name,section:t.section,price:t.price,ingredients:[],steps:[],allergens:{...t.allergens},dismissed:[],allergenNotes:t.allergenNotes,allergensConfirmed:t.signOff?{by:t.signOff.by,at:t.signOff.at}:void 0,signOff:t.signOff?{by:t.signOff.by,at:t.signOff.at}:null,wasLive:!t.hidden||!!t.signOff,origin:'imported',version:1,createdAt:s,updatedAt:s,updatedBy:'Imported from the menu'}};var e=r(d[0]);const t='Example data',s={by:'Example sign-off (demo)',at:'2026-10-26T10:00:00.000Z'},n='2026-10-26T09:00:00.000Z',o=(e,t)=>t.map(([t,s,n],o)=>({id:`${e}-i${o}`,qty:t,unit:s,name:n})),l=[{menuItemId:'a-lobster',photo:'asset:lobster',ings:[['1','whole','Live Dunure lobster (c. 600 g, Kitty Fisher)'],['60','g','Garlic butter'],['\xbd','','Lemon, charred'],['60','g','Mixed leaves, cucumber and red onion'],['15','ml','House vinaigrette (Dijon mustard)'],['200','g','Triple-cooked chips']],steps:['Chill the lobster for 20 minutes, then dispatch humanely and split lengthways. Remove the stomach sac and the intestinal tract.','Crack the claws. Season the flesh and spoon over half the garlic butter.','Grill flesh side up for 6\u20138 minutes until just opaque; baste with the rest of the butter.','Char the lemon on the grill. Dress the salad at the pass.','Plate on the long board: lobster, claws alongside, salad, chips in the cone, lemon and a pot of the pan butter.'],allergens:{crustaceans:'contains',milk:'contains',mustard:'contains',gluten:'may',fish:'may'},notes:'Chips are cooked in a shared fryer (gluten, fish, crustaceans may be present).'},{menuItemId:'a-skink',photo:'asset:skink',ings:[['120','g','Smoked haddock, undyed'],['200','ml','Whole milk'],['20','g','Butter'],['60','g','Leek, sliced'],['40','g','Onion, diced'],['120','g','Floury potato, diced'],['1','tbsp','Parsley, chopped'],['1','slice','Crusty bread'],['10','g','Butter (portion)']],steps:['Poach the haddock in the milk for 5 minutes. Lift out, flake and keep the milk.','Sweat the leek and onion in the butter until soft, with no colour.','Add the potato and the poaching milk; simmer for 15 minutes until the potato breaks down.','Crush a third of the potato for body, return the haddock and season with pepper.','Serve in the warm bowl, parsley on top, bread and butter on the side.'],allergens:{fish:'contains',milk:'contains',gluten:'contains'}},{menuItemId:'a-fishsupper',photo:'asset:fishsupper',ings:[['200','g','Haddock fillet, locally landed'],['80','g','Self-raising flour'],['100','ml','Beer (lager)'],['250','g','Triple-cooked chips'],['80','g','Garden peas'],['10','g','Butter'],['40','g','Tartare sauce (mayonnaise, capers, gherkins)'],['\xbc','','Lemon']],steps:['Whisk the flour and cold beer to a thick batter; rest for 10 minutes.','Dust the haddock in flour, dip in the batter and lower into the fryer at 180 \xb0C for 5\u20136 minutes.','Fry the chips at 190 \xb0C until golden.','Warm the peas with the butter.','Plate the fish on the chips, peas in the ramekin, tartare and lemon on the side.'],allergens:{fish:'contains',gluten:'contains',eggs:'contains',milk:'contains',mustard:'may',crustaceans:'may',sulphites:'may'},notes:'Shared fryer. Tartare is made with mayonnaise (egg, may contain mustard). The beer in the batter may contain sulphites.'},{menuItemId:'a-moules',photo:'asset:moules',ings:[['500','g','Scottish rope mussels, cleaned'],['30','g','Butter'],['1','','Shallot, finely diced'],['2','cloves','Garlic, sliced'],['100','ml','Dry white wine'],['60','ml','Double cream'],['1','tbsp','Parsley, chopped'],['2','slices','Crusty bread']],steps:['Check every mussel: discard any that are cracked or stay open when tapped.','Sweat the shallot and garlic in the butter for 2 minutes.','Add the mussels and wine, cover and steam on a high heat for 3\u20134 minutes until they open.','Discard any that stay shut. Stir in the cream and parsley.','Serve in the deep bowl with the bread and an empty-shell bowl.'],allergens:{molluscs:'contains',milk:'contains',sulphites:'contains',gluten:'contains'}},{menuItemId:'a-stp',photo:'asset:stp',awaiting:!0,ings:[['30','g','Medjool dates, chopped'],['40','ml','Boiling water'],['25','g','Butter'],['30','g','Dark muscovado sugar'],['1','','Egg (\xbd per portion)'],['35','g','Self-raising flour'],['60','ml','Butterscotch sauce (butter, cream, brown sugar)']],steps:['Soak the dates in the boiling water for 10 minutes, then blitz.','Cream the butter and sugar, beat in the egg, fold in the flour and the dates.','Steam in buttered moulds for 35 minutes.','Warm the butterscotch sauce.','Turn out, pour over the sauce and serve with the guest\u2019s choice of custard, ice cream or cream.'],allergens:{gluten:'contains',milk:'contains',eggs:'contains',sulphites:'may'},notes:'Dried dates may contain sulphites. Accompaniments are chosen at order (see the dish options).'}]},870,[847]); __d(function(g,r,i,a,m,e,d){"use strict";m.exports={uri:"/staff-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg",width:800,height:600,toString(){return this.uri}}},871,[]); @@ -979,7 +979,7 @@ __d(function(g,r,_i,_a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModul __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"KG_PER_STONE",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"HALF_STONE_KG",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"isFishName",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"fishInStone",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"halfStone",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"toStone",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"fromStone",{enumerable:!0,get:function(){return c}}),e.stoneText=b,e.stoneSpeech=h,Object.defineProperty(e,"fishQtyText",{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,"fishQtySpeech",{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,"quantityStep",{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,"stepQuantity",{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,"inputQuantity",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"quantityUnit",{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,"displayedCost",{enumerable:!0,get:function(){return k}}),e.parseStoneAmount=function(t){if('number'==typeof t)return Number.isFinite(t)?t:void 0;const n=t.toLowerCase().trim();if(/\b(?:kg|kilos?|kilograms?|grams?)\b/.test(n))return;const i=n.match(/(?:^|\s)(\d+(?:[.,]\d+)?)(\xbd)?(?:\s*(?:stone|st)\b|$)/);if(i)return Number(i[1].replace(',','.'))+(i[2]?.5:0);const o=n.match(/\b(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)(?: and a half)?(?: stone| st|$)/);return o?l.indexOf(o[1])+(/and a half/.test(o[0])?.5:0):/(?:^|\s)(?:\xbd|(?:a )?half(?: a)?)(?: stone| st|$)/.test(n)?.5:void 0};var t=r(d[0]);const n=6.35029318,i=3.17514659,o=(t="")=>!/\b(?:vegan|vegetarian|banana|blossom|mushroom|sauce|stock|oil)\b|\(vg\)/i.test(t)&&/\b(?:fish|haddock|salmon|cod|hake|halibut|plaice|sole|turbot|trout|mackerel|monkfish|seabass|sea bass|seabream|sea bream|tuna|pollock|coley|whiting|sardines?|anchov(?:y|ies)|herring)\b/i.test(t),u=(n,i)=>(0,t.isAnchorage)(n)&&/^(kg|kilos?|kilograms?|st|stone)$/i.test(i.unit||'')&&o(i.name),s=t=>Math.round(2*(t+Number.EPSILON))/2,f=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t/n,c=(t,i="kg")=>/^(st|stone)$/i.test(i)?t:t*n;function b(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'\u2212':''}${n%1?`${i||''}\xbd`:i} stone`}const l=['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'];function h(t){const n=s(Math.abs(t)),i=Math.floor(n);return`${t<0&&n?'minus ':''}${n%1?i?`${l[i]||i} and a half`:'half a':l[i]||i} stone`}const y=(t,n,i)=>u(t,n)?b(f(i,n.unit)):`${i} ${n.unit||''}`.trim(),p=(t,n,i)=>u(t,n)?h(f(i,n.unit)):y(t,n,i),O=(t,n)=>u(t,n)?c(.5,n.unit):'kg'===n.unit?.5:1,v=(t,n,i,o)=>u(t,n)?c(Math.max(0,s(f(i,n.unit))+.5*o),n.unit):Math.max(0,i+o*O(t,n)),P=(t,n,i)=>u(t,n)?c(s(i),n.unit):i,j=(t,n)=>u(t,n)?'stone':n.unit||'',k=(t,n,i)=>u(t,n)?i*c(1,n.unit):i},896,[820]); __d(function(g,r,_i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"ANCHORAGE_STOCK",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"stockKey",{enumerable:!0,get:function(){return n}}),_e.countsOf=function(e,t=[],n={}){const u={...n};for(const e of t)u[e.key]=u[e.key]??0;for(const t of e)u[t.kind]=(u[t.kind]??0)+t.delta;const i=new Map(t.map(e=>[e.key,e]));return Object.fromEntries(Object.entries(u).map(([e,t])=>[e,o(i.get(e),t)]))},_e.lastUndoable=function(e){const t=new Set(e.filter(e=>e.undoes).map(e=>e.undoes));return e.find(e=>'undo'!==e.reason&&'count'!==e.reason&&!t.has(e.id))},Object.defineProperty(_e,"fmtCount",{enumerable:!0,get:function(){return u}}),Object.defineProperty(_e,"fmtStockCount",{enumerable:!0,get:function(){return i}}),Object.defineProperty(_e,"speakStockCount",{enumerable:!0,get:function(){return s}}),Object.defineProperty(_e,"isLowItem",{enumerable:!0,get:function(){return c}}),_e.describe=function(e,t){const n=(t?.name??e.kind).toLowerCase(),o=(t?.plural??`${e.kind}s`).toLowerCase(),s=t?i(e.rid,t,Math.abs(e.delta)):u(Math.abs(e.delta));return'delivery'===e.reason?`Delivery in: +${s} ${1===Math.abs(e.delta)?n:o}`:'sold-half'===e.reason?`Sold: half ${n}`:'sold'===e.reason?`Sold: ${s} ${1===Math.abs(e.delta)?n:o}`:'undo'===e.reason?`Undo (${e.delta>0?'+':'\u2212'}${s} ${n})`:`Count: ${s} ${o}`},Object.defineProperty(_e,"isRoastItem",{enumerable:!0,get:function(){return l}}),_e.isSundayIn=function(e,t="Europe/London"){try{return'Sun'===new Intl.DateTimeFormat('en-GB',{weekday:'short',timeZone:t}).format(e)}catch{return 0===e.getDay()}};var e=r(_d[0]);const t=[{key:'lobster',name:'Lobster',plural:'Lobsters',unit:'half',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd9e',sort:1,active:!0},{key:'crab',name:'Crab',plural:'Crabs',unit:'whole',lowAt:4,supplierId:'os-kittyfisher',icon:'\ud83e\udd80',sort:2,active:!0}],n=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'item',o=(e,t)=>Math.max(0,'kg'===e?.unit?t:'half'===e?.unit?Math.round(2*t)/2:Math.round(t));const u=e=>{const t=Math.floor(e);return e-t>=.5?t?`${t}\xbd`:'\xbd':String(t)},i=(t,n,o)=>'kg'===n.unit?(0,e.fishQtyText)(t,n,o):u(o),s=(t,n,o)=>'kg'===n.unit?(0,e.fishQtySpeech)(t,n,o):u(o),c=(e,t)=>t<=(e?.lowAt??4);const l=e=>'roast'===e.group},897,[896]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.useLiveState=function(){const e=(0,s.useSync)(e=>e.mode),n=(0,s.useSync)(e=>e.venueId),o=(0,s.useSync)(e=>e.lastSyncAt);return c.PITCH||n&&o?'ready':'signin'===e||'local'===e||'off'===e||'unpaired'===e?'nolink':'offline'===e?'offline':'connecting'},_e.LiveWait=function({state:n,title:o,testID:s}){const c=e.IS_CAR?b[n]:'nolink'===n&&'display'===e.APP_VARIANT?p:f[n];return(0,h.jsxs)(t.default,{testID:s,accessible:!0,accessibilityLabel:`${o}: ${c}`,style:{borderRadius:16,borderWidth:1,borderColor:l.colours.border,backgroundColor:l.colours.surface,padding:14,gap:4},children:[(0,h.jsx)(u.T,{size:12,weight:"semibold",colour:l.colours.goldMuted,children:o.toUpperCase()}),(0,h.jsx)(u.T,{size:18,weight:"semibold",children:c})]})};var e=r(d[0]);r(d[1]);var n,o=r(d[2]),t=(n=o)&&n.__esModule?n:{default:n},s=r(d[3]),c=r(d[4]),l=r(d[5]),u=r(d[6]),h=r(d[7]);const f={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when this phone is back online.',nolink:'Not connected to the venue. Open your personal link from your manager on this phone to see live numbers.'},p="This Display isn't paired yet. Tap Not paired to pair it.",b={connecting:'Connecting\u2026',offline:'No connection. The live numbers show again when the car is back online.',nolink:'Not connected yet. Check the car has internet. If this stays, sign the car in again from Managers on your phone.'}},898,[856,17,85,899,880,804,777,8]); -__d(function(e,t,a,s,n,i,r){"use strict";Object.defineProperty(i,'__esModule',{value:!0}),Object.defineProperty(i,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(i,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(i,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(i,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(i,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(i,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(i,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(i,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(i,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(i,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(i,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(i,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(i,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Ut}}),i.rotaReconcile=Tt,i.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Gt(e,t,a)},i.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},i.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const i=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...bt(i)}:t)})),{ok:!0,role:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:i}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(i)return{ok:!1,message:i.message};const r=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:r}:e)})),{ok:!0,until:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},i.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},i.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},i.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(va.setState({live:!!a,known:!0}),{ok:!0})},i.readPushLive=ha,i.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},i.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(i,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return Sa}}),i.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:i}=await Te().storage.from(Sa).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return i?{ok:!1,message:i.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.orderLogoUrl=async function(e){const t=wa.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(Sa).createSignedUrl(e,3600);if(t?.signedUrl)return wa.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},i.removeOrderLogo=async function(e){try{await Te().storage.from(Sa).remove([e])}catch{}},Object.defineProperty(i,"usePushLive",{enumerable:!0,get:function(){return va}}),i.claimInvite=Ka,i.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},i.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),Be&&Ha(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},i.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Da)}catch{}},i.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const i=n?.error;return'not_display'===i||'not_kitchen'===i||'not_kitchen_role'===i||'missing'===i?{ok:!1,error:i}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},i.signedInHereAs=async function(e){qe();const t=await L.kv.get(Da,null);return!!t&&'staff'===t.kind&&t.staffRef===e},i.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ua,null)===e},i.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ua,null);return t?(0,D.appUrl)('staff',t):null},i.forgetSignInHere=async function(){qe(),await L.kv.remove(Da),await L.kv.remove(Ua),Ne({mode:'signin',perms:[]});try{await Fa()}catch{}},i.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Ba('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},i.claimInviteForSync=async function(e){const t=await Ka(e);return'ok'===t.status?t.id:null},i.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,i=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===i||'chef'===i?i:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},i.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('current_staff_app_links',{p_venue:t,p_staff_ref:e})},i.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Ba('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},i.staffAppLinkHistory=async function(e){return Ba('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},i.revokeStaffAppLink=async function(e){await Ba('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},i.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Ba('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},i.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Ba('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},i.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},i.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ca,n),Ha(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},i.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Pa();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(Ma,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:xa(e)}}},i.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(Ma,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],i=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ca,null);await L.kv.set(Ca,e),await L.kv.remove(Da),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Ha()}return'revoked'!==i&&'unknown'!==i||await qa(),i}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},i.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await qa(),await Fa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},i.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Ba('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:xa(e)}}},i.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},i.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:xa(e)}}},i.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Ba('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},i.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Ba('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},i.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},i.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Ba('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},i.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Ba('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},i.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Ba('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:ja(e)}}},i.unpairDisplay=async function(){await L.kv.remove(Ca),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},i.disconnectStaff=async function(){await L.kv.remove(Da),await L.kv.remove(Ua),await Fa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},i.wipeThisDevice=async function(e={}){try{await Fa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},i.guestSession=La,Object.defineProperty(i,"rpc",{enumerable:!0,get:function(){return Ba}}),i.mendSession=Wa,i.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Qa=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,ie.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ts(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Va()},Object.defineProperty(i,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return za}}),i.serverOrder=ss,Object.defineProperty(i,"guestWords",{enumerable:!0,get:function(){return ns}}),i.nudgeGuestSync=function(){is?.()},Object.defineProperty(i,"syncInternals",{enumerable:!0,get:function(){return rs}}),i.stockSaveBlocker=os,i.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},i.resendUnsavedStockEvents=ds,i.saveStockEventsNow=us,i.bookingSaveBlocker=ls,i.resendUnsavedBookings=gs,i.saveBookingsNow=ms,i.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ls();if(a)return Promise.resolve({state:'refused',why:a});const s=fs()[0]?.venueId??'',n=()=>cs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const i=[],r=e=>{s||(s=!0,i.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return r({state:'refused',why:t.why});n()||r((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};i.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),i.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>r(n()||fs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||fs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},i.tempSaveBlocker=ws,i.tempLogState=function(){const e=vs()[0]?.venueId??'',t=vs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),i=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>i.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},i.saveTempNow=ks,i.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!vs().length)return Promise.resolve({state:'local'});const s=ws(e);if(s)return Promise.resolve({state:'refused',why:s});const n=vs()[0]?.venueId??'',i=vs().find(t=>t.spec.table===e),r=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!i?.unsavedKeys().includes(t))?Date.now()-r>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},i.goLive=Os,Object.defineProperty(i,"usePublicDayStore",{enumerable:!0,get:function(){return $s}}),i.publicDay=function(e,t){const a=`${e}|${t}`,s=Bs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Bs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Ba('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],i=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):i.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Bs.set(a,{at:Date.now(),v:{bookings:n,blocks:i},ok:!0}),$s.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Bs.get(a);e&&!e.ok&&Bs.delete(a)}));const n=Bs.get(a);return n?.ok?n.v:null},i.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const i=await Ba('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...i,id:e})},i.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Ba('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},i.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Ba('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},i.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Ba('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(r[0]),d=t(r[1]),u=t(r[2]),c=t(r[3]),l=t(r[4]),f=t(r[5]),p=t(r[6]),g=t(r[7]),m=t(r[8]),_=t(r[9]),y=t(r[10]),h=t(r[11]),S=t(r[12]),w=t(r[13]),v=t(r[14]),k=t(r[15]),b=t(r[16]),I=t(r[17]),R=t(r[18]),O=t(r[19]),A=t(r[20]),C=t(r[21]),D=t(r[22]),U=t(r[23]),T=t(r[24]),E=t(r[25]),N=t(r[26]),P=t(r[27]),K=t(r[28]),M=t(r[29]),x=t(r[30]),q=t(r[31]),j=t(r[32]),L=t(r[33]),B=t(r[34]),$=t(r[35]),F=t(r[36]),H=t(r[37]),W=t(r[38]),Q=t(r[39]),V=t(r[40]),G=t(r[41]),J=t(r[42]),Z=t(r[43]),z=t(r[44]),Y=t(r[45]),X=t(r[46]),ee=t(r[47]),te=t(r[48]),ae=t(r[49]),se=t(r[50]),ne=t(r[51]),ie=t(r[52]),re=t(r[53]),oe=t(r[54]),de=t(r[55]),ue=t(r[56]),ce=t(r[57]),le=t(r[58]),fe=t(r[59]),pe=t(r[60]),ge=t(r[61]),me=t(r[62]),_e=t(r[63]),ye=t(r[64]),he=t(r[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(r[66]),ve=t(r[67]),ke=t(r[68]),be=t(r[69]),Ie=t(r[70]),Re=t(r[71]),Oe=t(r[72]),Ae=t(r[73]),Ce=t(r[74]),De=t(r[75]),Ue=t(r[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,i='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),r=n.externalSource??(i?'Wix':null),o=n.externalId??(i?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...r?{external_source:r}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const i=a;return!t&&'deposit_status'in i&&('added_to_table'===i.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=i.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=i.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{bookings:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{orders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,i='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&i?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:i,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id)),o=[...i,...e.filter(e=>!r.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),pt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.key,e])),r=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>i.get(e.key)??e),o=new Set(r.map(e=>e.key));return{items:{...s.items,[e]:[...r,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function it(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{events:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function rt(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set;function dt(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card),writable:()=>Pe('recipes.edit'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=ut(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ct(e,t)),s={...s,photo:e}}const{row:i,extra:r}=(0,Ce.cardToRow)(s,a);return{...i,...r,doc:Qe({card:s,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null;return{card:{...a.card,id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(t);ne.useCardStore.setState(t=>({cards:t.cards.map(t=>e.has(t.id)&&t.signOff?{...t,signOff:null}:t)})),t=[]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),i=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),r=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(r.map(e=>e.id));return i.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>i.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...r,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...i]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const ut=e=>(0,ne.readLocalPhoto)(e);async function ct(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const lt=new Map,ft=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=lt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(lt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(lt.set(e,{url:t.signedUrl,at:Date.now()}),ft.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const pt=new Map;const gt=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return pt.set(a,t),a};function mt(e){return{name:'order_sheets',table:'suppliers',list:()=>ie.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:gt(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(pt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>ie.useOrderSheets.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>i.get(e.id)??e),o=new Set(r.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...r,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>ie.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let _t=!1,yt=!1;const ht=new Map,St=new Map,wt=new Map,vt=new Map,kt=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',bt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},It=(e,t)=>({...e,managerAccess:t}),Rt=()=>({nickname:_t,display:yt}),Ot=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=It({role:e.role,level:e.level??bt(kt(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},Rt())};const At=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ct=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Dt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Ut=2e3;function Tt(e,t){return t||!e.length||e.length>=Ut?null:e=>(0,le.isUuid)(e.id)}function Et(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Tt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&ht.has(e.staffId)&&(Pe('rota.manage')||Dt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(At());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ct(e.start),end_time:Ct(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,i]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,i).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{shifts:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Nt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{attendance:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Pt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:ht.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{timeRequests:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function Kt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function Mt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function xt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const qt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function jt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function Lt(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:qt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...$t??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...$t?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...$t?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Bt??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Bt=t.feature_flags??{},$t=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&jt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Bt=null,$t=null;const Ft=()=>new Date(Date.now()-2592e6).toISOString(),Ht=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>ht.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Wt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>St.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Qt=()=>Ee.getState().perms.includes('*');function Vt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Ht(t.ch)&&(t.from===e()||Qt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Ft()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Ft(),toRow:(e,t)=>{const a=Ht(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:ht.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Wt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?St.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>i.has(e.id)?{...e,...i.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=r&&s.chatRead?.[r]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===r?[e.from]:r&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[r]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?St.get(String(t.from_staff)):'system',i=Wt(String(t.channel)),r=e();if(!i||!r||n===r||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[r]??[]).includes(i))return;if(!(0,be.inChannel)(i,o.staff.find(e=>e.id===r)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=i.startsWith('dm:')?'sent you a message':`in ${'all'===i?'Everyone':'foh'===i?'Front of house':'kitchen'===i?'Kitchen':'managers'===i?'Managers':i}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Gt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=ht.get(e),i='*'===t?'*':Ht(t);if(n&&i)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:i,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function Jt(e){const t=Ee.getState().staffRef,a=t?ht.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const i={};for(const e of s){const t='*'===e.channel?'*':Wt(String(e.channel));t&&(i[t]=new Date(e.read_at).toISOString())}Object.keys(i).length&&ce.useOwner.getState().chatMarkRead(t,i)}catch{}}function Zt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),i={...s.rules},r=t.filter(e=>'break_rules'===e.kind);for(const t of r)i[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};i[e]&&n.has(i[e].id)&&delete i[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:i,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function zt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{done:[...e.filter(e=>!r.has(e.id)),...i].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function Yt(e,t,a,s=()=>!0){const n=new Set(a),i=new Map(t.map(e=>[e.id,e])),r=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&i.has(e.id)?i.get(e.id):e),o=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!o.has(e.id))]}const Xt=e=>null==e||''===e?null:Number(e),ea=e=>e.filter(e=>!e.startsWith('data:')),ta=()=>Pe('takings.view');function aa(e){const t=!ta();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:Yt(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function sa(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:ea(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:Yt(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function na(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function ia(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function ra(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:Xt(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:Yt(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function oa(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function da(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function ua(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const i=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:Yt(s.lists,i,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function ca(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:Yt(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:Yt(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function fa(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function pa(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,i]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,i),kind:'person',staffRef:i,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function ga(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:Yt(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ma(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function _a(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function ya(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function ha(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();va.setState({live:!!t?.push_live,known:!0})}catch{}}const Sa='order-list-logos';const wa=new Map;const va=(0,N.create)(()=>({live:!1,known:!1}));async function ka(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function ba(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Ia=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Ra='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Oa(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Ia(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),i=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!i.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Aa(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,i)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:i}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Ra).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Ia(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ca='pair:v1',Da='staff:v1',Ua='staff:rejoin:v1';async function Ta(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Ea(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ua,null);if(!e)return'none';try{await Pa();const{data:t,error:a}=await Ta(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ua),await L.kv.remove(Da),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Da,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ua),'refused')}catch{return'offline'}}const Na=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Pa(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function Ka(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Pa();const{data:t,error:a}=await Ta(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Da,n),await L.kv.set(Ua,e),Be&&Ha(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const Ma='car:request:v1',xa=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function qa(){await L.kv.remove(Ca),await L.kv.remove(Da),await L.kv.remove(Ma),D.useSession.getState().meId&&D.useSession.getState().signOut()}const ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Pa(),!0}catch{return!1}}const Ba=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let $a=null;async function Fa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],$a&&(clearInterval($a),$a=null)}async function Ha(){await Fa(),await Va()}async function Wa(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ua,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Ea()&&(Ha(),!0)}catch{return!1}}(0,c.setSessionMender)(Wa);let Qa=ee.VENUE_RID;async function Va(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Qa;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await Xa(e);let t=await L.kv.get(Ca,null),a=await L.kv.get(Da,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ca,t)),await L.kv.remove(Da),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Ea();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Qa===e&&Ha()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Da,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let i=[];try{const e=(await Ba('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ca):(await L.kv.remove(Da),await L.kv.remove(Ua)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});i=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&i.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Na(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Ea()&&setTimeout(()=>{Qa===e&&Ha()},500)}i=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!i.includes('device.write')&&(i=[...i,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:i}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await Ja(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Ga=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function Ja(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Os(a),Le.push(Ls(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])wt.set(e.key,e.id),vt.set(e.id,e.key)}catch{}const i=[Lt(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ot),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,Rt()),toRow:(e,t)=>(0,F.staffRow)(e,t,Rt(),e.managerAccess||e.ownerAccess?null:wt.get(kt(e))),fromRow:e=>{if(!e.external_ref)return null;ht.set(String(e.external_ref),String(e.id)),St.set(String(e.id),String(e.external_ref)),Ms.set(String(e.external_ref),e.avatar_path??null);const t=It(bt(vt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},Rt())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{js()},onRemote:()=>{js()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Qa]?.staffGrade??{};return e.staff.filter(e=>ht.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:ht.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Qa],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Qa,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Qa]?.staffGrade!==a.sites[Qa]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),it(a),rt(a),mt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{suppliers:[...i,...e.filter(e=>!r.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},dt(a),Ns(a)];Pe('wages.view')&&i.push(Ps(a)),n&&(i.push(Et(!0),Nt(),Pt(),xt(a)),Mt(e)),n&&await ya('staff_leave')&&(i.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),i=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),r=new Set(i.map(e=>e.id));return{leave:[...e.filter(e=>!r.has(e.id)),...i]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Ga.add('staff_leave'),Kt(e));const o=n&&await ba();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&i.push(Vt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>St.get(String(e.staff_id))??String(e.staff_id),syncable:e=>ht.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:ht.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:ht.get(e.id),include:e.include}),fromRow:e=>{const t=St.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await ya('hr_questions')&&(i.push(Oa(a)),Ga.add('hr_questions'),Aa(e,a)),'guest'!==s&&'customer'!==Me&&await ya('temp_readings')&&(i.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Ga.add('temp_units'),Ga.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await ya('cooksafe_records')&&(i.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Ga.add('cooksafe_records')),'guest'!==s&&await ya('sold_out_items')?(i.push(ma(a,await ya('sold_out_items','auto'))),Ga.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await ya('sold_out_links')?(i.push(_a(a)),Ga.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await ka()&&(i.push(Zt(a)),n&&i.push(zt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){_t=await ya('staff','nickname'),yt=await ya('staff','display_clock');const[e,t,s,n]=await Promise.all([ya('scheduled_notifications'),ya('order_lists'),ya('venue_clock_area'),ya('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(i.push(pa(a),ga(a)),Ga.add('daily_tasks'),Ga.add('daily_task_ticks')),e&&(i.push(da(a)),ha()),t&&i.push(ua(a),ca(a),la(a)),s&&i.push(fa(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Ga.add(n)}if('guest'!==s&&await ya('day_tips')){i.push(ia(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Ga.add(e);await ya('tips_pot_events')&&i.push(ra(a),oa(a)),n&&(ta()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),i.push(aa(a),na(a)),Ga.add('cash_ups'),ta()&&(i.push(sa(a)),Ga.add('sales_reports')),t(r[78])(r[77],r.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(i.push(Et(),Nt()),await ya('scheduled_notifications')&&i.push(da(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await ya('ingredient_prices')&&(i.push((0,y.gpSyncSpec)('ing',u)),Ga.add('ingredient_prices'),await ya('card_costs')&&(i.push((0,y.gpSyncSpec)('card',u)),Ga.add('card_costs')),await ya('kitchen_deliveries')&&(i.push((0,y.gpSyncSpec)('del',u)),Ga.add('kitchen_deliveries')),await ya('kitchen_stock_counts')&&(i.push((0,y.gpSyncSpec)('count',u)),Ga.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await ya('specials_boards')&&(i.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Ga.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Ba('whoami')??[]).some(t=>t.venue_id===e))return void(Qa===a&&Ha());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ls()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ws(e)??'this screen could not send it'})}};je=i.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Ba('whoami');if(!t?.some(t=>t.venue_id===e))return void(Qa===a&&Ha())}catch(e){if(Na(e)){if(Y.IS_CAR)return void(Qa===a&&Ha());const e=await Ea();return void('ok'!==e&&'refused'!==e||Qa===a&&Ha())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===i[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await Jt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Ga.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:za(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Qa===a&&Ha()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Na,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Za(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Za(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Ba('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const za=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const Ya='guest:sent:v1';async function Xa(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Ba('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Os(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),jt(e,t.app?.events)}await es(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{es(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ts(e)}async function es(e){const t=await Ba('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Ba('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ts(e){let t=await L.kv.get(Ya,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),i=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||i.length){if(!await La())return;for(const a of n)try{const s=(await Ba('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of i)try{const s=(await Ba('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?ss(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Ba('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:ns(s)}}:e)})))}await L.kv.set(Ya,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Ba('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(Ya,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Ba('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=ss(e,a);return as(s)===as(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),$a=setInterval(()=>{n()},15e3),is=()=>{n()},n()}const as=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function ss(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const ns=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let is=null;const rs={bridges:()=>je,restart:Ha};function os(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function ds(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||os())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function us(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}ds();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{us()},3e3)});const cs=['bookings','walk_ins'];function ls(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const fs=()=>je.filter(e=>cs.includes(e.spec.table)),ps=e=>H.mutationQueue.failed.some(t=>cs.includes(t.table)&&t.rowKey===e);function gs(e=!1){return ls()?0:fs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ps(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ms(e=!1){const t=ls();if(t)return t;for(const e of fs())try{await e.read()}catch{}gs(e);try{await H.mutationQueue.retryNow()}catch{}return e&&_s(),null}function _s(){const e=fs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(fs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ps(s)||cs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{cs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let ys=null;const hs=(e=2500)=>{ys&&clearTimeout(ys),ys=setTimeout(()=>{ys=null,ms(!1)},e)};(0,M.onConnectivity)(e=>{e&&hs()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&hs(3e3)});const Ss=['temp_readings','temp_units'];function ws(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const vs=()=>je.filter(e=>Ss.includes(e.spec.table));async function ks(e=!1){const t=ws();if(t)return t;for(const e of vs())try{await e.read()}catch{}const a=vs()[0]?.venueId??'';for(const t of vs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=vs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{Ss.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let bs=null;const Is=(e=3e3)=>{bs&&clearTimeout(bs),bs=setTimeout(()=>{bs=null,ks(!1)},e)};(0,M.onConnectivity)(e=>{e&&Is()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Is(3500)});const Rs='golive:v1:';async function Os(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ts(e):(await L.kv.get(Rs+e,!1)||await Ts(e),await L.kv.get(Ds+e,!1)||(Us(e),await L.kv.set(Ds+e,!0)),await L.kv.get(As+e,!1)||(Cs(),await L.kv.set(As+e,!0)))}const As='golive:v3:';function Cs(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ds='golive:v2:';function Us(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ts(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),i={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},r=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));r(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),r(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),r(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),r(ue.useSafety.getState(),i)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(i));const o=(0,U.stripHrSamples)(U.useHr.getState());r(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());r(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=ie.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};r(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),ie.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return r(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(Rs+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(Rs+e,!0)}const Es=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ns(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Es(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Es(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ps(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const i=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:i})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const Ks='staff-avatars',Ms=new Map;let xs=!1;const qs=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function js(){if(!xs){xs=!0;try{for(const[e,t]of Ms){const a=re.useAvatars.getState().photos[e];if(!t){a?.path&&re.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(Ks).download(t);if(n||!s)continue;const i=await qs(s);i.startsWith('data:image/')&&re.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:i,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{xs=!1}}}function Ls(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?ht.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=re.useAvatars.getState().photos[t];try{const n=Ms.get(t),i=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(Ks).remove([t]).catch(()=>{})};if(!s){const e=!!re.useAvatars.getState().clears?.[t];return e&&n&&(await Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}),Ms.set(t,null),i(n)),void(e&&re.useAvatars.getState().doneClear(t))}if(s.path)return;const r=await(await fetch(s.dataUrl)).blob();if(r.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===r.type?'jpg':'image/webp'===r.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(Ks).upload(d,r,{upsert:!1,contentType:r.type||'image/png'});if(u)throw u;await Ba('set_staff_avatar',{p_staff_ref:t,p_path:d}),Ms.set(t,d),n!==d&&i(n),re.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:re.useAvatars.getState().photos},s=re.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;Ms.set(t,null),re.useAvatars.getState().doneClear(t),Ba('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(Ks).remove([e])).catch(()=>{})}});return t(),s}const Bs=new Map,$s=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); +__d(function(e,t,a,s,n,r,i){"use strict";Object.defineProperty(r,'__esModule',{value:!0}),Object.defineProperty(r,"pointFromRow",{enumerable:!0,get:function(){return V.pointFromRow}}),Object.defineProperty(r,"pointToRow",{enumerable:!0,get:function(){return V.pointToRow}}),Object.defineProperty(r,"readingFromRow",{enumerable:!0,get:function(){return V.readingFromRow}}),Object.defineProperty(r,"readingToRow",{enumerable:!0,get:function(){return V.readingToRow}}),Object.defineProperty(r,"sameReading",{enumerable:!0,get:function(){return V.sameReading}}),Object.defineProperty(r,"inviteRefusal",{enumerable:!0,get:function(){return O.inviteRefusal}}),Object.defineProperty(r,"keysToWipe",{enumerable:!0,get:function(){return O.keysToWipe}}),Object.defineProperty(r,"changedFields",{enumerable:!0,get:function(){return A.changedFields}}),Object.defineProperty(r,"useSync",{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(r,"can",{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(r,"isLive",{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(r,"stockEventSaved",{enumerable:!0,get:function(){return at}}),Object.defineProperty(r,"ROTA_READ_CAP",{enumerable:!0,get:function(){return Et}}),r.rotaReconcile=Nt,r.markChatRead=function(e,t){if(!e)return;const a=(new Date).toISOString();ce.useOwner.getState().chatMarkRead(e,{[t]:a});const s=ce.useOwner.getState();new Set(s.chat.filter(a=>('*'===t||a.ch===t)&&!a.seenBy.includes(e)).map(e=>e.ch)).forEach(t=>ce.useOwner.getState().chatSeen(t,e)),Zt(e,t,a)},r.setTempManagerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_manager_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,managerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setTempOwnerAccess=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{error:n}=await Te().rpc('set_staff_owner_access',{p_venue:s,p_staff_ref:e,p_on:t,p_reason:a.trim()||null});return n?{ok:!1,message:/owner/i.test(n.message)?'Only an owner can change this.':'Could not save. Try again.'}:(ce.useOwner.setState(a=>({staff:a.staff.map(a=>a.id===e?{...a,ownerAccess:t}:a)})),{ok:!0})}catch{return{ok:!1,message:'Could not save. Try again when the app is online.'}}},r.setManagerAccess=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:s,error:n}=await Te().rpc('set_manager_access',{p_venue:a,p_staff_ref:e,p_on:t});if(n)return{ok:!1,message:n.message.replace(/^.*?:\s*/,'')||'Not allowed'};const r=String(s??'');return ce.useOwner.setState(t=>({staff:t.staff.map(t=>t.id===e?{...t,...Rt(r)}:t)})),{ok:!0,role:r}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.unlockCashUp=async function(e,t,a){if(ye.PITCH)return Se.unlockCashUp(e,t,a);const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:n,error:r}=await Te().rpc('unlock_cash_up',{p_venue:s,p_kind:e,p_id:t,p_reason:a});if(r)return{ok:!1,message:r.message};const i=String(n);return'cashup'===e?pe.useCashUp.setState(e=>({cashUps:e.cashUps.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})):pe.useCashUp.setState(e=>({sales:e.sales.map(e=>e.id===t?{...e,unlockedUntil:i}:e)})),{ok:!0,until:i}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.readCashAudit=async function(e){if(ye.PITCH)return Se.cashAudit(e);const t=Ee.getState().venueId;if(!t)return[];let a=Te().from('cash_up_audit').select('at, action, changed_by_name, tbl, for_date, reason, old_row, new_row').eq('venue_id',t).order('at',{ascending:!1}).limit(50);e&&(a=a.eq('row_id',e));const{data:s,error:n}=await a;return n||!Array.isArray(s)?[]:s.map(e=>({at:String(e.at),action:String(e.action),by:String(e.changed_by_name??'\u2014'),tbl:String(e.tbl),forDate:e.for_date??void 0,reason:e.reason??void 0,changed:(0,A.changedFields)(e.old_row,e.new_row)}))},r.readClockChanges=async function(e=30){if(ye.PITCH)return null;const t=Ee.getState().venueId;if(!t)return null;try{const{data:a,error:s}=await Te().rpc('owner_clock_changes',{p_venue:t,p_days:e});return s||!Array.isArray(a)?null:a}catch{return null}},r.readLoyaltyInsight=async function(){if(ye.PITCH)return null;const e=Ee.getState().venueId;if(!e)return null;try{const t=await Te().rpc('owner_loyalty_insight',{p_venue:e});if(!t.error&&t.data&&'object'==typeof t.data)return{raw:t.data,source:'server'};const a=await Te().rpc('loyalty_summary',{p_venue:e});return!a.error&&a.data&&'object'==typeof a.data?{raw:a.data,source:'summary'}:null}catch{return null}},r.setPushLive=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Connect to the venue first.'};const{data:a,error:s}=await Te().rpc('set_push_live',{p_venue:t,p_on:e});return s?{ok:!1,message:s.message}:(ba.setState({live:!!a,known:!0}),{ok:!0})},r.readPushLive=wa,r.readAccessLog=async function(){const e=Ee.getState().venueId;if(!e)return[];try{const{data:t}=await Te().from('staff_access_log').select('*').eq('venue_id',e).order('changed_at',{ascending:!1}).limit(30);return t??[]}catch{return[]}},r.readSyncHeartbeats=async function(){const e=Ee.getState().venueId;if(!e)return[];const{data:t,error:a}=await Te().from('device_sync_heartbeats').select('device_id,app,who,version,last_synced_at,realtime,pending,failed,user_agent,seen_at').eq('venue_id',e).order('seen_at',{ascending:!1}).limit(50);if(a)throw a;return t??[]},Object.defineProperty(r,"ORDER_LOGO_BUCKET",{enumerable:!0,get:function(){return va}}),r.uploadOrderLogo=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'offline'};try{const s=await(await fetch(t)).blob(),n=`${a}/${e}-${Date.now()}.jpg`,{error:r}=await Te().storage.from(va).upload(n,s,{upsert:!0,contentType:'image/jpeg'});return r?{ok:!1,message:r.message}:{ok:!0,path:n}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.orderLogoUrl=async function(e){const t=ka.get(e);if(t&&t.until>Date.now())return t.url;try{const{data:t}=await Te().storage.from(va).createSignedUrl(e,3600);if(t?.signedUrl)return ka.set(e,{url:t.signedUrl,until:Date.now()+3e6}),t.signedUrl}catch{}return null},r.removeOrderLogo=async function(e){try{await Te().storage.from(va).remove([e])}catch{}},Object.defineProperty(r,"usePushLive",{enumerable:!0,get:function(){return ba}}),r.claimInvite=xa,r.makeChromeHandover=async function(){const e=Ee.getState();if(ye.PITCH)return{ok:!0,code:'pitch-handover-code-aaaaaaaaaaaa'};if('staff'!==e.kind||!e.venueId)return{ok:!1,message:'Sign in from your personal link first.'};try{const{data:t,error:a}=await Te().rpc('make_chrome_handover',{p_venue:e.venueId,p_app:Me});return a||'string'!=typeof t?{ok:!1,message:a?.message?.replace(/^.*?:\s*/,'')||'Could not open Chrome. Check your connection and try again.'}:{ok:!0,code:t}}catch{return{ok:!1,message:'Could not open Chrome. Check your connection and try again.'}}},r.claimChromeHandover=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_chrome_handover',{p_code:e,p_app:Me});if(a){if(/expired|no longer active/i.test(a.message))return{status:'refused',message:a.message.replace(/^.*?:\s*/,'')};throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This Chrome link has expired. Open CoverCharge on your phone and tap Open in Chrome again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.displayKitchenUnlock=async function(e){if(ye.PITCH)return{ok:!1,error:'not_set'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:t,error:a}=await Te().rpc('display_kitchen_unlock',{p_code:e});if(a)return{ok:!1,error:'offline'};const s=t;if(s&&s.ok&&'string'==typeof s.ticket)return{ok:!0,ticket:s.ticket};const n=s?.error;return'wrong'===n||'locked'===n||'not_display'===n||'not_set'===n?{ok:!1,error:n}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.claimDisplayKitchen=async function(e){if(ye.PITCH||!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Te().rpc('claim_display_kitchen',{p_ticket:e});if(a){const e=a.message.replace(/^.*?:\s*/,'');return/expired|already signed in|no longer active|belongs to the Display/i.test(a.message)?{status:'refused',message:e}:{status:'refused',message:'Could not open the Head Chef app. Go back to the Display and enter the code again.'}}const s=t?.[0];if(!s)return{status:'refused',message:'That unlock has expired. Go back to the Display and enter the code again.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),Be&&Qa(),{status:'ok',id:n}}catch(e){return{status:'offline',message:String(e?.message??e)}}},r.endDisplayKitchen=async function(){try{qe(),await Te().rpc('end_display_kitchen')}catch{}try{await L.kv.remove(Ta)}catch{}},r.displayAssignKitchenRole=async function(e,t){if(ye.PITCH)return{ok:!1,error:'not_display'};if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'offline'};try{qe();const{data:a,error:s}=await Te().rpc('display_assign_kitchen_role',{p_shift:e,p_badge:t??null});if(s)return{ok:!1,error:'offline'};const n=a;if(n&&n.ok)return{ok:!0,badge:n.badge??void 0};const r=n?.error;return'not_display'===r||'not_kitchen'===r||'not_kitchen_role'===r||'missing'===r?{ok:!1,error:r}:{ok:!1,error:'offline'}}catch{return{ok:!1,error:'offline'}}},r.signedInHereAs=async function(e){qe();const t=await L.kv.get(Ta,null);return!!t&&'staff'===t.kind&&t.staffRef===e},r.rememberedInviteHere=async function(e){return qe(),await L.kv.get(Ea,null)===e},r.kirkmichaelStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_KIRKMICHAEL||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.wildingsStaffAppUrl=async function(){const e=Ee.getState();if(!ee.IS_WILDINGS||'staff'!==e.kind||e.venueId!==ee.VENUE_UUID||e.staffRef!==D.useSession.getState().meId)return null;qe();const t=await L.kv.get(Ea,null);return t?(0,D.appUrl)('staff',t):null},r.forgetSignInHere=async function(){qe(),await L.kv.remove(Ta),await L.kv.remove(Ea),Ne({mode:'signin',perms:[]});try{await Wa()}catch{}},r.approveShiftSwap=async function(e,t,a){const s=Ee.getState().venueId;if(ye.PITCH||!s||'staff'!==Ee.getState().kind)return{ok:!0};if(!(0,le.isUuid)(e))return{ok:!1,message:'This shift isn\u2019t on the shared rota yet.'};try{return await Fa('approve_shift_swap',{p_venue:s,p_shift:e,p_to_ref:t,p_kind:a}),{ok:!0}}catch(e){return{ok:!1,message:String(e?.message??e).replace(/^.*?:\s*/,'')||'Not allowed'}}},r.claimInviteForSync=async function(e){const t=await xa(e);return'ok'===t.status?t.id:null},r.reissueInvite=async function(e){if(ye.PITCH)return Se.reissueInvite(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Connect to the venue first (sign in from your link).'};try{const{data:a,error:s}=await Te().rpc('reissue_invite',{p_venue:t,p_staff_ref:e});if(s)return{ok:!1,message:s.message.replace(/^.*?:\s*/,'')||'Not allowed'};const n=a,r=String(n.app??'staff');return{ok:!0,token:String(n.token),expiresAt:String(n.expiresAt),app:'owner'===r||'chef'===r?r:'staff'}}catch(e){return{ok:!1,message:String(e?.message??e)}}},r.currentStaffAppLinks=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('current_staff_app_links',{p_venue:t,p_staff_ref:e})},r.makeStaffAppLink=async function(e,t){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Fa('make_staff_app_link',{p_venue:a,p_staff_ref:e,p_platform:t})},r.staffAppLinkHistory=async function(e){return Fa('staff_app_link_history',{p_venue:Ee.getState().venueId,p_staff_ref:e})},r.revokeStaffAppLink=async function(e){await Fa('revoke_staff_app_link',{p_venue:Ee.getState().venueId,p_link_id:e})},r.staffLinkPhones=async function(){if(ye.PITCH)return Se.linkPhones();const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return{};try{const t=await Fa('staff_link_phones',{p_venue:e}),a={};for(const e of t??[])a[String(e.staff_ref)]={phones:Number(e.phones??0),since:String(e.since)};return a}catch{return{}}},r.resetStaffLinkPhone=async function(e){if(ye.PITCH)return Se.resetPhone(e);const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');return Number(await Fa('reset_staff_link_phone',{p_venue:t,p_staff_ref:e}))},r.readInviteStatus=async function(){if(ye.PITCH)return Se.inviteStatus();const e=Ee.getState().venueId;if(!e)return{};const{data:t,error:a}=await Te().rpc('invite_status',{p_venue:e});if(a||!Array.isArray(t))return{};const s={};for(const e of t)s[String(e.staff_ref)]={state:e.state,expiresAt:e.expires_at??void 0,usedAt:e.used_at??void 0,devices:Number(e.devices??0)};return s},r.pairWithCode=async function(e){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:t,error:a}=await Te().rpc((0,p.claimPairingRpc)(),{p_code:e});if(a)throw a;const s=t?.[0];if(!s)return{ok:!1,error:'That code was not accepted. It may have expired. Ask a manager for a new one.'};const n={kind:'device',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,canWrite:s.can_write,label:s.label};return await L.kv.set(Ua,n),Qa(),{ok:!0,venueName:s.venue_name}}catch(e){const t=String(e?.message??e);return/fetch|network/i.test(t)?{ok:!1,error:'No connection. Check the tablet\u2019s Wi-Fi and try again.'}:/rate|too many/i.test(t)?{ok:!1,error:'Too many tries from this network. Wait a little and try again.'}:{ok:!1,error:/valid|switched off/i.test(t)?t:`Couldn\u2019t pair: ${t}`}}},r.carPairStart=async function(){if(!(0,K.isSupabaseConfigured)())return{ok:!1,error:'This build has no shared backend.'};try{await Ma();const{data:e,error:t}=await Te().rpc('car_pair_start',{p_venue_slug:'anchorage'});if(t)throw t;const a=e?.[0];return a?(await L.kv.set(qa,a.request_id),{ok:!0,requestId:a.request_id,code:a.code,expiresAt:a.expires_at}):{ok:!1,error:'No code came back. Try again.'}}catch(e){return{ok:!1,error:ja(e)}}},r.carPairPoll=async function(e){try{qe();const t=e??await L.kv.get(qa,null);if(!t)return'unknown';const{data:a,error:s}=await Te().rpc('car_pair_poll',{p_request:t});if(s)throw s;const n=a?.[0],r=String(n?.status??'unknown');if((0,X.carPairApproved)(n)){const e=(0,X.carDeviceIdentity)({venue_id:n.venue_id,venue_slug:n.venue_slug,venue_name:n.venue_name,role_key:n.role_key,label:n.label}),t=await L.kv.get(Ua,null);await L.kv.set(Ua,e),await L.kv.remove(Ta),D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({staffAs:void 0,previewRole:'owner'}),t&&t.venueId===e.venueId&&'device'===t.kind||Qa()}return'revoked'!==r&&'unknown'!==r||await La(),r}catch(e){return/fetch|network/i.test(String(e?.message??e))?'offline':'unknown'}},r.carSignOut=async function(){try{qe(),await Te().rpc('car_sign_out')}catch{}await La(),await Wa();try{await Te().auth.signOut({scope:'local'})}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This car is unpaired.'})},r.carApprove=async function(e,t="Tesla"){const a=Ee.getState().venueId;if(!a||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const s=(await Fa('car_pair_approve',{p_venue:a,p_code:e,p_label:t}))?.[0];return s?.id?{ok:!0}:{ok:!1,message:String(s?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:ja(e)}}},r.carList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('car_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,staffName:e.staff_name,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0}))},r.carRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('car_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:ja(e)}}},r.assistantApprove=async function(e){const t=Ee.getState().venueId;if(!t||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const a=(await Fa('assistant_pair_approve',{p_venue:t,p_code:e}))?.[0];return a?.id?{ok:!0}:{ok:!1,message:String(a?.message??'That code isn\u2019t right or has run out.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_devices_list',{p_venue:e})??[]).map(e=>({id:e.id,label:e.label,approvedAt:e.approved_at,lastSeenAt:e.last_seen_at??void 0,enabled:!1!==e.enabled,ownerName:e.owner_name?String(e.owner_name):void 0}))},r.assistantSetEnabled=async function(e,t){const a=Ee.getState().venueId;if(!a)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_set_enabled',{p_venue:a,p_id:e,p_enabled:t}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantAccess=async function(){const e=Ee.getState().venueId;if(!e)return{plan:null,allowed:!1};const t=(await Fa('assistant_access',{p_venue:e}))?.[0];return{plan:null!=t?.plan?String(t.plan):null,allowed:!0===t?.allowed,reason:t?.reason?String(t.reason):void 0}},r.assistantAuditList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_audit_list',{p_venue:e,p_limit:100})??[]).map(e=>({id:String(e.id),at:String(e.at),actor:String(e.actor??''),actorName:e.actor_name?String(e.actor_name):void 0,action:String(e.action??''),detail:e.detail?String(e.detail):void 0}))},r.assistantRevoke=async function(e){const t=Ee.getState().venueId;if(!t)return{ok:!1,message:'Not connected.'};try{return await Fa('assistant_revoke',{p_venue:t,p_id:e}),{ok:!0}}catch(e){return{ok:!1,message:Ba(e)}}},r.assistantProposalsList=async function(){const e=Ee.getState().venueId;if(!e)return[];return(await Fa('assistant_proposals_list',{p_venue:e})??[]).map(e=>({id:String(e.id),kind:String(e.kind??''),summary:String(e.summary??''),warning:e.warning?String(e.warning):void 0,status:String(e.status??''),needsDoubleConfirm:!0===e.needs_double_confirm,canDecide:!0===e.can_decide,expiresAt:e.expires_at?String(e.expires_at):void 0,createdAt:e.created_at?String(e.created_at):void 0,decidedByName:e.decided_by_name?String(e.decided_by_name):void 0,appliedStamp:e.applied_stamp?String(e.applied_stamp):void 0,error:e.error?String(e.error):void 0}))},r.assistantProposalDecide=async function(e,t,a=!1){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)return{ok:!1,message:'Your phone needs to be connected first. Check your signal and try again.'};try{const n=(await Fa('assistant_proposal_decide',{p_venue:s,p_id:e,p_decision:t,p_double_confirm:a}))?.[0];return n?.id?{ok:!0}:{ok:!1,message:String(n?.error??n?.message??'That change could not be confirmed.')}}catch(e){return{ok:!1,message:Ba(e)}}},r.unpairDisplay=async function(){await L.kv.remove(Ua),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'unpaired',venueId:void 0,venueName:void 0,perms:[]})},r.disconnectStaff=async function(){await L.kv.remove(Ta),await L.kv.remove(Ea),await Wa();try{await Te().auth.signOut()}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'Disconnected. Open your personal invite link to connect again.'})},r.wipeThisDevice=async function(e={}){try{await Wa()}catch{}try{(0,K.isSupabaseConfigured)()&&await Te().auth.signOut({scope:'local'})}catch{}let t=0;try{const e='undefined'!=typeof navigator?navigator:null,t=await(e?.serviceWorker?.getRegistration?.()),a=await(t?.pushManager?.getSubscription?.());a&&await a.unsubscribe()}catch{}for(const e of['undefined'!=typeof localStorage?localStorage:null,'undefined'!=typeof sessionStorage?sessionStorage:null])if(e)try{const a=[];for(let t=0;te.startsWith(`cc-venue:${ee.VENUE_RID}:`)):(0,O.keysToWipe)(a).filter(e=>!e.startsWith('cc-venue:')))e.removeItem(s),t++}catch{}try{const e='undefined'!=typeof caches?caches:null;if(e)for(const t of await e.keys())!ee.IS_ISOLATED_VENUE&&/data|api|photo/i.test(t)&&await e.delete(t)}catch{}Ne({mode:'signin',venueId:void 0,venueName:void 0,perms:[],kind:void 0,role:void 0,staffRef:void 0,message:'This device has been wiped.'}),!1!==e.reload&&'undefined'!=typeof window&&window.location&&window.location.replace(window.location.pathname);return t},r.guestSession=$a,Object.defineProperty(r,"rpc",{enumerable:!0,get:function(){return Fa}}),r.mendSession=Va,r.startAppSync=async function(e=ee.VENUE_RID){if(ee.IS_ISOLATED_VENUE&&e!==ee.VENUE_RID)return;if(Be)return;Be=!0,Ga=e,'customer'===Me&&'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}});if(qe(),'customer'!==Me){const t=e=>new Promise(t=>{try{if(!e?.persist||e.persist.hasHydrated())return t();const a=e.persist.onFinishHydration(()=>{a?.(),t()});setTimeout(t,3e3)}catch{t()}}),a='chef'===Me&&(0,w.isAnchorage)(e)?[z.useStore,ce.useOwner,de.useKitchen,ue.useSafety,ne.useCardStore,y.useGpCalc,re.useOrderSheets,S.useSpecials,U.useHr]:[z.useStore,ce.useOwner,de.useKitchen];if(await Promise.all(a.map(t)),'chef'===Me&&(0,w.isAnchorage)(e)&&a.some(e=>!e.persist.hasHydrated()))return void Ne({mode:'offline',message:'Saved kitchen data could not be backed up. Nothing was cleared. Free some device storage, then reopen.',lastError:'Legacy kitchen archive not ready'});try{await Ns(e)}catch{if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e))return void Ne({mode:'offline',message:'Device backup failed. Nothing was cleared. Free some storage, then reopen.',lastError:'Legacy kitchen archive failed'})}'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}})}if(!(0,K.isSupabaseConfigured)())return void Ne({mode:'off'});H.mutationQueue.subscribe(()=>{const e=H.mutationQueue.waiting,t=e[0];Ne({pending:H.mutationQueue.pending.length,failed:H.mutationQueue.failed.length,waiting:e.length,waitingWhat:t?`${(0,$.describeWrite)(t)}: ${(0,$.plainReason)({...t.lastErr},'retry')}`:void 0})}),H.mutationQueue.onFailed(e=>Ne({lastError:`${e.table}: ${e.lastError??'rejected'}`,failed:H.mutationQueue.failed.length,...'temp_readings'===e.table||'temp_units'===e.table?{}:{refused:{what:(0,$.describeWrite)(e),why:'conflict'===e.reason?(0,$.plainReason)({code:'conflict'},'refused'):(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused'),at:e.failedAt}}})),Le.push((0,M.onConnectivity)(e=>Ne({mode:e?Ee.getState().venueId?'live':Ee.getState().mode:Ee.getState().venueId?'offline':Ee.getState().mode}))),await Ja()},Object.defineProperty(r,"BOOKINGS_POLL_MS",{enumerable:!0,get:function(){return Xa}}),r.serverOrder=rs,Object.defineProperty(r,"guestWords",{enumerable:!0,get:function(){return is}}),r.nudgeGuestSync=function(){os?.()},Object.defineProperty(r,"syncInternals",{enumerable:!0,get:function(){return ds}}),r.stockSaveBlocker=us,r.stockEventStatus=function(e){if(at(e))return{state:'saved'};const t=H.mutationQueue.failed.find(t=>'stock_events'===t.table&&t.rowKey===e);return t?{state:'refused',why:(0,$.plainReason)({...t.lastErr,message:t.lastErr?.message??t.lastError},'refused')}:{state:'waiting'}},r.resendUnsavedStockEvents=cs,r.saveStockEventsNow=ls,r.bookingSaveBlocker=ps,r.resendUnsavedBookings=_s,r.saveBookingsNow=ys,r.waitForBookingSave=function(e,t=12e3){if(!Ke())return Promise.resolve({state:'local'});const a=ps();if(a)return Promise.resolve({state:'refused',why:a});const s=gs()[0]?.venueId??'',n=()=>fs.some(t=>H.mutationQueue.hasPending(t,s,e));return new Promise(a=>{let s=!1;const r=[],i=e=>{s||(s=!0,r.forEach(e=>e()),clearTimeout(d),a(e))},o=()=>{const t=W.useBookingSaves.getState().notSaved[e];if(t)return i({state:'refused',why:t.why});n()||i((0,M.isOnline)()?{state:'saved'}:{state:'waiting'})};r.push(H.mutationQueue.onDone(t=>{t.rowKey===e&&setTimeout(o,0)})),r.push(H.mutationQueue.onFailed(t=>{t.rowKey===e&&setTimeout(o,0)}));const d=setTimeout(()=>i(n()||gs().some(t=>t.unsavedKeys().includes(e))?{state:'waiting'}:{state:'saved'}),t);setTimeout(()=>{n()||gs().some(t=>t.unsavedKeys().includes(e))||o()},400)})},r.tempSaveBlocker=ks,r.tempLogState=function(){const e=bs()[0]?.venueId??'',t=bs().find(e=>'temp_readings'===e.spec.table),a=H.mutationQueue.pending.filter(t=>'temp_readings'===t.table&&t.venueId===e).length,s=t&&t.spec.writable()?t.unsavedKeys().filter(t=>!H.mutationQueue.hasPending('temp_readings',e,t)).length:0,n=Object.values(Q.useTempSaves.getState().notSaved),r=ue.useSafety.getState().points??[];return{waiting:a+s,refused:n.filter(e=>'temp_readings'===e.table).length,refusedUnits:n.filter(e=>'temp_units'===e.table).map(e=>r.find(t=>t.id===e.id)?.name??'a unit'),why:n[0]?.why}},r.saveTempNow=Is,r.waitForTempSave=function(e,t,a=1e4){if(!Ke()||!bs().length)return Promise.resolve({state:'local'});const s=ks(e);if(s)return Promise.resolve({state:'refused',why:s});const n=bs()[0]?.venueId??'',r=bs().find(t=>t.spec.table===e),i=Date.now();return new Promise(s=>{const o=()=>{const d=t.map(t=>Q.useTempSaves.getState().notSaved[(0,Q.tempKey)(e,t)]).find(Boolean);if(d)return s({state:'refused',why:d.why});return t.some(t=>H.mutationQueue.hasPending(e,n,t)||!!r?.unsavedKeys().includes(t))?Date.now()-i>a?s({state:'waiting'}):void setTimeout(o,300):s({state:'saved'})};setTimeout(o,400)})},r.goLive=Cs,Object.defineProperty(r,"usePublicDayStore",{enumerable:!0,get:function(){return Hs}}),r.publicDay=function(e,t){const a=`${e}|${t}`,s=Fs.get(a);if('customer'!==Me||!(0,K.isSupabaseConfigured)())return null;(!s||Date.now()-s.at>6e4)&&(s?s.at=Date.now():Fs.set(a,{at:Date.now(),v:{bookings:[],blocks:[]}}),Fa('public_day',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_date:t}).then(s=>{const n=[],r=[];(s??[]).forEach((a,s)=>{'booking'===a.kind?n.push({id:`pub-${t}-${s}`,ref:'',restaurantId:e,customerId:null,name:'',date:t,time:He(a.booking_time),partySize:Number(a.covers)||0,table:(a.table_ids??[]).join('+')||void 0,durationMins:a.duration_mins??void 0,status:'confirmed',allergies:[],createdAt:''}):r.push({id:`pubblk-${t}-${s}`,rid:e,date:t,from:He(a.from_time),to:He(a.to_time),areaId:a.area_id??void 0,tables:Array.isArray(a.table_ids)&&a.table_ids.length?a.table_ids.map(String):void 0,by:'',createdAt:''})}),Fs.set(a,{at:Date.now(),v:{bookings:n,blocks:r},ok:!0}),Hs.setState(e=>({n:e.n+1}))}).catch(()=>{const e=Fs.get(a);e&&!e.ok&&Fs.delete(a)}));const n=Fs.get(a);return n?.ok?n.v:null},r.saveStaffBookingTimes=async function(e,t,a,s){const n=Ee.getState().venueId;if(!n||'staff'!==Ee.getState().kind)throw new Error('Connect to your venue first.');const r=await Fa('save_staff_booking_times',{p_venue:n,p_hours:t,p_turn:a,p_covers:s});z.useStore.getState().updateRestaurant(e,{...r,id:e})},r.staffTakeawayMenu=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return null;return(await Fa('takeaway_menu_staff',{p_venue:e})??[]).map(e=>({itemId:String(e.item_id),dish:String(e.dish??e.item_id),section:String(e.section??''),pricePence:null==e.price_pence?null:Number(e.price_pence),signedOff:!!e.signed_off,onMenu:!!e.on_menu,soldOut:!!e.sold_out}))},r.setStaffTakeawayDish=async function(e,t,a){const s=Ee.getState().venueId;if(!s||'staff'!==Ee.getState().kind)throw new Error('Connect to the venue first.');await Fa('takeaway_menu_set',{p_venue:s,p_item:e,p_on:t,p_by:a})},r.staffTakeawayCanSet=async function(){const e=Ee.getState().venueId;if(!e||'staff'!==Ee.getState().kind)return!1;try{return!0===await Fa('takeaway_menu_can_set',{p_venue:e})}catch{return!1}};var o=t(i[0]),d=t(i[1]),u=t(i[2]),c=t(i[3]),l=t(i[4]),f=t(i[5]),p=t(i[6]),g=t(i[7]),m=t(i[8]),_=t(i[9]),y=t(i[10]),h=t(i[11]),S=t(i[12]),w=t(i[13]),v=t(i[14]),k=t(i[15]),b=t(i[16]),I=t(i[17]),R=t(i[18]),O=t(i[19]),A=t(i[20]),C=t(i[21]),D=t(i[22]),U=t(i[23]),T=t(i[24]),E=t(i[25]),N=t(i[26]),P=t(i[27]),K=t(i[28]),M=t(i[29]),x=t(i[30]),q=t(i[31]),j=t(i[32]),L=t(i[33]),B=t(i[34]),$=t(i[35]),F=t(i[36]),H=t(i[37]),W=t(i[38]),Q=t(i[39]),V=t(i[40]),G=t(i[41]),J=t(i[42]),Z=t(i[43]),z=t(i[44]),Y=t(i[45]),X=t(i[46]),ee=t(i[47]),te=t(i[48]),ae=t(i[49]),se=t(i[50]),ne=t(i[51]),re=t(i[52]),ie=t(i[53]),oe=t(i[54]),de=t(i[55]),ue=t(i[56]),ce=t(i[57]),le=t(i[58]),fe=t(i[59]),pe=t(i[60]),ge=t(i[61]),me=t(i[62]),_e=t(i[63]),ye=t(i[64]),he=t(i[65]),Se=(function(e){if(e&&e.__esModule)return e;var t={};return e&&Object.keys(e).forEach(function(a){if('default'!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t})(he),we=t(i[66]),ve=t(i[67]),ke=t(i[68]),be=t(i[69]),Ie=t(i[70]),Re=t(i[71]),Oe=t(i[72]),Ae=t(i[73]),Ce=t(i[74]),De=t(i[75]),Ue=t(i[76]);const Te=()=>(0,P.getSupabase)();H.mutationQueue.setExecutor(B.executeMutation),(0,q.setClockServer)(()=>'staff'===Ee.getState().kind);const Ee=(0,N.create)(()=>({mode:'off',perms:[],pending:0,failed:0})),Ne=e=>Ee.setState(e),Pe=e=>{const t=Ee.getState().perms;return t.includes('*')||t.includes(e)},Ke=()=>{const e=Ee.getState().mode;return'live'===e||'offline'===e||'connecting'===e};Ee.subscribe(()=>(0,Ae.setLiveData)(Ke()));let Me=Y.IS_CAR?'car':Y.APP_VARIANT,xe=!1;const qe=()=>{xe||((0,L.setSyncNamespace)(Me),xe=!0)};let je=[],Le=[],Be=!1;const $e=()=>(new Date).toISOString().slice(0,10),Fe=e=>new Date(Date.now()-864e5*e).toISOString().slice(0,10),He=e=>e?e.slice(0,5):'',We=e=>Array.isArray(e)?e.filter(e=>e&&'object'==typeof e&&'string'==typeof e.allergen&&['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'].includes(e.allergen)&&(!e.severity||['intolerance','allergy','coeliac','anaphylaxis'].includes(e.severity))):[],Qe=e=>JSON.parse(JSON.stringify(e));function Ve(e,t){const a=Fe(120);return{name:t?'walk_ins':'bookings',table:t?'walk_ins':'bookings',list:()=>z.useStore.getState().bookings.filter(a=>a.restaurantId===e&&!!a.walkIn===t),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte(t?'walk_date':'booking_date',a),inWindow:e=>e.date>=a,toRow:(e,a)=>{const s=Qe(e);if(t)return{id:e.id,venue_id:a,walk_date:e.date,arrived_at:e.seatedAt??e.createdAt,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),note:e.notes??'',status:'finished'===e.status?'left':'cancelled'===e.status||'noshow'===e.status?'undone':'seated',created_at:e.createdAt,doc:s};const n=e,r='Wix'===n.importedFrom||Array.isArray(e.tags)&&e.tags.includes('Wix'),i=n.externalSource??(r?'Wix':null),o=n.externalId??(r?e.id:null);return{id:e.id,venue_id:a,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,guest_name:e.name||'Guest',phone:e.phone??null,email:e.email??null,booking_date:e.date,booking_time:e.time,duration_mins:e.durationMins&&e.durationMins>=15&&e.durationMins<=720?e.durationMins:null,covers:Math.max(1,Math.min(200,e.partySize)),table_ids:e.table?e.table.split('+').map(e=>e.trim()).filter(Boolean):[],dog:!!e.dog,allergies:We(e.allergies),allergy_ack_by:e.allergyAck?.by??null,allergy_ack_at:e.allergyAck?.at??null,notes:e.notes??'',tags:e.tags??[],occasion:e.occasion??null,status:e.status,source:e.source??'in-person',security:e.security??'none',deposit_paid:e.depositPaid??0,seated_at:e.seatedAt??null,finished_at:e.finishedAt??null,created_at:e.createdAt,doc:s,...i?{external_source:i}:{},...o?{external_id:o}:{}}},fromRow:a=>{if(!a.doc||'object'!=typeof a.doc)return null;const s={...a.doc,id:String(a.id),restaurantId:e};if(!t&&a.status&&'declined'!==a.status&&(s.status=a.status),!t){const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];s.table=e.length?e.join('+'):void 0}if(t){s.walkIn=!0,'left'===a.status?s.status='finished':'undone'===a.status?s.status='cancelled':'seated'===a.status&&(s.status='seated');const e=Array.isArray(a.table_ids)?a.table_ids.map(String).map(e=>e.trim()).filter(Boolean):[];e.length&&(s.table=e.join('+'))}'saved-card'===s.security&&(s.security='none');const n=a;'string'==typeof n.phone&&n.phone.trim()&&(s.phone=n.phone.trim()),'string'==typeof n.email&&n.email.trim()&&(s.email=n.email.trim());const r=a;return!t&&'deposit_status'in r&&('added_to_table'===r.deposit_status?(s.depositStatus='added_to_table',s.depositAddedAt=r.deposit_added_at??s.depositAddedAt??null,s.depositAddedBy=r.deposit_added_by??s.depositAddedBy??null):(delete s.depositStatus,delete s.depositAddedAt,delete s.depositAddedBy)),s},apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.bookings.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{bookings:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.bookings!==a.bookings&&e()}),protect:!0}}function Ge(e){const t=new Date(Date.now()-18144e5).toISOString();return{name:'orders',table:'takeaway_orders',list:()=>z.useStore.getState().orders.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('created_at',t),inWindow:e=>e.createdAt>=t,toRow:(e,t)=>({id:e.id,venue_id:t,ref:e.ref,customer_id:(0,le.isUuid)(e.customerId)?e.customerId:null,customer_name:e.customerName||'Guest',phone:e.phone??null,email:e.email??null,items:Qe(e.lines??[]),allergies:We(e.allergies),notes:e.notes??null,slot_time:e.slotTime??null,ready_by:e.readyBy??null,subtotal:Math.round(e.subtotal??0),tip:Math.round(e.tip??0),total:Math.round(e.total??0),paid:Math.round(e.paid??0),status:e.status,channel:e.channel??null,confirmed_by:e.accepted?e.accepted.by:null,confirmed_at:e.accepted?e.accepted.at:null,created_at:e.createdAt,allergy_chain:Qe(e.allergyChain??{}),readiness:Qe(e.readiness??{}),allergy_ticks:Qe(e.allergyTicks??{}),handover_check:e.handoverCheck?Qe(e.handoverCheck):null,accepted:e.accepted?Qe(e.accepted):null,doc:Qe(e)}),fromRow:t=>t.doc&&'object'==typeof t.doc?{...t.doc,id:String(t.id),restaurantId:e,status:t.status??t.doc.status}:null,apply:(e,t)=>z.useStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.orders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{orders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.orders!==a.orders&&e()})}}function Je(e){const t=Fe(60);return{protect:!0,name:'blocks',table:'blocks',list:()=>[...te.useBlocks.getState().blocks,...te.useBlocks.getState().removed].filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.to>e.from,writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e},filter:e=>e.gte('block_date',t),inWindow:e=>e.date>=t,toRow:(e,t)=>({id:e.id,venue_id:t,block_date:e.date,from_time:e.from,to_time:e.to,reason:e.reason??null,note:e.note??null,area_id:e.areaId??null,area_name:e.areaName??null,created_by:e.by,created_at:e.createdAt,doc:Qe(e)}),fromRow:t=>{const a=t.doc&&'object'==typeof t.doc?{...t.doc}:null,s=(0,te.blockClock)(t.from_time)??a?.from,n=(0,te.blockClock)(t.to_time)??a?.to,r='string'==typeof t.block_date?t.block_date.slice(0,10):a?.date;return s&&n&&r?{...a??{by:t.created_by??'',createdAt:t.created_at},id:String(t.id),rid:e,date:r,from:s,to:n,reason:(t.reason??a?.reason)||void 0,note:t.note??a?.note,areaId:t.area_id??a?.areaId,areaName:t.area_name??a?.areaName}:a?{...a,id:String(t.id),rid:e}:null},apply:(e,t)=>te.useBlocks.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=[...a.blocks,...a.removed].filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id)),o=[...r,...e.filter(e=>!i.has(e.id))];return{blocks:o.filter(e=>!e.removedAt),removed:o.filter(e=>!!e.removedAt)}}),subscribe:e=>te.useBlocks.subscribe((t,a)=>{t.blocks===a.blocks&&t.removed===a.removed||e()})}}let Ze=null,ze='Main plan';function Ye(e){const t=e=>Qe({areas:e.areas??[],tables:e.tables??[],joins:e.joins??[],sections:e.sections??[],fixtures:e.fixtures??[]});return{name:'table_plan',table:'table_plans',list:()=>[t(ae.useFloor.getState().plans[e]??(0,ae.planOf)(e))],key:()=>'plan',rowKey:()=>'plan',syncable:()=>!0,writable:()=>Pe('floor.manage')||Pe('device.write'),filter:e=>e.eq('is_active',!0),deletes:!1,toRow:(e,a)=>({id:Ze??(0,Ce.uuidFrom)(`plan:${a}`),venue_id:a,name:ze||'Main plan',is_active:!0,...t(e),updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>!0!==e.is_active?null:(Ze=String(e.id),ze=String(e.name||'Main plan'),t({areas:e.areas,tables:e.tables,joins:e.joins,sections:e.sections,fixtures:e.fixtures})),apply:t=>{const a=t[0]?(0,De.withSeedBest)(e,t[0]):void 0;a&&ae.useFloor.setState(t=>({plans:{...t.plans,[e]:a}}))},subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.plans!==a.plans&&e()})}}function Xe(e){return{protect:!0,name:'stock_items',table:'stock_items',conflict:'venue_id,key',list:()=>se.useShellStore.getState().items[e]??[],key:e=>e.key,rowKey:e=>String(e.key),syncable:()=>!0,writable:()=>Pe('stock.manage'),matchKey:e=>({key:e}),toRow:(e,t)=>({venue_id:t,key:e.key,name:e.name,plural:e.plural,unit:e.unit,low_at:e.lowAt,supplier_id:e.supplierId?(0,le.isUuid)(e.supplierId)?e.supplierId:(0,Ce.uuidFrom)(`sup:${t}:${e.supplierId}`):null,icon:e.icon,sort:e.sort,active:e.active,display_group:e.group??null}),fromRow:e=>{return{key:e.key,name:e.name,plural:e.plural,unit:e.unit,lowAt:Number(e.low_at),icon:e.icon??'\u2022',sort:e.sort??0,active:!1!==e.active,...'roast'===e.display_group?{group:'roast'}:{},...e.supplier_id?{supplierId:(t=String(e.supplier_id),mt.get(t)??t)}:{}};var t},apply:(t,a)=>se.useShellStore.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.key,e])),i=(s.items[e]??[]).filter(e=>!n.has(e.key)).map(e=>r.get(e.key)??e),o=new Set(i.map(e=>e.key));return{items:{...s.items,[e]:[...i,...t.filter(e=>!o.has(e.key))]}}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.items!==a.items&&e()})}}const et=new Set,tt=new Set;H.mutationQueue.onDone(e=>{'stock_events'===e.table&&tt.add(e.rowKey)});const at=e=>tt.has(e)||et.has(e),st=()=>Pe('*')||Pe('staff.manage')||Pe('recipes.edit')||Pe('recipes.signoff'),nt=()=>'guest'!==Ee.getState().kind&&('device'!==Ee.getState().kind||Pe('device.write'));function rt(e){const t=new Date(Date.now()-2592e5).toISOString();return{name:'stock_events',table:'stock_events',mode:'insert',list:()=>se.useShellStore.getState().events.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.id)&&!!(se.useShellStore.getState().items[e]??[]).find(e=>e.key===t.kind),writable:()=>{const e=Ee.getState().kind;return'guest'!==e&&'assistant'!==e&&('device'!==e||Pe('device.write'))},filter:e=>e.gte('at',t).order('at',{ascending:!1}),inWindow:e=>e.at>=t,toRow:(e,t)=>({id:e.id,venue_id:t,item:e.kind,delta:e.delta,reason:e.reason,undoes:e.undoes&&(0,le.isUuid)(e.undoes)&&(at(e.undoes)||H.mutationQueue.hasPending('stock_events',t,e.undoes))?e.undoes:null,by_name:e.by||'Team',app:e.app,at:e.at}),fromRow:t=>(et.add(String(t.id)),{id:String(t.id),rid:e,kind:t.item,delta:Number(t.delta),reason:t.reason,by:t.by_name??'',app:t.app??'',at:new Date(t.at).toISOString(),...t.undoes?{undoes:String(t.undoes)}:{}}),apply:(e,t)=>se.useShellStore.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.events.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{events:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,500)}}),subscribe:e=>se.useShellStore.subscribe((t,a)=>{t.events!==a.events&&e()})}}function it(e){let t={};return{name:'stock_counts',table:'stock_counts',list:()=>Object.entries(se.useShellStore.getState().server[e]?.counts??{}).map(([e,t])=>({item:e,quantity:t})),key:e=>e.item,rowKey:e=>String(e.item),syncable:()=>!1,writable:()=>!1,toRow:()=>({}),fromRow:e=>({item:String(e.item),quantity:Number(e.quantity)}),apply:(a,s)=>{t={...se.useShellStore.getState().server[e]?.counts??{}};for(const e of s)delete t[e];for(const e of a)t[e.item]=e.quantity;se.useShellStore.setState(a=>({server:{...a.server,[e]:{counts:t,seen:[...et]}}}))},afterRead:()=>{se.useShellStore.getState().server[e]||se.useShellStore.setState(t=>({server:{...t.server,[e]:{counts:{},seen:[...et]}}}))},subscribe:()=>()=>{}}}const ot=new Set,dt=()=>!Pe('recipes.edit')&&Pe('recipes.create_own'),ut=e=>!!e.authorRef&&e.authorRef===Ee.getState().staffRef;function ct(e){return{name:'recipe_cards',table:'recipe_cards',list:()=>{const t=z.useStore.getState().menu;return ne.useCardStore.getState().cards.filter(t=>t.restaurantId===e).map(e=>({card:e,item:t.find(t=>t.id===e.menuItemId)}))},key:e=>e.card.id,rowKey:e=>String(e.id),syncable:t=>(0,le.isUuid)(t.card.id)&&!((0,w.isAnchorage)(e)&&(0,w.isDemoCard)(t.card))&&!(0,w.isPlaceholderCard)(t.card)&&(!dt()||ut(t.card)),writable:()=>Pe('recipes.edit')||Pe('recipes.create_own'),toRow:(t,a)=>{let s=t.card;(0,w.isAnchorage)(e)&&(s={...s,signOff:(0,w.demoActor)(s.signOff?.by)?null:s.signOff,allergensConfirmed:(0,w.demoActor)(s.allergensConfirmed?.by)?void 0:s.allergensConfirmed});const n=t.item&&(0,w.isAnchorage)(e)&&(0,w.demoActor)(t.item.signOff?.by)?{...t.item,signOff:null}:t.item;if(s.photo?.startsWith('local:')){const e=(0,Ce.photoPath)(a,s),t=lt(s.photo);t&&((0,ne.cachePhotoAs)(e,t),ft(e,t)),s={...s,photo:e}}const{row:r,extra:i}=(0,Ce.cardToRow)(s,a),{authorRef:o,...d}=s;return{...r,...i,doc:Qe({card:d,item:n})}},fromRow:t=>{const a=t.doc;if(!a?.card||(0,w.isPlaceholderCard)(a.card))return null;const s=t.signed_off_by&&t.signed_off_at?{by:t.signed_off_by,at:new Date(t.signed_off_at).toISOString()}:null,{authorRef:n,...r}=a.card;return{card:{...r,...t.author_ref?{authorRef:String(t.author_ref)}:{},id:String(t.id),restaurantId:e,signOff:s&&a.card.signOff?a.card.signOff:s,...t.photo_url?{photo:t.photo_url}:{}},item:a.item?{...a.item,restaurantId:e,signOff:(0,w.isAnchorage)(e)&&(0,w.demoActor)(a.item.signOff?.by)?null:a.item.signOff}:void 0}},supersededBy:(e,t)=>t.some(t=>t.card.menuItemId===e.card.menuItemId&&t.card.id!==e.card.id),apply:(e,t)=>{if(!Pe('recipes.edit')&&t.length){const e=new Set(dt()?ne.useCardStore.getState().cards.filter(e=>t.includes(e.id)&&ut(e)).map(e=>e.id):[]),a=new Set(t.filter(t=>!e.has(t)));ne.useCardStore.setState(e=>({cards:e.cards.map(e=>a.has(e.id)&&e.signOff?{...e,signOff:null}:e)})),t=[...e]}const a=new Set(t);ne.useCardStore.setState(t=>{const s=new Map(e.map(e=>[e.card.id,e.card])),n=new Set(e.map(e=>e.card.menuItemId)),r=t.cards.filter(e=>a.has(e.id)).map(e=>e.menuItemId),i=t.cards.filter(e=>!a.has(e.id)&&(s.has(e.id)||!n.has(e.menuItemId))).map(e=>s.get(e.id)??e),o=new Set(i.map(e=>e.id));return r.length&&z.useStore.setState(e=>({menu:e.menu.map(e=>r.includes(e.id)?{...e,hidden:!0}:e)})),{cards:[...i,...e.filter(e=>!o.has(e.card.id)).map(e=>e.card)],removed:[...t.removed,...r]}});const s=e.map(e=>e.item).filter(Boolean);s.length&&z.useStore.setState(e=>{const t=new Map(s.map(e=>[e.id,e])),a=e.menu.map(e=>t.get(e.id)??e),n=new Set(a.map(e=>e.id));return{menu:[...a,...s.filter(e=>!n.has(e.id))]}})},subscribe:e=>{const t=ne.useCardStore.subscribe((t,a)=>{t.cards!==a.cards&&e()}),a=z.useStore.subscribe((t,a)=>{t.menu!==a.menu&&e()});return()=>{t(),a()}}}}const lt=e=>(0,ne.readLocalPhoto)(e);async function ft(e,t){if(!ot.has(e)){ot.add(e);try{const a=await(await fetch(t)).blob(),{error:s}=await Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).upload(e,a,{upsert:!0,contentType:a.type||'image/jpeg'});if(s)throw s}catch(t){ot.delete(e),Ne({lastError:`Photo upload: ${String(t?.message??t)}`})}}}const pt=new Map,gt=(0,N.create)(()=>({n:0}));(0,ne.setStoragePhotoResolver)(e=>{const t=pt.get(e);return t&&Date.now()-t.at<3e6?t.url:(0,K.isSupabaseConfigured)()&&'off'!==Ee.getState().mode?(t||(pt.set(e,{url:'',at:Date.now()}),Te().storage.from(Ce.RECIPE_PHOTO_BUCKET).createSignedUrl(e,3600).then(({data:t})=>{t?.signedUrl&&(pt.set(e,{url:t.signedUrl,at:Date.now()}),gt.setState(e=>({n:e.n+1})),ne.useCardStore.setState(e=>({cards:[...e.cards]})))}).catch(()=>{})),t?.url||null):null});const mt=new Map;const _t=(e,t)=>{const a=(0,le.isUuid)(t)?t:(0,Ce.uuidFrom)(`sup:${e}:${t}`);return mt.set(a,t),a};function yt(e){return{name:'order_sheets',table:'suppliers',list:()=>re.useOrderSheets.getState().sheets[e]??[],key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:t=>!((0,w.isAnchorage)(e)&&'os-veg'===t.id&&t.placeholder),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:_t(t,e.id),venue_id:t,name:e.name||'Supplier',category:e.goods||null,contact:e.contact??null,phones:e.number?[e.number]:[],website:e.url||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,notes:e.notes||null,doc:{kind:'sheet',localId:e.id,sheet:Qe(e)}}),fromRow:e=>'sheet'!==e.doc?.kind?null:(mt.set(String(e.id),String(e.doc.localId)),e.doc.sheet),apply:(t,a)=>re.useOrderSheets.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=(s.sheets[e]??[]).filter(e=>!n.has(e.id)).map(e=>r.get(e.id)??e),o=new Set(i.map(e=>e.id));return{sheets:{...s.sheets,[e]:[...i,...t.filter(e=>!o.has(e.id))]}}}),subscribe:e=>re.useOrderSheets.subscribe((t,a)=>{t.sheets!==a.sheets&&e()}),matchKey:e=>({id:(0,le.isUuid)(e)?e:(0,Ce.uuidFrom)(`sup:${Ee.getState().venueId}:${e}`)})}}let ht=!1,St=!1;const wt=new Map,vt=new Map,kt=new Map,bt=new Map,It=e=>'owner'===e.role?'owner':'manager'===e.role?'Supervisor'===e.level?'supervisor':'manager':'Head Chef'===e.level?'head_chef':'staff',Rt=e=>'owner'===e?{role:'owner',level:'Owner'}:'manager'===e?{role:'manager',level:'Manager'}:'supervisor'===e?{role:'manager',level:'Supervisor'}:'head_chef'===e?{role:'staff',level:'Head Chef'}:{role:'staff',level:'Staff'},Ot=(e,t)=>({...e,managerAccess:t}),At=()=>({nickname:ht,display:St}),Ct=e=>{const t=!!(e.temp&&e.tempUntil&&e.tempUntil<(new Date).toLocaleDateString('en-CA',{timeZone:'Europe/London'})),a=Ot({role:e.role,level:e.level??Rt(It(e)).level},!0===e.managerAccess);return(0,F.staffSyncItem)({...e,...a,active:!t&&e.active,ownerAccess:!0===e.ownerAccess},At())};const Dt=(e=new Date)=>{const t=new Date(e);return t.setDate(t.getDate()-(t.getDay()+6)%7),t.toISOString().slice(0,10)},Ut=e=>{const t=Math.round(60*e)%1440;return`${String(Math.floor(t/60)).padStart(2,'0')}:${String(t%60).padStart(2,'0')}`},Tt=e=>{const t=ce.useOwner.getState().staff.find(t=>t.id===e);return!!t&&(0,u.isKitchenTeam)(t)},Et=2e3;function Nt(e,t){return t||!e.length||e.length>=Et?null:e=>(0,le.isUuid)(e.id)}function Pt(e=!1){return{name:'rota',table:'rota_shifts',authoritative:t=>e?Nt(t,Pe('rota.manage')):null,keepOnEmpty:()=>e&&!Pe('rota.manage'),list:()=>ce.useOwner.getState().shifts,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&wt.has(e.staffId)&&(Pe('rota.manage')||Tt(e.staffId)),writable:()=>Pe('rota.manage')||Pe('rota.kitchen'),toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId),staff_ref:e.staffId,shift_date:e.date??(()=>{const t=new Date(Dt());return t.setDate(t.getDate()+(e.day??0)),t.toISOString().slice(0,10)})(),start_time:Ut(e.start),end_time:Ut(e.end),published:!!e.published,doc:Qe(e)}),fromRow:e=>{if(!e.doc)return null;const t=e.doc,a=t.date??String(e.shift_date).slice(0,10),[s,n,r]=a.split('-').map(Number);return{...t,id:String(e.id),date:a,day:(new Date(s,n-1,r).getDay()+6)%7,published:!!e.published}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.shifts.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{shifts:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.shifts!==a.shifts&&e()})}}function Kt(){const e=Fe(62),t=e=>Pe('rota.manage')||e.staffId===Ee.getState().staffRef;return{name:'attendance',table:'attendance',list:()=>ce.useOwner.getState().attendance,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&t(e),writable:()=>'staff'===Ee.getState().kind,deletes:!1,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,writeBeforeRead:!0,urgent:e=>e.date>=Fe(2)&&e.staffId===Ee.getState().staffRef&&!e.adjusted&&!e.signOff&&!e.voided,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,clock_in:e.in??null,clock_out:e.out??null,breaks:Qe(e.breaks??[]),break_mins:e.breakMins??0,doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,e))}),fromRow:e=>{if(!e.doc)return null;const t=(0,v.privateAttendance)(ee.VENUE_RID,{...e.doc,id:String(e.id)});return'confirmed'===e.status?t.signOff={by:String(e.confirmed_by_name??t.signOff?.by??'Manager'),byId:t.signOff?.byId??'',at:e.confirmed_at?new Date(e.confirmed_at).toISOString():t.signOff?.at??''}:delete t.signOff,t},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.attendance.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{attendance:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.attendance!==a.attendance&&e()})}}function Mt(){const e=Fe(62);return{name:'time_requests',table:'time_requests',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().timeRequests,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&e.staffId===Ee.getState().staffRef&&'open'===e.status,writable:()=>'staff'===Ee.getState().kind,filter:t=>t.gte('work_date',e),inWindow:t=>t.date>=e,toRow:(e,t)=>({id:e.id,venue_id:t,staff_id:wt.get(e.staffId)??null,staff_ref:e.staffId,work_date:e.date,attendance_id:e.attendanceId&&(0,le.isUuid)(e.attendanceId)?e.attendanceId:null,kind:e.kind,suggested_in:e.suggestedIn??null,suggested_out:e.suggestedOut??null,note:(e.note??'').slice(0,300)||null,status:'open',doc:Qe({...e,status:'open'})}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),date:String(e.work_date).slice(0,10),attendanceId:e.attendance_id?String(e.attendance_id):t.attendanceId,kind:e.kind,suggestedIn:e.suggested_in?new Date(e.suggested_in).toISOString():void 0,suggestedOut:e.suggested_out?new Date(e.suggested_out).toISOString():void 0,note:e.note??'',at:t.at??new Date(e.created_at).toISOString(),status:e.status,resolvedBy:e.resolved_by_name??void 0,resolvedAt:e.resolved_at?new Date(e.resolved_at).toISOString():void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.timeRequests.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{timeRequests:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.timeRequests!==a.timeRequests&&e()})}}function xt(e){ce.leaveRemote.decide=t=>!(!Pe('rota.manage')||!(0,le.isUuid)(t.id)||'approved'!==t.status&&'declined'!==t.status)&&(H.mutationQueue.enqueue({table:'staff_leave',venueId:e,kind:'rpc',fn:'staff_leave_decide',rowKey:t.id,values:{p_id:t.id,p_status:t.status}}),!0),Le.push(()=>{ce.leaveRemote.decide=null})}function qt(e){ce.timesheetRemote.send=(t,a)=>{if(!Pe('rota.manage')||!(0,le.isUuid)(a.id))return!1;if('time_request_resolve'===t){const s=a;return H.mutationQueue.enqueue({table:'time_requests',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_status:s.status,p_doc:Qe(s)}}),!0}const s=a;if('attendance_void'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_reason:s.voided?.reason??'Removed',p_void:!0}}),!0;if('attendance_delete'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e}}),!0;if('attendance_add_past'===t)return!(!s.in||!s.out)&&(H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out,p_break_mins:s.breakMins??0,p_note:s.adjusted?.reason??'',p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0);if('attendance_confirm'===t)return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:t,rowKey:s.id,values:{p_id:s.id,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0;if(!s.in)return!1;const n=s.adjusted?.reason??'';return H.mutationQueue.enqueue({table:'attendance',venueId:e,kind:'rpc',fn:'attendance_override',rowKey:s.id,values:{p_id:s.id,p_venue:e,p_staff_ref:s.staffId,p_work_date:s.date,p_clock_in:s.in,p_clock_out:s.out??null,p_break_mins:s.breakMins??0,p_breaks:Qe(s.breaks??[]),p_reason:n,p_doc:Qe((0,v.privateAttendance)(ee.VENUE_RID,s))}}),!0},Le.push(()=>{ce.timesheetRemote.send=null})}function jt(e){return{name:'outbox',table:'outbox',mode:'insert',list:()=>z.useStore.getState().outbox.filter(t=>t.restaurantId===e),key:e=>e.id,rowKey:e=>String(e.local_id??e.id),syncable:()=>!0,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',new Date(Date.now()-2592e6).toISOString()),inWindow:()=>!1,toRow:(e,t)=>{return{id:(a=e.id,(0,le.isUuid)(a)?a:(0,Ce.uuidFrom)(`outbox:${a}`)),local_id:e.id,venue_id:t,channel:e.channel,kind:e.kind,to_address:e.to||'',to_name:e.toName||null,subject:e.subject??null,body:e.body,html:e.html??null,ref_type:e.refType,ref_id:(0,le.isUuid)(e.refId)?e.refId:null,ref:e.ref,status:e.status,provider:e.provider,error:e.error??null,created_at:e.at,doc:Qe(e)};var a},fromRow:t=>t.doc?{...t.doc,restaurantId:e}:null,apply:e=>z.useStore.setState(t=>{const a=new Set(t.outbox.map(e=>e.id));return{outbox:[...e.filter(e=>!a.has(e.id)),...t.outbox].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,300)}}),subscribe:e=>z.useStore.subscribe((t,a)=>{t.outbox!==a.outbox&&e()})}}const Lt=e=>z.useStore.getState().events.filter(t=>t.restaurantId===e&&!t.example);function Bt(e,t){if(!Array.isArray(t))return;const a=t.filter(e=>e&&'string'==typeof e.id&&'string'==typeof e.date&&'string'==typeof e.title).map(t=>({...t,restaurantId:e,example:!1}));z.useStore.setState(t=>({events:[...t.events.filter(t=>!(t.restaurantId===e&&!t.example)),...a]}))}function $t(e){return{name:'venue',table:'venues',venueColumn:'id',mode:'update',list:()=>{const t=z.useStore.getState(),a=t.restaurants.find(t=>t.id===e);return[Qe({restaurant:a,msgTemplates:t.msgTemplates[e]??{},display:ae.useFloor.getState().settings[e]??{},games:!1!==a?.settings?.games,events:Lt(e)})]},key:()=>'venue',rowKey:()=>'venue',syncable:()=>!0,writable:()=>Pe('venue.settings'),matchKey:()=>({}),toRow:e=>({name:e.restaurant?.name,settings:{...Ht??{},whatsapp:e.restaurant?.settings?.whatsapp||null,app:{...Ht?.app??{},restaurant:e.restaurant,events:e.events??[]},ops:{...Ht?.ops??{},msgTemplates:e.msgTemplates,display:e.display}},feature_flags:{...Ft??{},games:e.games,takeaway:!e.restaurant?.settings?.takeawayPaused}}),fromRow:t=>{Ft=t.feature_flags??{},Ht=t.settings??{};const a=t.settings?.app?.restaurant;if(!a)return null;const s='string'==typeof t.settings?.whatsapp?t.settings.whatsapp:void 0;return s&&!a.settings?.whatsapp&&(a.settings={...a.settings,whatsapp:s}),Qe({restaurant:{...a,id:e},msgTemplates:t.settings?.ops?.msgTemplates??{},display:t.settings?.ops?.display??{},games:!1!==t.feature_flags?.games,...Array.isArray(t.settings?.app?.events)?{events:t.settings.app.events}:{}})},apply:t=>{const a=t[0];a&&(z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e&&a.restaurant?(0,f.withVenueAddress)({...a.restaurant,id:e,settings:{...a.restaurant.settings,games:a.games}}):t),msgTemplates:{...t.msgTemplates,[e]:a.msgTemplates??{}}})),a.display&&Object.keys(a.display).length&&ae.useFloor.setState(t=>({settings:{...t.settings,[e]:a.display}})),a.events&&Bt(e,a.events))},subscribe:e=>{const t=z.useStore.subscribe((t,a)=>{t.restaurants===a.restaurants&&t.msgTemplates===a.msgTemplates&&t.events===a.events||e()}),a=ae.useFloor.subscribe((t,a)=>{t.settings!==a.settings&&e()});return()=>{t(),a()}}}}let Ft=null,Ht=null;const Wt=()=>new Date(Date.now()-2592e6).toISOString(),Qt=e=>{if(!e.startsWith('dm:'))return['all','kitchen','foh','managers'].includes(e)?e:null;const t=e.split(':').slice(1).map(e=>wt.get(e));return 2===t.length&&t[0]&&t[1]?`dm:${[t[0],t[1]].sort().join(':')}`:null},Vt=e=>{if(!e.startsWith('dm:'))return e;const t=e.split(':').slice(1).map(e=>vt.get(e));return 2===t.length&&t[0]&&t[1]?(0,be.dmId)(t[0],t[1]):null},Gt=()=>Ee.getState().perms.includes('*');function Jt(){const e=()=>Ee.getState().staffRef;return{name:'chat',table:'chat_messages',deletes:!1,list:()=>ce.useOwner.getState().chat.filter(e=>(0,le.isUuid)(e.id)).map(e=>Qe({id:e.id,ch:e.ch,from:e.from,text:e.text,photo:e.photo,at:e.at,removed:!!e.removed})),key:e=>e.id,rowKey:e=>String(e.id),syncable:t=>!!Qt(t.ch)&&(t.from===e()||Gt()&&!t.ch.startsWith('dm:')&&t.removed),writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('created_at',Wt()).order('created_at',{ascending:!1}),inWindow:e=>e.at>=Wt(),toRow:(e,t)=>{const a=Qt(e.ch);if(!a)throw new Error('chat: unknown person');const s='system'===e.from?null:wt.get(e.from)??null;return{id:e.id,venue_id:t,channel:a,from_staff:s,body:e.text??null,photo:e.photo??null,removed:e.removed,created_at:e.at}},fromRow:e=>{const t=Vt(String(e.channel));if(!t)return null;const a=String(e.from_device??''),s='car'===a?'car-device':'display'===a?'display-device':e.from_staff?vt.get(String(e.from_staff)):'system';return s?Qe({id:String(e.id),ch:t,from:s,text:e.body??void 0,photo:e.photo??void 0,at:new Date(e.created_at).toISOString(),removed:!!e.removed}):null},apply:(t,a)=>ce.useOwner.setState(s=>{const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e(),o=s.chat.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,...r.get(e.id)}:e),d=new Set(o.map(e=>e.id)),u=i&&s.chatRead?.[i]||{},c=t.filter(e=>!d.has(e.id)).map(e=>{return{...e,reactions:{},seenBy:e.from===i?[e.from]:i&&Date.parse(e.at)<=(t=e.ch,Math.max(Date.parse(u['*']??'')||0,Date.parse(u[t]??'')||0))?[i]:[]};var t});return{chat:c.length?[...o,...c].sort((e,t)=>e.at.localeCompare(t.at)):o}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.chat!==a.chat&&e()}),onRemote:(t,a)=>{if('upsert'!==a||t.removed)return;const s=String(t.from_device??''),n='car'===s?'car-device':'display'===s?'display-device':t.from_staff?vt.get(String(t.from_staff)):'system',r=Vt(String(t.channel)),i=e();if(!r||!i||n===i||Date.now()-new Date(t.created_at).getTime()>12e4)return;const o=ce.useOwner.getState();if((o.chatMuted[i]??[]).includes(r))return;if(!(0,be.inChannel)(r,o.staff.find(e=>e.id===i)))return;if((0,Ie.soundAllowed)())try{(0,Ie.chime)('soft')}catch{}const d='car-device'===n?'Car':'display-device'===n?'Display':'system'===n?'CoverCharge':o.staff.find(e=>e.id===n)?.name?.replace(' (example)','')??'The team',u=r.startsWith('dm:')?'sent you a message':`in ${'all'===r?'Everyone':'foh'===r?'Front of house':'kitchen'===r?'Kitchen':'managers'===r?'Managers':r}`,c=String(t.body??t.text??'').slice(0,120);(0,I.notify)({id:`chat:${t.id}`,icon:'\ud83d\udcac',kicker:'NEW MESSAGE',title:`${d} ${u}`,body:c||void 0,timeoutMs:7e3,testID:'chat-notice'})}}}async function Zt(e,t,a){const s=Ee.getState();if(!ke.useChatSync.getState().synced||!s.venueId||'staff'!==s.kind||s.staffRef!==e)return;const n=wt.get(e),r='*'===t?'*':Qt(t);if(n&&r)try{await Te().from('chat_reads').upsert({venue_id:s.venueId,staff_id:n,channel:r,read_at:a},{onConflict:'staff_id,channel'})}catch{}}async function zt(e){const t=Ee.getState().staffRef,a=t?wt.get(t):void 0;if(t&&a)try{const{data:s,error:n}=await Te().from('chat_reads').select('channel,read_at').eq('venue_id',e).eq('staff_id',a);if(n||!s?.length)return;const r={};for(const e of s){const t='*'===e.channel?'*':Vt(String(e.channel));t&&(r[t]=new Date(e.read_at).toISOString())}Object.keys(r).length&&ce.useOwner.getState().chatMarkRead(t,r)}catch{}}function Yt(e){return{name:'reminders',table:'venue_reminders',list:()=>{const t=T.useReminders.getState(),a=t.reminders.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'reminder',doc:Qe(a)}}),s=t.rules[e];return s?[...a,{id:s.id,kind:'break_rules',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'break_rules'===e.kind?'break_rules':'reminder',doc:e.doc??{}}),apply:(t,a)=>T.useReminders.setState(s=>{const n=new Set(a),r={...s.rules},i=t.filter(e=>'break_rules'===e.kind);for(const t of i)r[e]={...(0,E.clampRules)(t.doc),id:t.id,updatedAt:t.doc.updatedAt};r[e]&&n.has(r[e].id)&&delete r[e];const o=new Map(t.filter(e=>'reminder'===e.kind).map(t=>[t.id,{...t.doc,id:t.id,rid:e}])),d=s.reminders.filter(e=>!n.has(e.id)).map(e=>o.get(e.id)??e),u=new Set(d.map(e=>e.id));return{rules:r,reminders:[...d,...[...o.values()].filter(e=>!u.has(e.id))]}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.reminders===a.reminders&&t.rules===a.rules||e()})}}function Xt(e){const t=Fe(14);return{name:'reminder_done',table:'reminder_done',mode:'insert',deletes:!1,list:()=>T.useReminders.getState().done.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.reminderId)&&e.staffRef===Ee.getState().staffRef,writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t).order('done_at',{ascending:!1}),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,reminder_id:e.reminderId,for_date:e.forDate,staff_ref:e.staffRef,staff_name:e.staffName.slice(0,80),done_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,reminderId:String(t.reminder_id),forDate:String(t.for_date).slice(0,10),staffRef:t.staff_ref??'',staffName:t.staff_name??'Team',at:new Date(t.done_at).toISOString()}),apply:(e,t)=>T.useReminders.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.done.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{done:[...e.filter(e=>!i.has(e.id)),...r].sort((e,t)=>t.at.localeCompare(e.at)).slice(0,400)}}),subscribe:e=>T.useReminders.subscribe((t,a)=>{t.done!==a.done&&e()})}}function ea(e,t,a,s=()=>!0){const n=new Set(a),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!s(e)||!n.has(e.id)).map(e=>s(e)&&r.has(e.id)?r.get(e.id):e),o=new Set(i.map(e=>e.id));return[...i,...t.filter(e=>!o.has(e.id))]}const ta=e=>null==e||''===e?null:Number(e),aa=e=>e.filter(e=>!e.startsWith('data:')),sa=()=>Pe('takings.view');function na(e){const t=!sa();return{name:'cash_ups',table:'cash_ups',list:()=>pe.useCashUp.getState().cashUps.filter(a=>a.rid===e&&(!t||a.date===(0,b.tradingDay)())),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt&&(!t||e.date===(0,b.tradingDay)()&&!e.onServer),writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,filter:e=>t?e.eq('for_date',(0,b.tradingDay)()):e.gte('for_date',Fe(400)),...t?{inWindow:e=>e.date===(0,b.tradingDay)()}:{},toRow:(e,t)=>(0,C.cashUpToRow)(e,t),fromRow:t=>(0,C.cashUpFromRow)(t,e),apply:(t,a)=>pe.useCashUp.setState(s=>({cashUps:ea(s.cashUps,t.map(e=>{const t=s.cashUps.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.cashUps!==a.cashUps&&e()})}}function ra(e){return{name:'sales_reports',table:'sales_reports',list:()=>pe.useCashUp.getState().sales.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&!!e.confirmedAt,writable:()=>Pe('wages.manage')||(0,k.hasCashUpAccess)(),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,week_start:e.weekStart,vals:Qe(e.vals),categories:e.categories,photos:aa(e.photos),read_by:e.readBy??null,confirmed_by:e.confirmedBy??null,confirmed_at:e.confirmedAt??null,updated_at:(new Date).toISOString()}),fromRow:t=>({id:String(t.id),rid:e,weekStart:String(t.week_start),vals:t.vals??{},categories:t.categories??[],photos:t.photos??[],readBy:t.read_by??null,confirmedBy:t.confirmed_by??void 0,confirmedAt:t.confirmed_at??void 0,onServer:!0,unlockedUntil:t.unlocked_until??void 0,unlockedBy:t.unlocked_by??void 0}),apply:(t,a)=>pe.useCashUp.setState(s=>({sales:ea(s.sales,t.map(e=>{const t=s.sales.find(t=>t.id===e.id);return t&&!e.photos.length?{...e,photos:t.photos}:e}),a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.sales!==a.sales&&e()})}}function ia(e){return{name:'cashup_settings',table:'cashup_settings',conflict:'venue_id',list:()=>{const t=pe.useCashUp.getState().settings[e];return t?[t]:[]},key:e=>e.id,rowKey:()=>(0,pe.cashSettingsId)(e),syncable:e=>!!e.updatedAt,writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({venue_id:t,doc:Qe({cashFields:e.cashFields,salesFields:e.salesFields}),updated_at:(new Date).toISOString()}),fromRow:t=>({...t.doc,id:(0,pe.cashSettingsId)(e),updatedAt:t.updated_at??void 0}),apply:t=>pe.useCashUp.setState(a=>t[0]?{settings:{...a.settings,[e]:t[0]}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.settings!==a.settings&&e()})}}function oa(e){return{name:'day_tips',table:'day_tips',list:()=>pe.useCashUp.getState().tips.filter(t=>t.rid===e).map(e=>({...e,id:e.date})),key:e=>e.id,rowKey:e=>String(e.for_date),syncable:()=>!1,writable:()=>!1,deletes:!1,filter:e=>e.gte('for_date',Fe(120)),toRow:()=>({}),fromRow:t=>({id:String(t.for_date),rid:e,date:String(t.for_date),total:Number(t.total),postedAt:String(t.posted_at),postedBy:t.posted_by??void 0}),apply:t=>pe.useCashUp.setState(a=>{const s=new Map(t.map(e=>[e.date,e])),n=a.tips.filter(t=>!(t.rid===e&&s.has(t.date)));return{tips:[...t.map(({id:e,...t})=>t),...n]}}),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.tips!==a.tips&&e()})}}function da(e){return{name:'tips_pot_events',table:'tips_pot_events',mode:'insert',deletes:!1,list:()=>pe.useCashUp.getState().pot.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('wages.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,for_date:e.forDate??null,through_date:e.throughDate??null,amount:e.amount,reason:e.reason??null,by_name:e.by,at:e.at}),fromRow:t=>({id:String(t.id),rid:e,kind:'payout'===t.kind?'payout':'correction',forDate:t.for_date??void 0,throughDate:t.through_date??void 0,amount:ta(t.amount)??0,reason:t.reason??void 0,by:String(t.by_name),at:String(t.at)}),apply:(t,a)=>pe.useCashUp.setState(s=>({pot:ea(s.pot,t,a,t=>t.rid===e)})),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.pot!==a.pot&&e()})}}function ua(e){return{name:'tips_settings',table:'tips_settings',conflict:'venue_id',deletes:!1,list:()=>{const t=pe.useCashUp.getState().show[e];return t?[{id:'show',...t}]:[]},key:e=>e.id,rowKey:()=>'show',syncable:()=>!0,writable:()=>Pe('wages.manage'),toRow:(e,t)=>({venue_id:t,show_today:e.showToday,show_pot:e.showPot,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'show',showToday:!1!==e.show_today,showPot:!1!==e.show_pot}),apply:t=>pe.useCashUp.setState(a=>t[0]?{show:{...a.show,[e]:{showToday:t[0].showToday,showPot:t[0].showPot}}}:a),subscribe:e=>pe.useCashUp.subscribe((t,a)=>{t.show!==a.show&&e()})}}function ca(e){return{name:'scheduled_notifications',table:'scheduled_notifications',list:()=>fe.useNotifs.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings'),deletes:!1,toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,doc:Qe(s),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>fe.useNotifs.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>fe.useNotifs.subscribe((t,a)=>{t.items!==a.items&&e()})}}function la(e){return{name:'order_lists',table:'order_lists',list:()=>{const t=ge.useOrderLists.getState(),a=t.lists.filter(t=>t.rid===e&&(0,le.isUuid)(t.id)).map(e=>{const{rid:t,...a}=e;return{id:e.id,kind:'list',doc:Qe(a)}}),s=t.settings[e];return s?[...a,{id:s.id,kind:'settings',doc:Qe(s)}]:a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),deletes:!1,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'settings'===e.kind?'settings':'list',doc:e.doc??{}}),apply:(t,a)=>ge.useOrderLists.setState(s=>{const n={...s.settings};for(const a of t.filter(e=>'settings'===e.kind))n[e]={...me.DEFAULT_ORDER_LIST_SETTINGS,...a.doc,id:a.id};const r=t.filter(e=>'list'===e.kind).map(t=>({...t.doc,id:t.id,rid:e}));return{settings:n,lists:ea(s.lists,r,a,t=>t.rid===e)}}),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.lists===a.lists&&t.settings===a.settings||e()})}}function fa(e){const t=()=>Pe('venue.settings')||Pe('suppliers.order');return{name:'order_list_items',table:'order_list_items',list:()=>ge.useOrderLists.getState().items.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:a=>(0,le.isUuid)(a.id)&&(0,le.isUuid)(a.listId)&&(t()||'open'===a.status&&(0,ge.orderSettingsOf)(e).allowStaff),writable:()=>'staff'===Ee.getState().kind,deletes:!0,toRow:(e,a)=>{const{rid:s,...n}=e;return{id:e.id,venue_id:a,list_id:e.listId,status:e.status,added_by_ref:(t()?e.addedBy:Ee.getState().staffRef)||null,doc:Qe(n),updated_at:(new Date).toISOString()}},fromRow:t=>({...t.doc,id:String(t.id),listId:String(t.list_id),status:t.status??'open',rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({items:ea(s.items,t,a,t=>t.rid===e)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.items!==a.items&&e()})}}function pa(e){const t=Fe(400);return{name:'order_list_history',table:'order_list_history',mode:'insert',deletes:!1,list:()=>ge.useOrderLists.getState().history.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('venue.settings')||Pe('suppliers.order'),filter:e=>e.gte('finished_at',t).order('finished_at',{ascending:!1}).limit(300),toRow:(e,t)=>{const{rid:a,...s}=e;return{id:e.id,venue_id:t,list_id:e.listId,finished_at:e.finishedAt,finished_by:e.finishedByName.slice(0,80),doc:Qe(s)}},fromRow:t=>({...t.doc,id:String(t.id),rid:e}),apply:(t,a)=>ge.useOrderLists.setState(s=>({history:ea(s.history,t,a,t=>t.rid===e).sort((e,t)=>t.finishedAt.localeCompare(e.finishedAt)).slice(0,300)})),subscribe:e=>ge.useOrderLists.subscribe((t,a)=>{t.history!==a.history&&e()})}}function ga(e){return{name:'venue_clock_area',table:'venue_clock_area',conflict:'venue_id',deletes:!1,list:()=>{const t=_e.useClockArea.getState().areas[e];return t&&t.updatedAt?[{id:'area',doc:Qe(t)}]:[]},key:()=>'area',rowKey:()=>'area',syncable:()=>!0,matchKey:()=>({}),writable:()=>Pe('venue.settings'),toRow:(e,t)=>({venue_id:t,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:'area',doc:e.doc??{}}),apply:t=>{const a=t[0];a&&_e.useClockArea.setState(t=>({areas:{...t.areas,[e]:{...(0,v.venueClockArea)(e,a.doc),updatedAt:a.doc.updatedAt,updatedBy:a.doc.updatedBy}}}))},subscribe:e=>_e.useClockArea.subscribe((t,a)=>{t.areas!==a.areas&&e()})}}function ma(e){return{name:'daily_tasks',table:'daily_tasks',deletes:!1,list:()=>{const t=we.useDailyTasks.getState(),a=[],s=t.library[e];s?.updatedAt&&a.push({id:(0,we.libraryRowId)(e),kind:'library',doc:Qe({items:s.items,updatedAt:s.updatedAt})});for(const[s,n]of Object.entries(t.people)){const[t,r]=s.split('|');t===e&&n.updatedAt&&a.push({id:(0,we.personRowId)(e,r),kind:'person',staffRef:r,doc:Qe({tasks:n.tasks,updatedAt:n.updatedAt})})}return a},key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);if(!t)return!1;if('staff'!==t.role)return!0;if('person'!==e.kind)return!1;const a=ce.useOwner.getState().staff.find(t=>t.id===e.staffRef);return!!a&&(0,ve.canEditTasks)(t,a)},writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,kind:e.kind,staff_ref:e.staffRef??null,doc:e.doc,updated_at:(new Date).toISOString()}),fromRow:e=>({id:String(e.id),kind:'library'===e.kind?'library':'person',staffRef:e.staff_ref??void 0,doc:e.doc??{}}),apply:t=>we.useDailyTasks.setState(a=>{const s={...a.library},n={...a.people};for(const a of t)'library'===a.kind?s[e]={items:a.doc.items??[],updatedAt:a.doc.updatedAt}:a.staffRef&&(n[(0,we.personKey)(e,a.staffRef)]={tasks:a.doc.tasks??[],updatedAt:a.doc.updatedAt});return{library:s,people:n}}),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.library===a.library&&t.people===a.people||e()})}}function _a(e){const t=Fe(7);return{name:'daily_task_ticks',table:'daily_task_ticks',list:()=>we.useDailyTasks.getState().ticks.filter(t=>t.rid===e),key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>{const t=Ee.getState();return e.byRef===t.staffRef||Pe('staff.manage')},writable:()=>'staff'===Ee.getState().kind,filter:e=>e.gte('for_date',t),inWindow:e=>e.forDate>=t,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffRef,task_id:e.taskId,for_date:e.forDate,ticked_by_ref:e.byRef,ticked_by_name:e.byName.slice(0,80),ticked_at:e.at}),fromRow:t=>({id:String(t.id),rid:e,staffRef:String(t.staff_ref),taskId:String(t.task_id),forDate:String(t.for_date).slice(0,10),byRef:String(t.ticked_by_ref??''),byName:String(t.ticked_by_name??''),at:String(t.ticked_at)}),apply:(t,a)=>we.useDailyTasks.setState(s=>({ticks:ea(s.ticks,t,a,t=>t.rid===e)})),subscribe:e=>we.useDailyTasks.subscribe((t,a)=>{t.ticks!==a.ticks&&e()})}}function ya(e,t=!1){const a=Fe(14);return{name:'sold_out_items',table:'sold_out_items',conflict:'venue_id,item_id',list:()=>Re.useSoldOut.getState().entries.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),filter:e=>e.gte('marked_at',a),inWindow:e=>e.at.slice(0,10)>=a,toRow:(e,a)=>({id:(0,Ce.uuidFrom)(`soldout:${a}:${e.itemId}`),venue_id:a,item_id:e.itemId.slice(0,80),name:e.name.slice(0,120),is_on:e.on,marked_at:e.at,by_name:(e.by||'Staff').slice(0,80),clear_after:e.clearAfter??null,...t?{auto:!!e.auto,kept:!!e.kept}:{}}),fromRow:a=>({rid:e,itemId:String(a.item_id),name:String(a.name??''),on:!0===a.is_on,at:String(a.marked_at),by:String(a.by_name??''),clearAfter:a.clear_after?String(a.clear_after):void 0,...t?{auto:!0===a.auto,kept:!0===a.kept}:{}}),apply:(t,a)=>Re.useSoldOut.setState(s=>{const n=new Set(a);return{entries:[...s.entries.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>{return s=a,(t=e).rid===s.rid&&t.itemId===s.itemId;var t,s})))),...t]}}),subscribe:e=>Re.useSoldOut.subscribe((t,a)=>{t.entries!==a.entries&&e()}),afterRead:()=>{Oe.autoSync.soldOutRead.add(e)}}}function ha(e){return{name:'sold_out_links',table:'sold_out_links',conflict:'venue_id,item_id',list:()=>Oe.useSoldOutLinks.getState().links.filter(t=>t.rid===e),key:e=>e.itemId,rowKey:e=>String(e.item_id),syncable:()=>!0,deletes:!1,writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:(0,Ce.uuidFrom)(`soldoutlink:${t}:${e.itemId}`),venue_id:t,item_id:e.itemId.slice(0,80),uses:e.uses.slice(0,10).map(e=>({key:String(e.key).slice(0,40),qty:Math.max(0,Math.min(99,Number(e.qty)||0))})),auto:!!e.auto,updated_at:e.at,updated_by:(e.by||'Staff').slice(0,80)}),fromRow:t=>({rid:e,itemId:String(t.item_id),uses:(Array.isArray(t.uses)?t.uses:[]).map(e=>({key:String(e.key??''),qty:Number(e.qty)||0})).filter(e=>e.key&&e.qty>0),at:String(t.updated_at??''),by:String(t.updated_by??''),...!0===t.auto?{auto:!0}:{}}),apply:(t,a)=>Oe.useSoldOutLinks.setState(s=>{const n=new Set(a);return{links:[...s.links.filter(a=>!(a.rid===e&&(n.has(a.itemId)||t.some(e=>e.itemId===a.itemId)))),...t]}}),subscribe:e=>Oe.useSoldOutLinks.subscribe((t,a)=>{t.links!==a.links&&e()}),afterRead:()=>{Oe.autoSync.linksRead.add(e)}}}async function Sa(e,t="*"){const a='*'===t?`table:${e}`:`table:${e}.${t}`;try{const s=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:n}=await Promise.race([Te().from(e).select(t,{head:!0,count:'exact'}).limit(1),s]);return n?!!/fetch|network|Failed/i.test(n.message)&&L.kv.get(a,!1):(L.kv.set(a,!0),!0)}catch{return L.kv.get(a,!1)}}async function wa(){const e=Ee.getState().venueId;if(e)try{const{data:t}=await Te().from('push_settings').select('push_live').eq('venue_id',e).maybeSingle();ba.setState({live:!!t?.push_live,known:!0})}catch{}}const va='order-list-logos';const ka=new Map;const ba=(0,N.create)(()=>({live:!1,known:!1}));async function Ia(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('venue_reminders').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('reminders:ok',!1):(L.kv.set('reminders:ok',!0),!0)}catch{return L.kv.get('reminders:ok',!1)}}async function Ra(){try{const e=new Promise(e=>setTimeout(()=>e({error:{message:'Failed: timed out'}}),5e3)),{error:t}=await Promise.race([Te().from('chat_messages').select('id').limit(1),e]);return t?!!/fetch|network|Failed/i.test(t.message)&&L.kv.get('chat:ok',!1):(L.kv.set('chat:ok',!0),!0)}catch{return L.kv.get('chat:ok',!1)}}const Oa=(e,t)=>Qe({id:String(e.id),venue:t,body:String(e.body??''),kind:'yesno'===e.kind?'yesno':'up',up:Number(e.up_count??0),yes:Number(e.yes_count??0),no:Number(e.no_count??0),hidden:!!e.hidden,reply:e.reply??void 0,replyAt:e.reply_at??void 0,postedOn:String(e.posted_on??'').slice(0,10)}),Aa='id,body,kind,up_count,yes_count,no_count,hidden,reply,reply_at,posted_on';function Ca(e){return{name:'hr_questions',table:'hr_questions',deletes:!1,list:()=>U.useHr.getState().questions.filter(t=>t.venue===e&&(0,le.isUuid)(t.id)),key:e=>e.id,rowKey:e=>String(e.id),syncable:()=>!1,writable:()=>!1,toRow:e=>({id:e.id}),fromRow:t=>Oa(t,e),filter:e=>e.gte('posted_on',new Date(Date.now()-10368e6).toISOString().slice(0,10)),apply:(e,t)=>{const a=new Set(t);U.useHr.setState(t=>{const s=new Map(e.map(e=>[e.id,e])),n=t.questions.filter(e=>!a.has(e.id)).map(e=>s.get(e.id)??e),r=new Set(n.map(e=>e.id));return{questions:[...n,...e.filter(e=>!r.has(e.id))]}})},subscribe:e=>U.useHr.subscribe((t,a)=>{t.questions!==a.questions&&e()})}}function Da(e,t){const a=(t,a,s)=>{H.mutationQueue.enqueue({table:'hr_questions',venueId:e,kind:'rpc',fn:t,rowKey:a,values:s})};Object.assign(U.hrRemote,{live:!0,checkout:t=>a('hr_checkout',t.token,{p_venue:e,p_day:t.day,p_token:t.token,p_morale:t.morale,p_staffing:t.staffing,p_question:t.question??null,p_kind:t.kind??'up',p_shout_to:t.shoutTo??null,p_shout_body:t.shoutBody??null}),post:(t,s,n,r)=>a('hr_post_question',s,{p_venue:e,p_id:s,p_body:n,p_kind:r}),vote:(e,t,s)=>a('hr_vote',e,{p_question:e,p_token:t,p_vote:s}),moderate:(e,t,s)=>a('hr_moderate',e,{p_question:e,p_action:t,p_reason:s}),reply:(e,t)=>a('hr_reply',e,{p_question:e,p_reply:t}),trend:async(t,a,s)=>{try{const{data:t,error:n}=await Te().rpc('hr_trend',{p_venue:e,p_from:a,p_to:s});return n?null:(t??[]).map(e=>({day:String(e.day).slice(0,10),answers:Number(e.answers),morale:Number(e.morale),staffing:null==e.staffing?null:Number(e.staffing),short:Number(e.short),perfect:Number(e.perfect),over:Number(e.over)}))}catch{return null}},shouts:async(a,s)=>{try{const{data:a,error:n}=await Te().from('hr_shoutouts').select('id,day,to_name,body').eq('venue_id',e).gte('day',s).order('day',{ascending:!1}).limit(20);return n?null:(a??[]).map(e=>({id:String(e.id),venue:t,day:String(e.day).slice(0,10),to:String(e.to_name),body:e.body??void 0}))}catch{return null}},log:async()=>{try{const{data:a,error:s}=await Te().from('hr_mod_log').select('id,question_id,action,reason,by_name,at').eq('venue_id',e).order('at',{ascending:!1}).limit(30);return s?null:(a??[]).map(e=>({id:String(e.id),venue:t,questionId:String(e.question_id??''),action:e.action,reason:e.reason??void 0,by:String(e.by_name??'A manager'),at:String(e.at)}))}catch{return null}},refresh:async()=>{try{const{data:a,error:s}=await Te().from('hr_questions').select(Aa).eq('venue_id',e).order('posted_on',{ascending:!1}).limit(200);s||U.useHr.getState().setRemoteBoard(t,(a??[]).map(e=>Oa(e,t)))}catch{}}}),Le.push(()=>{Object.assign(U.hrRemote,{live:!1,checkout:null,post:null,vote:null,moderate:null,reply:null,trend:null,shouts:null,log:null,refresh:null})})}const Ua='pair:v1',Ta='staff:v1',Ea='staff:rejoin:v1';async function Na(e){const t=(0,p.claimInviteRpc)(),a={p_token:e,p_app:Me,p_device:(0,D.deviceId)()},s=await Te().rpc(t,{...a,p_phone:(0,D.phoneKey)()});return s.error&&('PGRST202'===s.error.code||/could not find the function/i.test(s.error.message))?Te().rpc(t,a):s}async function Pa(){if('display'===Me||'customer'===Me||ye.PITCH)return'none';const e=await L.kv.get(Ea,null);if(!e)return'none';try{await Ma();const{data:t,error:a}=await Na(e);if(a)return(0,O.inviteRefusal)(a.message)?(await L.kv.remove(Ea),await L.kv.remove(Ta),'refused'):'offline';const s=t?.[0];return s?(await L.kv.set(Ta,{kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name}),'ok'):(await L.kv.remove(Ea),'refused')}catch{return'offline'}}const Ka=e=>/jwt|refresh|token|401|not authenticated|invalid claim|session/i.test(String(e?.message??e))&&!/fetch|network/i.test(String(e?.message??e));async function Ma(){qe();const{data:e}=await Te().auth.getSession();if(!e.session)for(let e=0;;e++){const{error:t}=await Te().auth.signInAnonymously();if(!t)return;const a=429===t.status||/rate|too many/i.test(t.message);if(!a||e>=2){if(a)throw new Error('Too many people are connecting from this network right now. Wait a few minutes, or switch to mobile data, and open the link again.');throw t}Ne({message:'Lots of people are connecting at once. Trying again in a moment\u2026'}),await new Promise(t=>setTimeout(t,0===e?15e3:45e3))}}async function xa(e){if(ye.PITCH)return{status:'refused',message:/^pitch-other-phone/.test(e)?(0,O.inviteRefusal)('already linked to another phone'):'This link has been replaced or switched off. Ask your manager for a new one.'};if(!(0,K.isSupabaseConfigured)())return{status:'off'};try{await Ma();const{data:t,error:a}=await Na(e);if(a){const e=(0,O.inviteRefusal)(a.message);if(e){try{localStorage.removeItem((0,ee.venueKey)(`cc-pending-invite:${Me}`))}catch{}return{status:'refused',message:e}}throw a}const s=t?.[0];if(!s)return{status:'refused',message:'This link has been replaced or switched off. Ask your manager for a new one.'};const n={kind:'staff',venueId:s.venue_id,venueSlug:s.venue_slug,venueName:s.venue_name,staffRef:s.external_ref,staffUuid:s.staff_id,role:s.role_key,displayName:s.display_name};return await L.kv.set(Ta,n),await L.kv.set(Ea,e),Be&&Qa(),{status:'ok',id:n}}catch(e){const t=String(e?.message??e);return Ne({lastError:`Sign-in: ${t}`}),{status:'offline',message:t}}}const qa='car:request:v1',ja=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check the car has Wi-Fi or mobile data, then try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function La(){await L.kv.remove(Ua),await L.kv.remove(Ta),await L.kv.remove(qa),D.useSession.getState().meId&&D.useSession.getState().signOut()}const Ba=e=>{const t=String(e?.message??e);return/fetch|network/i.test(t)?'No connection. Check your signal and try again.':t.replace(/^.*?:\s*(?=[A-Z])/,'')};async function $a(){if(!(0,K.isSupabaseConfigured)())return!1;try{return await Ma(),!0}catch{return!1}}const Fa=async(e,t={})=>{if(ye.PITCH)return(0,he.pitchRpc)(e,t);const{data:a,error:s}=await Te().rpc(e,t);if(s)throw s;return a};let Ha=null;async function Wa(){for(const e of Le)try{e()}catch{}Le=[],je.forEach(e=>e.stop()),je=[],Ha&&(clearInterval(Ha),Ha=null)}async function Qa(){await Wa(),await Ja()}async function Va(){if(!(0,K.isSupabaseConfigured)()||'customer'===Me||ye.PITCH)return!1;try{qe();const{data:e}=await Te().auth.getSession();if(e.session){const{error:e}=await Te().auth.refreshSession();if(!e)return!0}if('display'===Me)return!1;if(!await L.kv.get(Ea,null))return!1;if(e.session)try{await Te().auth.signOut({scope:'local'})}catch{}return'ok'===await Pa()&&(Qa(),!0)}catch{return!1}}(0,c.setSessionMender)(Va);let Ga=ee.VENUE_RID;async function Ja(){try{const e='undefined'!=typeof navigator?navigator.storage:null;e?.persist&&e.persist()}catch{}try{const e='undefined'!=typeof window?window.CoverChargeNative:null;e&&'function'==typeof e.checkUpdate&&/CoverChargePhone\//.test(navigator.userAgent)&&e.checkUpdate()}catch{}const e=Ga;try{if(Ne({mode:'connecting'}),await H.mutationQueue.load(),'customer'===Me)return void await ts(e);let t=await L.kv.get(Ua,null),a=await L.kv.get(Ta,null);if(Y.IS_CAR&&!t&&a){const e=(0,X.migrateCarStaffIdentity)(a);e&&(t=e,await L.kv.set(Ua,t)),await L.kv.remove(Ta),a=null,D.useSession.getState().meId&&D.useSession.getState().signOut()}if(ee.IS_ISOLATED_VENUE&&(t&&!(0,ee.venueIdentityAllowed)(t.venueId,t.venueSlug)||a&&!(0,ee.venueIdentityAllowed)(a.venueId,a.venueSlug)))return void Ne({mode:'display'===Me?'unpaired':'signin',perms:[],message:'This sign-in belongs to a different venue.'});let{data:s}=await Te().auth.getSession();if('display'!==Me&&!Y.IS_CAR&&a&&!s.session){const t=await Pa();if('offline'===t)return Ne({venueId:a.venueId,venueSlug:a.venueSlug,venueName:a.venueName,kind:a.kind,role:a.role,staffRef:a.staffRef,staffUuid:a.staffUuid,mode:'offline'}),void setTimeout(()=>{Ga===e&&Qa()},6e4);'refused'===t&&a.staffRef&&D.useSession.getState().meId===a.staffRef&&D.useSession.getState().signOut(),a=await L.kv.get(Ta,null),({data:s}=await Te().auth.getSession())}const n='display'===Me||Y.IS_CAR?t:a;if(!s.session||!n)return void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[]});let r=[];try{const e=(await Fa('whoami')??[]).filter(e=>e.venue_id===n.venueId);if(!e.length)return'display'===Me||Y.IS_CAR?await L.kv.remove(Ua):(await L.kv.remove(Ta),await L.kv.remove(Ea)),'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId===n.staffRef&&D.useSession.getState().signOut(),void Ne({mode:'display'===Me||Y.IS_CAR?'unpaired':'signin',perms:[],message:'display'===Me?'This display was unpaired by a manager.':Y.IS_CAR?'This car was unpaired by an owner. Make a new code and approve it from Managers.':'Open your invite link again to connect.'});r=[...new Set(e.flatMap(e=>e.permissions??[]))],'device'===n.kind&&n.canWrite&&r.push('device.write')}catch(t){if(!(0,M.isOnline)()||/fetch|network/i.test(String(t?.message)))Ne({mode:'offline'});else if(Ka(t)&&'display'!==Me){const{error:t}=await Te().auth.refreshSession();t&&'ok'===await Pa()&&setTimeout(()=>{Ga===e&&Qa()},500)}r=Ee.getState().perms,'device'===n.kind&&n.canWrite&&!r.includes('device.write')&&(r=[...r,'device.write'])}Ne({venueId:n.venueId,venueSlug:n.venueSlug,venueName:n.venueName,kind:n.kind,role:n.role,staffRef:n.staffRef,staffUuid:n.staffUuid,perms:r}),!Y.IS_CAR&&'staff'===n.kind&&n.staffRef&&D.useSession.getState().meId!==n.staffRef&&(D.useSession.getState().signIn(n.staffRef),ce.useOwner.setState({staffAs:n.staffRef})),Y.IS_CAR&&(D.useSession.getState().meId&&D.useSession.getState().signOut(),ce.useOwner.setState({previewRole:'owner'})),await za(n.venueId,e,n.kind)}catch(e){Ne({mode:'local',lastError:String(e?.message??e)})}}const Za=new Set(['venues','staff','bookings','walk_ins','blocks','table_plans','takeaway_orders','stock_items','stock_events','stock_counts','recipe_cards','suppliers','supplier_orders','rota_shifts','attendance','time_requests','game_scores','floor_live','chat_messages','venue_reminders','reminder_done']);async function za(e,a,s){if(!(0,ee.venueIdentityAllowed)(e,a))throw new Error('Different venue: sync refused.');const n='staff'===s||Y.IS_CAR&&'device'===s;await Cs(a),Le.push($s(e));try{const{data:t}=await Te().from('roles').select('id,key').eq('venue_id',e);for(const e of t??[])kt.set(e.key,e.id),bt.set(e.id,e.key)}catch{}const r=[$t(a),{protect:!0,name:'staff',table:'staff',conflict:'venue_id,external_ref',list:()=>ce.useOwner.getState().staff.map(Ct),key:e=>e.id,rowKey:e=>String(e.external_ref??e.id),syncable:e=>!e.name.includes('(example)'),writable:()=>Pe('staff.manage'),deletes:!1,revision:e=>(0,F.staffRevision)(e,At()),toRow:(e,t)=>(0,F.staffRow)(e,t,At(),e.managerAccess||e.ownerAccess?null:kt.get(It(e))),fromRow:e=>{if(!e.external_ref)return null;wt.set(String(e.external_ref),String(e.id)),vt.set(String(e.id),String(e.external_ref)),qs.set(String(e.external_ref),e.avatar_path??null);const t=Ot(Rt(bt.get(String(e.role_id))),!0===e.manager_access);return(0,F.staffSyncItem)({id:String(e.external_ref),name:e.display_name,job:e.job_title??'',active:!1!==e.active,dept:e.department??'',nickname:e.nickname??null,displayClock:!!e.display_clock,temp:!!e.temp,tempUntil:e.temp_until??null,...t,ownerAccess:!0===e.owner_access,bookingWrite:'boolean'==typeof e.can_change_bookings?e.can_change_bookings:void 0},At())},apply:e=>ce.useOwner.setState(t=>{const a=new Map(e.map(e=>[e.id,e])),s=t.staff.map(e=>a.has(e.id)?{...e,...a.get(e.id)}:e),n=new Set(s.map(e=>e.id));return{staff:[...s,...e.filter(e=>!n.has(e.id)).map(e=>({...e}))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.staff!==a.staff&&e()}),afterRead:()=>{Bs()},onRemote:()=>{Bs()}},{name:'pay',table:'staff_private',conflict:'staff_id',list:()=>{const e=ce.useOwner.getState(),t=oe.useSetup.getState().sites[Ga]?.staffGrade??{};return e.staff.filter(e=>wt.has(e.id)).map(a=>Qe({id:a.id,hourly:e.hourly[a.id]??null,salaried:!!a.salaried,noTax:!!a.noTax,grade:t[a.id]||void 0}))},key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('wages.manage'),deletes:!1,toRow:(e,t)=>({staff_id:wt.get(e.id),venue_id:t,hourly_rate:null==e.hourly?null:e.hourly/100,salaried:e.salaried,no_tax:e.noTax,pay_grade:e.grade??null}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?Qe({id:t,hourly:null==e.hourly_rate?null:Math.round(100*Number(e.hourly_rate)),salaried:!!e.salaried,noTax:!!e.no_tax,grade:e.pay_grade||void 0}):null},apply:e=>ce.useOwner.setState(t=>{const a={...t.hourly},s=new Map(e.map(e=>[e.id,e]));for(const t of e)null==t.hourly?delete a[t.id]:a[t.id]=t.hourly;if(e.length){const t=oe.useSetup.getState().sites[Ga],a={...t?.staffGrade??{}};let s=!1;for(const t of e)(a[t.id]||void 0)!==t.grade&&(s=!0,t.grade?a[t.id]=t.grade:delete a[t.id]);s&&oe.useSetup.getState().patch(Ga,{staffGrade:a})}return{hourly:a,staff:t.staff.map(e=>s.has(e.id)?{...e,salaried:s.get(e.id).salaried,noTax:s.get(e.id).noTax}:e)}}),subscribe:e=>{const t=ce.useOwner.subscribe((t,a)=>{t.hourly===a.hourly&&t.staff===a.staff||e()}),a=oe.useSetup.subscribe((t,a)=>{t.sites[Ga]?.staffGrade!==a.sites[Ga]?.staffGrade&&e()});return()=>{t(),a()}}},Ve(a,!1),Ve(a,!0),Je(a),Ye(a),Ge(a),Xe(a),rt(a),it(a),yt(a),{name:'supplier_directory',table:'suppliers',list:()=>ce.useOwner.getState().suppliers,key:e=>e.id,rowKey:e=>String(e.doc?.localId??e.id),syncable:e=>(0,le.isUuid)(e.id),writable:()=>Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,name:e.name||'Supplier',category:e.category,contact:e.contact||null,phones:e.phones.filter(Boolean),email:e.email||null,website:e.website||null,account_ref:e.account||null,cutoff:e.cutoff||null,order_days:e.orderDays,delivery_days:e.deliveryDays,doc:{kind:'directory',localId:e.id,supplier:Qe(e)}}),fromRow:e=>'directory'===e.doc?.kind?e.doc.supplier:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.suppliers.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{suppliers:[...r,...e.filter(e=>!i.has(e.id))]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.suppliers!==a.suppliers&&e()})},{name:'supplier_orders',table:'supplier_orders',list:()=>ce.useOwner.getState().supplierOrders,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId),writable:()=>Pe('suppliers.order')||Pe('suppliers.manage'),toRow:(e,t)=>({id:e.id,venue_id:t,supplier_id:e.supplierId,order_date:e.date||$e(),items:[{text:e.items}],amount:Math.round(e.amount||0),status:'sent',by_name:e.by,doc:Qe(e)}),fromRow:e=>e.doc?{...e.doc,id:String(e.id)}:null,apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.supplierOrders.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{supplierOrders:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.supplierOrders!==a.supplierOrders&&e()})},ct(a),Ks(a)];Pe('wages.view')&&r.push(Ms(a)),n&&(r.push(Pt(!0),Kt(),Mt(),jt(a)),qt(e)),n&&await Sa('staff_leave')&&(r.push({name:'staff_leave',table:'staff_leave',mode:'insert',deletes:!1,list:()=>ce.useOwner.getState().leave,key:e=>e.id,rowKey:e=>String(e.id),syncable:e=>(0,le.isUuid)(e.id)&&/^\d{4}-\d{2}-\d{2}$/.test(e.from)&&/^\d{4}-\d{2}-\d{2}$/.test(e.to)&&e.to>=e.from&&(e.staffId===Ee.getState().staffRef&&'pending'===e.status||Pe('rota.manage')),writable:()=>'staff'===Ee.getState().kind,toRow:(e,t)=>({id:e.id,venue_id:t,staff_ref:e.staffId,from_date:e.from,to_date:e.to,reason:(e.reason??'').slice(0,200)||null,status:e.status,doc:Qe(e)}),fromRow:e=>{const t=e.doc??{};return{...t,id:String(e.id),staffId:String(e.staff_ref),from:String(e.from_date).slice(0,10),to:String(e.to_date).slice(0,10),reason:e.reason??t.reason??'Holiday',status:e.status,by:e.requested_by_name??t.by,decidedBy:e.decided_by_name??void 0}},apply:(e,t)=>ce.useOwner.setState(a=>{const s=new Set(t),n=new Map(e.map(e=>[e.id,e])),r=a.leave.filter(e=>!s.has(e.id)).map(e=>n.get(e.id)??e),i=new Set(r.map(e=>e.id));return{leave:[...e.filter(e=>!i.has(e.id)),...r]}}),subscribe:e=>ce.useOwner.subscribe((t,a)=>{t.leave!==a.leave&&e()})}),Za.add('staff_leave'),xt(e));const o=n&&await Ra();if(ke.useChatSync.setState({synced:o,checked:!0}),Le.push(()=>ke.useChatSync.setState({synced:!1})),o&&r.push(Jt(),{name:'chat_extra',table:'chat_channel_extra',conflict:'venue_id,channel,staff_id',list:()=>Object.entries(be.useKitchenExtra.getState().extra).map(([e,t])=>({id:e,include:t})),key:e=>e.id,rowKey:e=>vt.get(String(e.staff_id))??String(e.staff_id),syncable:e=>wt.has(e.id),writable:()=>Pe('staff.manage'),filter:e=>e.eq('channel','kitchen'),matchKey:e=>({channel:'kitchen',staff_id:wt.get(e)??e}),toRow:(e,t)=>({venue_id:t,channel:'kitchen',staff_id:wt.get(e.id),include:e.include}),fromRow:e=>{const t=vt.get(String(e.staff_id));return t?{id:t,include:!!e.include}:null},apply:(e,t)=>be.useKitchenExtra.setState(a=>{const s={...a.extra};return t.forEach(e=>{delete s[e]}),e.forEach(e=>{s[e.id]=e.include}),{extra:s}}),subscribe:e=>be.useKitchenExtra.subscribe((t,a)=>{t.extra!==a.extra&&e()})}),n&&await Sa('hr_questions')&&(r.push(Ca(a)),Za.add('hr_questions'),Da(e,a)),'guest'!==s&&'customer'!==Me&&await Sa('temp_readings')&&(r.push((0,V.tempUnitsSpec)(ue.useSafety,st),(0,V.tempReadingsSpec)(ue.useSafety,nt)),Za.add('temp_units'),Za.add('temp_readings')),'guest'!==s&&'customer'!==Me&&await Sa('cooksafe_records')&&(r.push((0,G.cooksafeSpec)(ue.useSafety,J.useCookSafe,ue.isSeedAccident,nt)),Za.add('cooksafe_records')),'guest'!==s&&await Sa('sold_out_items')?(r.push(ya(a,await Sa('sold_out_items','auto'))),Za.add('sold_out_items')):Oe.autoSync.soldOutRead.add(a),'guest'!==s&&await Sa('sold_out_links')?(r.push(ha(a)),Za.add('sold_out_links')):Oe.autoSync.linksRead.add(a),T.useReminders.getState().ensure(a),'guest'!==s&&await Ia()&&(r.push(Yt(a)),n&&r.push(Xt(a))),fe.useNotifs.getState().ensure(a),ge.useOrderLists.getState().ensure(a),n){ht=await Sa('staff','nickname'),St=await Sa('staff','display_clock');const[e,t,s,n]=await Promise.all([Sa('scheduled_notifications'),Sa('order_lists'),Sa('venue_clock_area'),Sa('daily_tasks')]);we.useDailyTasks.getState().ensure(a),n&&(r.push(ma(a),_a(a)),Za.add('daily_tasks'),Za.add('daily_task_ticks')),e&&(r.push(ca(a)),wa()),t&&r.push(la(a),fa(a),pa(a)),s&&r.push(ga(a));for(const[a,n]of[[e,'scheduled_notifications'],[t,'order_lists'],[t,'order_list_items'],[t,'order_list_history'],[s,'venue_clock_area']])a&&Za.add(n)}if('guest'!==s&&await Sa('day_tips')){r.push(oa(a));for(const e of['day_tips','tips_pot_events','tips_settings'])Za.add(e);await Sa('tips_pot_events')&&r.push(da(a),ua(a)),n&&(sa()||(0,pe.forgetPastTakings)(a,(0,b.tradingDay)()),r.push(na(a),ia(a)),Za.add('cash_ups'),sa()&&(r.push(ra(a)),Za.add('sales_reports')),t(i[78])(i[77],i.paths).then(e=>e.refreshCashAccess()))}'device'!==s||n||(r.push(Pt(),Kt()),await Sa('scheduled_notifications')&&r.push(ca(a)));let d=!1;const u=()=>{if(Y.IS_CAR&&n&&Pe('recipes.edit'))return!0;const e=ce.useOwner.getState().staff.find(e=>e.id===Ee.getState().staffRef);return!!e&&e.active&&Pe('recipes.edit')&&(0,h.costsAllowedFor)(e)};n&&u()&&await Sa('ingredient_prices')&&(r.push((0,y.gpSyncSpec)('ing',u)),Za.add('ingredient_prices'),await Sa('card_costs')&&(r.push((0,y.gpSyncSpec)('card',u)),Za.add('card_costs')),await Sa('kitchen_deliveries')&&(r.push((0,y.gpSyncSpec)('del',u)),Za.add('kitchen_deliveries')),await Sa('kitchen_stock_counts')&&(r.push((0,y.gpSyncSpec)('count',u)),Za.add('kitchen_stock_counts'))),(0,Ue.specialsSyncOn)()&&'guest'!==s&&await Sa('specials_boards')&&(r.push((0,Ue.specialsBoardSpec)(a,()=>Pe('recipes.edit')||Pe('floor.manage')||Pe('*'))),Za.add('specials_boards'));const c={onActivity:()=>Ne({lastSyncAt:(new Date).toISOString()}),onError:(e,t)=>Ne({lastError:`${e}: ${t}`}),onSuspect:(t,s)=>{Ne({lastError:`${t}: held back, ${s}`}),d||(d=!0,(async()=>{try{if(!(await Fa('whoami')??[]).some(t=>t.venue_id===e))return void(Ga===a&&Qa());for(const a of je){if(a.spec.name!==t)continue;const{count:s,error:n}=await Te().from(a.spec.table).select('*',{count:'exact',head:!0}).eq(a.spec.venueColumn??'venue_id',e);!n&&(s??0)>0&&a.allowMassRemoveOnce()}}catch{}finally{d=!1}})())},onSkipped:(e,t)=>{'bookings'!==e&&'walk_ins'!==e||W.useBookingSaves.getState().mark({id:t,table:e,why:ps()??'this screen could not send it'}),'temp_readings'!==e&&'temp_units'!==e||Q.useTempSaves.getState().mark({id:t,table:e,why:ks(e)??'this screen could not send it'})}};je=r.map(t=>new Z.EntityBridge(t,e,c)),await Promise.all(je.map(e=>e.start()));let l=0;const f=async()=>{if(!(l&&Date.now()-l<6e4)){l=Date.now();try{await p()}finally{l=0}}},p=async()=>{if(n&&(0,M.isOnline)())try{const t=await Fa('whoami');if(!t?.some(t=>t.venue_id===e))return void(Ga===a&&Qa())}catch(e){if(Ka(e)){if(Y.IS_CAR)return void(Ga===a&&Qa());const e=await Pa();return void('ok'!==e&&'refused'!==e||Ga===a&&Qa())}}let t=0;for(const[a,s]of je.entries()){const n='chat'===r[a]?.name;try{await s.read(),t++,n&&(ke.useChatSync.getState().error&&ke.useChatSync.setState({error:void 0}),await zt(e))}catch(e){const t=String(e?.message??e);if((n||/fetch|network|Failed/i.test(t))&&ke.useChatSync.setState({error:t||'unknown error'}),/fetch|network|Failed/i.test(t))break}}if(t){const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({mode:'live',lastSyncAt:e,lastServerAt:e}),H.mutationQueue.flush()}else Ne({mode:'offline'});if(!Pe('wages.view')){const e=Ee.getState().staffRef;ce.useOwner.setState(t=>({hourly:e&&null!=t.hourly[e]?{[e]:t.hourly[e]}:{}}))}};await Promise.race([f(),new Promise(e=>setTimeout(e,3e4))]);const g=new Map;for(const e of je)g.set(e.spec.table,[...g.get(e.spec.table)??[],e]);const m=[...g.keys()].filter(e=>Za.has(e)).map(e=>({table:e,venueColumn:g.get(e)[0].spec.venueColumn}));let _=!1;const S=(0,Z.venueChannel)(e,m,(e,t,a)=>{for(const s of g.get(e)??[])s.remote(t,a);const s=(new Date).toISOString();Ne({lastSyncAt:s,lastServerAt:s})},e=>{Ne({realtime:e}),'SUBSCRIBED'===e?(_&&f(),_=!1):'CHANNEL_ERROR'!==e&&'TIMED_OUT'!==e&&'CLOSED'!==e||(_=!0)});Le.push(()=>{Te().removeChannel(S)}),Le.push((0,M.onConnectivity)(e=>{e&&f()}));const w=je.filter(e=>'bookings'===e.spec.table||'walk_ins'===e.spec.table),v=(0,x.superviseSync)({fastMs:Xa(Me),readFast:async()=>{for(const e of w)await e.read()},readAll:f,flush:()=>{H.mutationQueue.flush()},wake:()=>{H.mutationQueue.retryNow()},restart:()=>{Ga===a&&Qa()},realtime:()=>Ee.getState().realtime,lastServerAt:()=>{const e=Ee.getState().lastServerAt;return e?Date.parse(e):0},markServer:()=>{const e=(new Date).toISOString();(0,M.setOnline)(!0),Ne({lastSyncAt:e,lastServerAt:e,mode:'live'})},isAuthError:Ka,refreshAuth:async()=>{await Te().auth.refreshSession()},heartbeat:()=>Ya(e),doc:'undefined'!=typeof document?document:null,win:'undefined'!=typeof window?window:null});Le.push(v.stop)}async function Ya(e){const t=Ee.getState(),a='undefined'!=typeof navigator?String(navigator.userAgent??''):'';await Fa('sync_heartbeat',{p_venue:e,p_device:(0,D.deviceId)()??'unknown',p_app:Me,p_version:j.APP_VERSION,p_last_synced_at:t.lastServerAt??null,p_realtime:t.realtime??null,p_pending:(t.waiting??0)+(t.pending??0),p_failed:t.failed??0,p_user_agent:a.slice(0,300)})}const Xa=e=>'display'===e?15e3:3e4;'undefined'!=typeof window&&(window.__ccSync=()=>({...Ee.getState(),queue:H.mutationQueue.pending.map(e=>e.table),failedTables:H.mutationQueue.failed.map(e=>`${e.table}: ${e.lastError??''}`.slice(0,200))}),ye.PITCH&&(window.__ccSyncPreview=e=>Ne(e)));const es='guest:sent:v1';async function ts(e){Ne({kind:'guest',venueSlug:e,perms:[]});try{const t=(await Fa('public_venue',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)}))?.[0];if(t&&(!ee.IS_ISOLATED_VENUE||t.id===ee.VENUE_UUID)){Ne({venueId:t.id,venueName:t.name}),await Cs(e);const a=t.app?.restaurant;a&&z.useStore.setState(t=>({restaurants:t.restaurants.map(t=>t.id===e?(0,f.withVenueAddress)({...a,id:e}):t)})),Bt(e,t.app?.events)}await as(e),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}catch{Ne({mode:(0,M.isOnline)()?'local':'offline'})}const t=setInterval(()=>{as(e).catch(()=>{})},6e4);Le.push(()=>clearInterval(t)),ee.IS_ISOLATED_VENUE||await ss(e)}async function as(e){const t=await Fa('public_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];if(t.length){const a=new Map(t.map(e=>[String(e.menu_item_id??e.doc?.item?.id??''),e]));ne.useCardStore.setState(t=>({cards:t.cards.map(t=>{if(t.restaurantId!==e)return t;const s=a.get(t.menuItemId);return s?{...(0,d.applyServerCard)(t,s),photo:s.photo_url||void 0}:t.signOff?{...t,signOff:null}:t})}))}const a=t.map(t=>(0,d.serverItem)(t,e)).filter(e=>!!e);a.length&&z.useStore.setState(e=>{const t=new Map(a.map(e=>[e.id,e])),s=e.menu.map(e=>t.get(e.id)??e),n=new Set(s.map(e=>e.id));return{menu:[...s,...a.filter(e=>!n.has(e.id))]}});try{const t=await Fa('public_takeaway_menu',{p_venue_slug:(0,l.queuedDatabaseSlug)(e)})??[];o.useTakeawayMenu.getState().set(e,{on:t.filter(e=>e.on_menu).map(e=>String(e.item_id)),soldOut:t.filter(e=>e.sold_out).map(e=>String(e.item_id)),at:(new Date).toISOString()})}catch{}}async function ss(e){let t=await L.kv.get(es,{}),a=!1;const s=new Date(Date.now()-1728e5).toISOString(),n=async()=>{if(!a){a=!0;try{const a=z.useStore.getState(),n=a.bookings.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!a.walkIn&&!t[a.id]&&a.createdAt>=s),r=a.orders.filter(a=>a.restaurantId===e&&(0,le.isUuid)(a.id)&&!t[a.id]&&a.createdAt>=s&&'table'!==a.type);if(n.length||r.length){if(!await $a())return;for(const a of n)try{const s=(await Fa('guest_create_booking',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_booking:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];t={...t,[a.id]:'booking'};const n={};s?.status&&s.status!==a.status&&(n.status=s.status),'string'==typeof s?.ref&&s.ref&&s.ref!==a.ref&&(n.ref=s.ref),Object.keys(n).length&&z.useStore.setState(e=>({bookings:e.bookings.map(e=>e.id===a.id?{...e,...n}:e)}))}catch(e){/fetch|network/i.test(String(e?.message))||(t={...t,[a.id]:'failed'},Ne({lastError:`Booking: ${e?.message}`}))}for(const a of r)try{const s=(await Fa('guest_create_takeaway',{p_venue_slug:(0,l.queuedDatabaseSlug)(e),p_order:{...Qe(a),...(0,R.takeGuard)(a.id),allergies:We(a.allergies)}}))?.[0];if(t={...t,[a.id]:'order'},s&&z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?rs(e,s):e)})),'boolean'==typeof a.marketingOptIn&&a.email)try{await Fa('guest_marketing_consent',{p_order:a.id,p_opt_in:a.marketingOptIn})}catch{}}catch(e){const s=String(e?.message??'');/fetch|network/i.test(s)||(t={...t,[a.id]:'failed'},Ne({lastError:`Order: ${s}`}),z.useStore.setState(e=>({orders:e.orders.map(e=>e.id===a.id?{...e,status:'cancelled',payment:{state:'refused',error:is(s)}}:e)})))}await L.kv.set(es,t)}for(const e of a.bookings)if('booking'===t[e.id]&&'cancelled'===e.status)try{await Fa('guest_cancel_booking',{p_id:e.id}),t={...t,[e.id]:'cancelled'},await L.kv.set(es,t)}catch{}if(Object.values(t).some(e=>'booking'===e||'order'===e)){const e=await Fa('guest_my_items')??[],t=new Map(e.map(e=>[String(e.id),e]));z.useStore.setState(e=>({bookings:e.bookings.map(e=>{const a=t.get(e.id);return a&&a.status&&a.status!==e.status&&'declined'!==a.status?{...e,status:a.status}:'declined'===a?.status&&'cancelled'!==e.status?{...e,status:'cancelled'}:e}),orders:e.orders.map(e=>{const a=t.get(e.id);if(!a)return e;const s=rs(e,a);return ns(s)===ns(e)?e:s})})),Ne({mode:'live',lastSyncAt:(new Date).toISOString()})}}catch{Ne({mode:(0,M.isOnline)()?Ee.getState().mode:'offline'})}finally{a=!1}}};Le.push(z.useStore.subscribe((e,t)=>{e.bookings===t.bookings&&e.orders===t.orders||setTimeout(()=>{n()},200)})),Ha=setInterval(()=>{n()},15e3),os=()=>{n()},n()}const ns=e=>JSON.stringify([e.status,e.readyBy,e.accepted,e.payment,e.total,e.paid,e.ref]);function rs(e,t){const a=t.doc??{},s=(e,t)=>'number'==typeof e&&Number.isFinite(e)?e:t;return{...e,status:t.status??a.status??e.status,readyBy:a.readyBy??e.readyBy,accepted:a.accepted??e.accepted,...a.payment?{payment:a.payment}:{},...Array.isArray(a.lines)&&a.lines.length?{lines:a.lines}:{},subtotal:s(a.subtotal,e.subtotal),total:s(a.total,e.total),paid:s(a.paid,e.paid),tip:s(a.tip,e.tip),giftCardApplied:s(a.giftCardApplied,e.giftCardApplied),ref:'string'==typeof a.ref&&a.ref?a.ref:'string'==typeof t.ref&&t.ref?t.ref:e.ref}}const is=e=>{const t=e.replace(/^.*?:\s*(?=[A-Z])/,'').trim();return/^[A-Z][^{}<>]{3,200}[.!?]$/.test(t)?t:'The restaurant\u2019s system couldn\u2019t take this order. Nothing has been charged. Please try again or ring the restaurant.'};let os=null;const ds={bridges:()=>je,restart:Qa};function us(){const e=Ee.getState();return'offline'===e.mode?'there is no connection right now. It saves by itself when the connection is back':'live'!==e.mode&&'connecting'!==e.mode?'this screen is not connected to the shared venue':'guest'===e.kind||'device'===e.kind&&!Pe('device.write')?'this screen can only read. A manager can allow changes for it in Managers':null}function cs(){const e=je.find(e=>'stock_events'===e.spec.table);if(!e||us())return 0;const t=new Date(Date.now()-2592e5).toISOString();let a=0;for(const s of[...e.spec.list()].sort((e,t)=>e.at.localeCompare(t.at)))s.at'stock_events'===e.table&&e.rowKey===s.id)&&e.spec.syncable(s)&&(H.mutationQueue.enqueue({table:'stock_events',venueId:e.venueId,kind:'insert',rowKey:s.id,values:e.spec.toRow(s,e.venueId),conflictKey:'id'}),a++);return a}async function ls(){const e=je.find(e=>'stock_events'===e.spec.table);if(e)try{await e.read()}catch{}cs();try{await H.mutationQueue.retryNow()}catch{}}Ee.subscribe((e,t)=>{e.perms!==t.perms&&e.perms.includes('device.write')&&!t.perms.includes('device.write')&&setTimeout(()=>{ls()},3e3)});const fs=['bookings','walk_ins'];function ps(){const e=Ee.getState();return Ke()?'guest'===e.kind?'this screen can only read bookings, so the change would stay on this screen only':'device'!==e.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'unpaired'===e.mode||'signin'===e.mode?'this screen is not connected to the venue, so the change would stay on this screen only':null}const gs=()=>je.filter(e=>fs.includes(e.spec.table)),ms=e=>H.mutationQueue.failed.some(t=>fs.includes(t.table)&&t.rowKey===e);function _s(e=!1){return ps()?0:gs().reduce((t,a)=>t+a.resendUnsaved(t=>!e&&ms(t)&&!!W.useBookingSaves.getState().notSaved[t]),0)}async function ys(e=!1){const t=ps();if(t)return t;for(const e of gs())try{await e.read()}catch{}_s(e);try{await H.mutationQueue.retryNow()}catch{}return e&&hs(),null}function hs(){const e=gs()[0]?.venueId??'',t=W.useBookingSaves.getState(),a=new Set(gs().flatMap(e=>e.unsavedKeys()));for(const s of Object.keys(t.notSaved))a.has(s)||ms(s)||fs.some(t=>H.mutationQueue.hasPending(t,e,s))||t.clear(s)}H.mutationQueue.onFailed(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{fs.includes(e.table)&&W.useBookingSaves.getState().clear(e.rowKey)});let Ss=null;const ws=(e=2500)=>{Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,ys(!1)},e)};(0,M.onConnectivity)(e=>{e&&ws()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&ws(3e3)});const vs=['temp_readings','temp_units'];function ks(e="temp_readings"){const t=Ee.getState();return Ke()?'guest'===t.kind?'this screen can only read the food safety log':'temp_units'!==e||st()?'device'!==t.kind||Pe('device.write')?null:'this screen can only read. A manager can allow changes for it in Managers \u203a Displays':'only the Head Chef, managers and owners can change the units':'unpaired'===t.mode||'signin'===t.mode?'this screen is not connected to the venue, so it is kept on this screen only':null}const bs=()=>je.filter(e=>vs.includes(e.spec.table));async function Is(e=!1){const t=ks();if(t)return t;for(const e of bs())try{await e.read()}catch{}const a=bs()[0]?.venueId??'';for(const t of bs())t.resendUnsaved(a=>{return!e&&(s=t.spec.table,n=a,H.mutationQueue.failed.some(e=>e.table===s&&e.rowKey===n));var s,n});try{await H.mutationQueue.retryNow()}catch{}if(e){const e=Q.useTempSaves.getState();for(const t of Object.values(e.notSaved)){const s=bs().find(e=>e.spec.table===t.table);!s||s.unsavedKeys().includes(t.id)||H.mutationQueue.hasPending(t.table,a,t.id)||e.clear((0,Q.tempKey)(t.table,t.id))}}return null}H.mutationQueue.onFailed(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().mark({id:e.rowKey,table:e.table,why:(0,$.plainReason)({...e.lastErr,message:e.lastErr?.message??e.lastError},'refused')})}),H.mutationQueue.onDone(e=>{vs.includes(e.table)&&Q.useTempSaves.getState().clear((0,Q.tempKey)(e.table,e.rowKey))});let Rs=null;const Os=(e=3e3)=>{Rs&&clearTimeout(Rs),Rs=setTimeout(()=>{Rs=null,Is(!1)},e)};(0,M.onConnectivity)(e=>{e&&Os()}),Ee.subscribe((e,t)=>{('live'===e.mode&&'live'!==t.mode||e.perms!==t.perms&&Pe('device.write')&&!t.perms.includes('device.write')&&!t.perms.includes('*'))&&Os(3500)});const As='golive:v1:';async function Cs(e){'live'!==z.useStore.getState().clock.mode&&z.useStore.setState({clock:{mode:'live',simStartMs:Date.now(),anchorRealMs:Date.now()}}),g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)?await Ns(e):(await L.kv.get(As+e,!1)||await Ns(e),await L.kv.get(Ts+e,!1)||(Es(e),await L.kv.set(Ts+e,!0)),await L.kv.get(Ds+e,!1)||(Us(),await L.kv.set(Ds+e,!0)))}const Ds='golive:v3:';function Us(){const e=e=>JSON.stringify(e).includes('(example)');try{de.useKitchen.setState(t=>({waste:t.waste.filter(t=>!e(t)),stockTakes:t.stockTakes.filter(t=>!e(t)),deliveries:t.deliveries.filter(e=>'dl-today-fish'!==e.id&&'dl-today-veg'!==e.id)}))}catch{}}const Ts='golive:v2:';function Es(e){const t=e=>JSON.stringify(e).includes('(example)');z.useStore.setState(t=>({customer:{...t.customer,name:'',email:'',phone:'',allergies:[],allergyConsent:!1,marketingOptIn:{}},stampCards:t.stampCards.filter(t=>t.restaurantId!==e),giftCards:t.giftCards.filter(t=>t.restaurantId!==e),ratings:t.ratings.filter(t=>t.restaurantId!==e),events:t.events.filter(t=>!(t.example&&(t.restaurantId===e||null===t.restaurantId)))})),ce.useOwner.setState(e=>({referrals:[],coats:[],merchOrders:[],lost:[],customerTags:{},offers:e.offers.filter(e=>!t(e)),changeRequests:e.changeRequests.filter(e=>!t(e)),campaigns:e.campaigns.filter(e=>!t(e)),supplierOrders:e.supplierOrders.filter(e=>!t(e)),chat:e.chat.filter(e=>e.id.startsWith('m-seed-')).map((e,t)=>({...e,at:new Date(Date.now()-6e4*(5-t)).toISOString()}))}))}async function Ns(e){if(g.LIVE_VENUE_BUILD&&(0,g.isLiveVenue)(e)){const t=(0,m.stripCoreLiveSamples)(z.useStore.getState()),a=(0,de.stripKitchenExamples)(de.useKitchen.getState()),s=ce.useOwner.getState(),n=(0,m.stripOwnerLiveSamples)(s),r={accidents:ue.useSafety.getState().accidents.filter(e=>!(0,ue.isSeedAccident)(e))},i=(e,t)=>Object.keys(t).some(a=>JSON.stringify(e[a])!==JSON.stringify(t[a]));i(z.useStore.getState(),t)&&(await(0,_.archiveChefCache)('core',z.useStore.getState()),z.useStore.setState(t)),i(de.useKitchen.getState(),a)&&(await(0,_.archiveChefCache)('kitchen',de.useKitchen.getState()),de.useKitchen.setState(a)),i(s,n)&&(await(0,_.archiveChefCache)('owner',s),ce.useOwner.setState(n)),i(ue.useSafety.getState(),r)&&(await(0,_.archiveChefCache)('safety',ue.useSafety.getState()),ue.useSafety.setState(r));const o=(0,U.stripHrSamples)(U.useHr.getState());i(U.useHr.getState(),o)&&(await(0,_.archiveChefCache)('hr',U.useHr.getState()),U.useHr.setState(o));const d=(0,y.stripGpSamples)(y.useGpCalc.getState());i(y.useGpCalc.getState(),d)&&(await(0,_.archiveChefCache)('gp',y.useGpCalc.getState()),y.useGpCalc.setState(d));const u=re.useOrderSheets.getState(),c={sheets:{...u.sheets,anchorage:(u.sheets.anchorage||[]).filter(e=>!('os-veg'===e.id&&e.placeholder))}};i(u,c)&&(await(0,_.archiveChefCache)('order-sheets',u),re.useOrderSheets.setState(c));const l=ne.useCardStore.getState(),f={cards:l.cards.filter(e=>!(0,g.isLiveVenue)(e.restaurantId)||!(0,w.isDemoCard)(e)),log:l.log.filter(e=>!(0,w.demoActor)(e.by))};return i(l,f)&&(await(0,_.archiveChefCache)('recipe-cards',l),ne.useCardStore.setState(f)),void await L.kv.set(As+e,!0)}const t=t=>t.restaurantId===e&&!(0,le.isUuid)(t.id);z.useStore.setState(a=>({bookings:a.bookings.filter(e=>!t(e)),orders:a.orders.filter(e=>!t(e)),waitlist:a.waitlist.filter(t=>t.restaurantId!==e),walkIns:Object.fromEntries(Object.entries(a.walkIns).filter(([t])=>!t.includes(e)))})),te.useBlocks.setState(t=>({blocks:t.blocks.filter(t=>t.rid!==e||(0,le.isUuid)(t.id))})),ae.useFloor.setState(t=>({live:{...t.live,[e]:{}}})),ce.useOwner.setState(e=>({shifts:e.shifts.filter(e=>(0,le.isUuid)(e.id)),attendance:e.attendance.filter(e=>(0,le.isUuid)(e.id)),timeRequests:e.timeRequests.filter(e=>(0,le.isUuid)(e.id)),leave:e.leave.filter(e=>(0,le.isUuid)(e.id)),swaps:[]}));try{de.useKitchen.setState(e=>(0,de.stripKitchenExamples)(e))}catch{}ce.useOwner.setState(e=>({suppliers:e.suppliers.filter(e=>(0,le.isUuid)(e.id)),supplierOrders:e.supplierOrders.filter(e=>(0,le.isUuid)(e.id)&&(0,le.isUuid)(e.supplierId))}));try{ue.useSafety.setState(e=>({accidents:e.accidents.filter(e=>{return!String(e.id).startsWith('acc-ex')&&(t=e,!JSON.stringify(t).includes('(example)'));var t})}))}catch{}await L.kv.set(As+e,!0)}const Ps=(e,t)=>Qe({name:e,stage:t.stage||void 0,dirty:t.dirty||void 0,blocked:t.blocked||void 0,note:t.note||void 0});function Ks(e){return{name:'floor_live',table:'floor_live',conflict:'venue_id,table_name',list:()=>Object.entries(ae.useFloor.getState().live[e]??{}).map(([e,t])=>Ps(e,t)),key:e=>e.name,rowKey:e=>String(e.table_name),syncable:e=>e.name.length>0&&e.name.length<=20,writable:()=>'staff'===Ee.getState().kind||Pe('device.write'),deletes:!1,matchKey:e=>({table_name:e}),toRow:(e,t)=>({venue_id:t,table_name:e.name,stage:e.stage??null,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note?e.note.slice(0,200):null,updated_by:(0,X.actorStamp)({isCar:Y.IS_CAR,kind:Ee.getState().kind,staffRef:Ee.getState().staffRef,fallback:Me})}),fromRow:e=>Ps(String(e.table_name),{stage:e.stage??void 0,dirty:!!e.dirty,blocked:!!e.blocked,note:e.note??void 0}),apply:(t,a)=>ae.useFloor.setState(s=>{const n={...s.live[e]??{}};for(const e of t){const{name:t,...a}=e;n[t]=a}for(const e of a)delete n[e];return{live:{...s.live,[e]:n}}}),subscribe:e=>ae.useFloor.subscribe((t,a)=>{t.live!==a.live&&e()})}}function Ms(e){return{name:'pay_grades',table:'pay_grades',conflict:'venue_id,grade_id',list:()=>(oe.useSetup.getState().sites[e]?.grades??oe.DEFAULT_GRADES).map((e,t)=>({id:e.id,name:e.name,pence:e.pence,sort:t})),key:e=>e.id,rowKey:e=>String(e.grade_id),syncable:e=>!!e.id&&!!e.name,writable:()=>Pe('wages.manage'),matchKey:e=>({grade_id:e}),toRow:(e,t)=>({venue_id:t,grade_id:e.id,name:e.name.slice(0,60),pence:Math.max(0,Math.min(1e5,Math.round(e.pence))),sort:e.sort}),fromRow:e=>({id:String(e.grade_id),name:String(e.name),pence:Number(e.pence),sort:Number(e.sort??0)}),apply:(t,a)=>{if(!t.length&&!a.length)return;const s=oe.useSetup.getState().sites[e]?.grades??[],n=new Map(s.map((e,t)=>[e.id,{...e,sort:t}]));for(const e of t)n.set(e.id,e);for(const e of a)n.delete(e);const r=[...n.values()].sort((e,t)=>e.sort-t.sort).map(e=>({id:e.id,name:e.name,pence:e.pence}));oe.useSetup.getState().patch(e,{grades:r})},subscribe:t=>oe.useSetup.subscribe((a,s)=>{a.sites[e]?.grades!==s.sites[e]?.grades&&t()})}}const xs='staff-avatars',qs=new Map;let js=!1;const Ls=e=>new Promise((t,a)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=a,s.readAsDataURL(e)});async function Bs(){if(!js){js=!0;try{for(const[e,t]of qs){const a=ie.useAvatars.getState().photos[e];if(!t){a?.path&&ie.useAvatars.setState(t=>{const a={...t.photos};return delete a[e],{photos:a}});continue}if(a?.path===t)continue;if(a&&!a.path&&e===Ee.getState().staffRef)continue;const{data:s,error:n}=await Te().storage.from(xs).download(t);if(n||!s)continue;const r=await Ls(s);r.startsWith('data:image/')&&ie.useAvatars.setState(a=>({photos:{...a.photos,[e]:{dataUrl:r,at:(new Date).toISOString(),path:t}}}))}}catch{}finally{js=!1}}}function $s(e){const t=async()=>{const t=Ee.getState().staffRef,a=t?wt.get(t)??Ee.getState().staffUuid:void 0;if(!t||!a||'staff'!==Ee.getState().kind)return;const s=ie.useAvatars.getState().photos[t];try{const n=qs.get(t),r=t=>{t&&t.startsWith(`${e}/${a}-`)&&Te().storage.from(xs).remove([t]).catch(()=>{})};if(!s){const e=!!ie.useAvatars.getState().clears?.[t];return e&&n&&(await Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}),qs.set(t,null),r(n)),void(e&&ie.useAvatars.getState().doneClear(t))}if(s.path)return;const i=await(await fetch(s.dataUrl)).blob();if(i.size>512e3)return void Ne({lastError:'Avatar: picture too large to share'});const o='image/jpeg'===i.type?'jpg':'image/webp'===i.type?'webp':'png',d=`${e}/${a}-${Date.now().toString(36)}.${o}`,{error:u}=await Te().storage.from(xs).upload(d,i,{upsert:!1,contentType:i.type||'image/png'});if(u)throw u;await Fa('set_staff_avatar',{p_staff_ref:t,p_path:d}),qs.set(t,d),n!==d&&r(n),ie.useAvatars.setState(e=>e.photos[t]?.dataUrl===s.dataUrl?{photos:{...e.photos,[t]:{...s,path:d}}}:e)}catch(e){Ne({lastError:`Avatar: ${String(e?.message??e)}`})}},a={photos:ie.useAvatars.getState().photos},s=ie.useAvatars.subscribe(e=>{const s=a.photos;if(a.photos=e.photos,t(),Pe('staff.manage'))for(const t of Object.keys(s))if(!e.photos[t]&&s[t]?.path&&t!==Ee.getState().staffRef&&e.clears?.[t]){const e=s[t].path;qs.set(t,null),ie.useAvatars.getState().doneClear(t),Fa('set_staff_avatar',{p_staff_ref:t,p_path:null}).then(()=>Te().storage.from(xs).remove([e])).catch(()=>{})}});return t(),s}const Fs=new Map,Hs=(0,N.create)(()=>({n:0}))},899,[900,901,902,903,806,817,904,822,818,823,905,909,910,820,912,914,915,916,917,918,839,919,920,923,926,927,831,928,971,973,974,975,978,972,979,977,984,976,985,986,987,989,992,988,816,856,993,805,995,998,895,868,1000,885,886,1002,1003,876,854,1005,1008,1010,1011,1012,880,1013,1014,1015,1016,1017,1018,891,893,869,847,842,1019,1022,1023]); __d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PAY_WINDOW_MINS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ALLERGEN_LINE",{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,"allergyPhoneLine",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"useTakeawayMenu",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"takesCardTakeaway",{enumerable:!0,get:function(){return s}}),e.takeawayAvail=function(t,n){return t.hidden||!t.signOff||null==t.price||t.price<=0?'off':n&&n.on.includes(t.id)?t.soldOut||n.soldOut.includes(t.id)?'sold-out':'on':'off'},Object.defineProperty(e,"NOT_TODAY_LABEL",{enumerable:!0,get:function(){return f}}),e.takeawayNotToday=function(t,n){return!!n&&!t.hidden&&!!t.signOff&&null!=t.price&&t.price>0&&!n.on.includes(t.id)},e.payView=function(t,n){if('takeaway'!==t.type)return{kind:'none'};const r=t.payment;if('refused'===r?.state)return{kind:'refused',reason:r.error||'The restaurant could not take this order.'};if('paid'===r?.state)return{kind:'paid',amount:r.paidPence??t.paid,late:!!r.late};if('expired'===r?.state||'cancelled'===t.status&&'waiting'===r?.state)return{kind:'expired'};if('awaiting_payment'!==t.status)return{kind:'none'};if(!r?.expiresAt)return{kind:'sending'};const o=Math.floor((Date.parse(r.expiresAt)-n)/1e3);return o>0?{kind:'pay',secondsLeft:o,expiresAt:r.expiresAt}:{kind:'expired'}},Object.defineProperty(e,"mmss",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"paidBadge",{enumerable:!0,get:function(){return c}});var t=_r(d[0]);const n=15,r='All our products are made with ingredients that contain allergens. Please speak to a member of our team before ordering if you have any questions.',o=t=>t?`If you have an allergy, phone us on ${t} before ordering.`:'If you have an allergy, phone the restaurant before ordering.',u=(0,t.create)(t=>({byVenue:{},set:(n,r)=>t(t=>({byVenue:{...t.byVenue,[n]:r}}))})),s=(t,n)=>!!t&&!t.fictional&&!n;const f='Not available for takeaway today';const l=t=>`${Math.floor(Math.max(0,t)/60)}:${String(Math.max(0,t)%60).padStart(2,'0')}`,c=t=>'paid'===t.payment?.state?`Paid by card online \xb7 \xa3${((t.payment.paidPence??t.paid)/100).toFixed(2)}${t.payment.late?' (paid late: check the slot)':''}`:null},900,[831]); __d(function(g,r,_i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"UK14",{enumerable:!0,get:function(){return t}}),e.cardAllergenMap=n,e.applyServerCard=function(t,s){const i=s.updated_at?new Date(String(s.updated_at)).toISOString():t.updatedAt,o=s.doc?.item?.allergenNotes;return{...t,allergens:n(s.allergens,s.may_contain),allergenNotes:'string'==typeof o&&o?o:void 0,dish:'string'==typeof s.dish&&s.dish?s.dish:t.dish,section:'string'==typeof s.section&&s.section?s.section:t.section,price:'number'==typeof s.price_pence?s.price_pence:t.price,signOff:t.signOff??{by:'Head chef',at:i}}},e.serverItem=function(t,s){const i=t.doc?.item;return i&&i.id?{...i,restaurantId:s,allergens:n(t.allergens,t.may_contain)}:null},Object.defineProperty(e,"noAllergenWords",{enumerable:!0,get:function(){return s}});const t=['gluten','crustaceans','molluscs','eggs','fish','peanuts','treenuts','soya','milk','celery','mustard','sesame','sulphites','lupin'];function n(n,s){const i=n=>Array.isArray(n)?n.map(String).filter(n=>t.includes(n)):[],o={};for(const t of i(s))o[t]='may';for(const t of i(n))o[t]='contains';return o}const s=t=>t?'No listed allergens':'Allergens not confirmed yet: ask staff'},901,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"isKitchenTeam",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"canEditKitchenRota",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"kitchenTeam",{enumerable:!0,get:function(){return c}}),e.kitchenPending=function(t,n,c,s){return t.filter(t=>n.has(t.staffId)&&!!t.date&&t.date>=c&&t.date<=s&&(!t.published||t.changed))},e.publishKitchen=function(t,n,c,s){let u=0;return{shifts:t.map(t=>!n.has(t.staffId)||!t.date||t.dates||t.published&&!t.changed?t:(u++,{...t,published:!0,changed:!1})),n:u}},Object.defineProperty(e,"clashes",{enumerable:!0,get:function(){return s}});const t=t=>'kitchen'===String(t.dept??'').trim().toLowerCase()&&'owner'!==t.role&&'manager'!==t.role&&!t.managerAccess&&!t.ownerAccess,n=t=>t.includes('*')||t.includes('rota.kitchen')||t.includes('rota.manage'),c=n=>n.filter(n=>!1!==n.active&&t(n));const s=(t,n,c,s,u,o)=>t.some(t=>t.staffId===n&&t.date===c&&t.id!==o&&t.start!1,c=n=>{}},912,[913]); __d(function(g,_r,i,_a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"MIN_RADIUS",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"MAX_RADIUS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"ACCURACY_CAP",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"DEFAULT_BREAK_OPTIONS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"DEFAULT_CLOCK_AREA",{enumerable:!0,get:function(){return r}}),e.distanceM=s,Object.defineProperty(e,"validLat",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"validLng",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"areaSet",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"clampRadius",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"accuracyAllowance",{enumerable:!0,get:function(){return p}}),e.isInside=h,e.cleanArea=function(t){const n=(t.breakOptions??a).map(t=>Math.round(Number(t))).filter(t=>Number.isFinite(t)&&t>0&&t<=180);return{...r,...t,lat:c(t.lat)?t.lat:null,lng:l(t.lng)?t.lng:null,radius:f(t.radius??r.radius),on:!1!==t.on,offRotaPrompt:!1!==t.offRotaPrompt,breakOptions:[...new Set(n)].sort((t,n)=>t-n).slice(0,12),offRotaTitle:(t.offRotaTitle??'').trim().slice(0,80)||r.offRotaTitle,offRotaBody:(t.offRotaBody??'').trim().slice(0,160)||r.offRotaBody}},Object.defineProperty(e,"ACTION_WORD",{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,"DENIED_TEXT",{enumerable:!0,get:function(){return m}}),e.gate=function(t,n,o,a,r="browser"){if(!t.on||!d(t)){const r={action:n,at:a,inside:null,unchecked:!0};return'object'==typeof o&&Object.assign(r,{lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc)}),{allowed:!0,geo:r,warn:t.on?'The clock-in area isn\u2019t set yet, so location isn\u2019t checked.':void 0}}if('object'!=typeof o){const t='app-phone-off'===r?m['app-phone-off']:'denied'===o?m[r]:'timeout'===o?'Your phone couldn\u2019t find your location in time. Step outside or near a window and try again.':'unsupported'===o?'This phone or browser can\u2019t share its location. Ask a manager to record it for you.':'Your phone couldn\u2019t find your location. Check Location is on, then try again.';return{allowed:!1,message:`You need to be at the venue to ${b[n]}. ${t}`,geo:{action:n,at:a,inside:!1}}}const u=h(t,o),s={action:n,at:a,lat:y(o.lat),lng:y(o.lng),acc:Math.round(o.acc),dist:u.dist,inside:u.inside};if(u.inside)return{allowed:!0,geo:s};const c=u.dist>=1e3?`${(u.dist/1e3).toFixed(1)} km`:`${u.dist} m`;return{allowed:!1,geo:s,message:`You need to be at the venue to ${b[n]}. You look to be about ${c} away (allowed ${u.limit} m). If you\u2019re at the venue, try again in a moment or ask a manager to record it for you.`}},e.overrideGeo=function(t,n,o,a){const r=a.trim();return r.length<3?null:{action:t,at:n,inside:null,override:{by:o.name,byId:o.id,reason:r.slice(0,200)}}},e.offRotaDue=function(t){return!(!(t.area.offRotaPrompt&&d(t.area)&&t.inside)||t.clockedIn||t.dismissedToday)&&!t.shifts.some(n=>t.nowHours>=n.start-1&&t.nowHours<(n.end<=n.start?n.end+24:n.end))},Object.defineProperty(e,"breakLabel",{enumerable:!0,get:function(){return O}});const t=50,n=2e3,o=50,a=[5,10,15,20,30,45,60],r={lat:null,lng:null,radius:100,on:!0,breakOptions:[...a],offRotaPrompt:!0,offRotaTitle:'Do you want to sign in?',offRotaBody:'Should you be on the rota?'},u=t=>t*Math.PI/180;function s(t,n){const o=u(n.lat-t.lat),a=u(n.lng-t.lng),r=Math.sin(o/2)**2+Math.cos(u(t.lat))*Math.cos(u(n.lat))*Math.sin(a/2)**2;return 12742017.6*Math.asin(Math.min(1,Math.sqrt(r)))}const c=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-90&&t<=90,l=t=>'number'==typeof t&&Number.isFinite(t)&&t>=-180&&t<=180,d=t=>c(t.lat)&&l(t.lng),f=o=>Number.isFinite(o)?Math.min(n,Math.max(t,Math.round(o))):r.radius,p=t=>Number.isFinite(t)&&t>0?Math.min(t,o):0;function h(t,n){const o=s({lat:t.lat,lng:t.lng},n),a=f(t.radius)+p(n.acc);return{inside:o<=a,dist:Math.round(o),limit:Math.round(a)}}const b={in:'clock in',out:'clock out',break_start:'start a break',break_end:'end your break'},m={browser:'Location is turned off for this browser. Turn it on in your phone\u2019s settings (Location \u203a allow for this browser), then try again.',iphone:'Location is turned off for this app. On your iPhone open Settings \u203a Privacy & Security \u203a Location Services \u203a Safari Websites and choose While Using the App, then try again.',app:'Location is turned off for this app. Tap Open app settings, then Permissions \u203a Location \u203a Allow only while using the app. Then come back and try again.','app-old':'This version of the app can\u2019t use location. Tap Update the app at the bottom of the screen, then tap Allow when your phone asks.','app-phone-off':'Location is switched off on your phone. Tap Open location settings, turn on Use location, then come back and try again.'};const y=t=>Math.round(1e6*t)/1e6;const O=t=>60===t?'1 hour':t%60==0?t/60+" hours":t>60?`${Math.floor(t/60)} h ${t%60} min`:`${t} min`},913,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useCashAccess",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"hasCashUpAccess",{enumerable:!0,get:function(){return n}});const t=(0,r(d[0]).create)(()=>({byRef:{},mine:null,loaded:!1,takings:null,tradingDate:null,photos:null})),n=()=>!0===t.getState().mine},914,[831]); -__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return f}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),f=n(o.removed),d=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...f.filter(t=>!d.includes(t))],u=[...d.filter(t=>!f.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),f=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const d={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); +__d(function(_g,r,i,_a,m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"PERM_CATALOG",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"PERM_KEYS",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"PERM_GROUPS",{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,"permLabel",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"ROLE_ORDER",{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,"ROLE_LABEL",{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,"ownerLevel",{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,"has",{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,"ticks",{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,"toggle",{enumerable:!0,get:function(){return d}}),e.effectivePerms=function(t,n,a){const o=[...new Set([...t,...n])];return(o.includes('*')?o:o.filter(t=>!a.includes(t))).sort()},e.tickSource=function(t,n){return t.extra.includes(n)?'extra':t.removed.includes(n)&&!t.base.includes('*')?'removed':c(t.base,n)?'role':'off'},Object.defineProperty(e,"SOURCE_WORDS",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"isCloser",{enumerable:!0,get:function(){return p}}),e.tradingDay=function(t=new Date,n="Europe/London"){const a=new Date(t.getTime()-216e5),o=new Intl.DateTimeFormat('en-GB',{timeZone:n,year:'numeric',month:'2-digit',day:'2-digit'}).formatToParts(a),s=t=>o.find(n=>n.type===t)?.value??'';return`${s('year')}-${s('month')}-${s('day')}`},Object.defineProperty(e,"ukDay",{enumerable:!0,get:function(){return b}}),e.logWords=function(t){const n=t=>Array.isArray(t)?t:[],a=t=>t&&'object'==typeof t&&!Array.isArray(t)?t:{};let s=[],u=[];if('role'===t.target_kind){const a=n(t.before),o=n(t.after);s=o.filter(t=>!a.includes(t)),u=a.filter(t=>!o.includes(t))}else{const o=a(t.before),l=a(t.after),c=n(o.extra),g=n(l.extra),d=n(o.removed),f=n(l.removed);s=[...g.filter(t=>!c.includes(t)),...d.filter(t=>!f.includes(t))],u=[...f.filter(t=>!d.includes(t)),...c.filter(t=>!g.includes(t))]}const c='role'===t.target_kind?`${l[t.target_ref??'']??t.target_name??'Role'} role`:t.target_name??'Someone',g=[...s.map(t=>`+ ${o(t)}`),...u.map(t=>`\u2212 ${o(t)}`)];return`${t.changed_by_name??'Admin'}: ${c}${g.length?`, ${g.join(', ')}`:', back to their role'}`},e.logWhen=function(t){const n=new Date(t);return new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/London',day:'2-digit',month:'2-digit',year:'numeric',hour:'2-digit',minute:'2-digit',hour12:!1}).format(n).replace(',','')};const t=[{key:'bookings.manage',label:'Take and change bookings',group:'Bookings & floor'},{key:'bookings.settings',label:'Booking settings: times, tables and blocks',group:'Bookings & floor'},{key:'floor.manage',label:'Edit the table plan and seat tables',group:'Bookings & floor'},{key:'orders.manage',label:'Kitchen and table orders',group:'Bookings & floor'},{key:'stock.manage',label:'Stock and deliveries',group:'Kitchen & stock'},{key:'suppliers.manage',label:'Suppliers',group:'Kitchen & stock'},{key:'suppliers.order',label:'Order from suppliers',group:'Kitchen & stock'},{key:'recipes.edit',label:'Edit recipe cards and allergens',group:'Kitchen & stock'},{key:'recipes.signoff',label:'Sign off recipe cards',group:'Kitchen & stock'},{key:'recipes.create_own',label:'Add recipe cards and change their own',group:'Kitchen & stock',note:'Their own cards only, shown as created by them. The Head Chef, an owner or a manager still signs off the allergens.'},{key:'attendance.view',label:'See everyone\u2019s hours',group:'Team'},{key:'rota.manage',label:'Make the rota and approve timesheets',group:'Team'},{key:'rota.kitchen',label:'Make the kitchen rota (kitchen team only)',group:'Team',note:'Add, change and publish shifts for the kitchen team in the Head Chef app. No hours, pay or takings.'},{key:'rota.swap',label:'Approve shift swaps',group:'Team'},{key:'shift.manager',label:'Shift manager features in the Staff app',group:'Team'},{key:'staff.manage',label:'Add staff and change their details',group:'Team'},{key:'takings.view',label:'See takings, past cash ups and sales reports',group:'Money',note:'Without this, \u201cCan use cash up\u201d is tonight\u2019s cash up only.'},{key:'wages.view',label:'See pay and wages',group:'Money'},{key:'wages.manage',label:'Change pay, cash-up settings and any day\u2019s cash up',group:'Money'},{key:'venue.settings',label:'Change venue settings',group:'Venue'},{key:'devices.manage',label:'Pair and remove screens',group:'Venue'},{key:'outbox.view',label:'See messages sent to guests',group:'Venue'}],n=t.map(t=>t.key),a=[...new Set(t.map(t=>t.group))],o=n=>t.find(t=>t.key===n)?.label??n,s=['owner','manager','supervisor','head_chef','staff'],l={owner:'Owner',manager:'Manager',supervisor:'Supervisor',head_chef:'Head Chef',staff:'Staff'},u=t=>t.includes('*'),c=(t,n)=>t.includes('*')||t.includes(n),g=t=>u(t)?[...n]:n.filter(n=>t.includes(n)),d=(t,n,a)=>(a?[...new Set([...t,n])]:t.filter(t=>t!==n)).sort();const f={role:'from their role',extra:'added just for them',removed:'taken off just for them',off:'off'},p=t=>t.cashUp&&!t.takings;const b=t=>/^\d{4}-\d{2}-\d{2}$/.test(t)?`${t.slice(8,10)}/${t.slice(5,7)}/${t.slice(0,4)}`:t},915,[]); __d(function(g,r,i,_a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"useSliders",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"notify",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"dismissNotice",{enumerable:!0,get:function(){return c}});var t=r(d[0]);let u=0;const s=t=>'urgent'===t.tone?0:'warn'===t.tone?1:2,n=(0,t.create)()((t,n)=>({queue:[],push:n=>t(t=>{const o=t.queue.find(t=>t.id===n.id),c=o?t.queue.map(t=>t.id===n.id?{...n,seq:o.seq}:t):[...t.queue,{...n,seq:++u}];return{queue:(f=c,[...f].sort((t,u)=>s(t)-s(u)||(t.seq??0)-(u.seq??0))).slice(0,40)};var f}),dismiss:u=>{const s=n().queue.find(t=>t.id===u);if(s){t(t=>({queue:t.queue.filter(t=>t.id!==u)}));try{s.onClose?.()}catch{}}},dismissWhere:t=>{for(const u of n().queue.filter(t))n().dismiss(u.id)}})),o=t=>n.getState().push(t),c=t=>n.getState().dismiss(t)},916,[831]); __d(function(_g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.startForm=function(t=Date.now()){return{openedAt:t,hp:''}},e.guardFor=function(t,n=Date.now()){return{hp:t.hp,formMs:Math.max(0,Math.round(n-t.openedAt))}},e.rememberGuard=function(n,o){t.set(n,o)},e.takeGuard=function(n){const o=t.get(n);return o?(t.delete(n),o):{}};const t=new Map},917,[]); __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.inviteFromLocation=function(n,t){const o=new URLSearchParams(n).get('invite');if(o)return o;const s=(t||'').match(/[#&]invite=([A-Za-z0-9_-]{10,})/);return s?s[1]:null},e.addressWithoutInvite=function(n){try{const t=new URL(n);t.searchParams.delete('invite');const o=t.hash.replace(/^#/,'').split('&').filter(n=>n&&!n.startsWith('invite=')&&!n.startsWith('ccchrome=')&&!n.startsWith('cckitchen=')).join('&');return t.hash=o?`#${o}`:'',t.toString()}catch{return n}},Object.defineProperty(e,"PHONE_LINKED_TEXT",{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,"isPhoneLinked",{enumerable:!0,get:function(){return t}}),e.inviteRefusal=function(t){return/already linked to another phone/i.test(t)?n:/update the app/i.test(t)?'Update the app: close it, then open your personal link again.':/already been used/i.test(t)?'This link has already been used on another device. Ask your manager for a new one.':/expired/i.test(t)?'This link has expired. Ask your manager for a new one.':/replaced|switched off|not valid|invalid|unknown invite/i.test(t)?'This link has been replaced or switched off. Ask your manager for a new one.':/personal app link is incomplete/i.test(t)?'Open the complete personal iPhone link your manager sent.':/no longer active/i.test(t)?'This person is no longer on the team. Ask your manager if this is wrong.':null},Object.defineProperty(e,"WIPE_PREFIXES",{enumerable:!0,get:function(){return o}}),e.keysToWipe=function(n){return n.filter(n=>o.some(t=>n.startsWith(t)))},e.handoverFromHash=function(n){const t=(n||'').match(/[#&]ccchrome=([A-Za-z0-9_-]{24,64})(?:&|$)/);return t?t[1]:null};const n='This link is already linked to another phone. Ask a manager to reset it or send you a new link.',t=n=>!!n&&/already linked to another phone/i.test(n);const o=['covercharge-','cc-sync:','cc-','sb-']},918,[]); @@ -1058,7 +1058,7 @@ __d(function(g,r,i,a,m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule' __d(function(g,r,i,a,_m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.setClockServer=function(t){s=t,c()},e.markClockUnsent=function(t){o.set(t,Date.now()),c()},e.markClockSent=function(t){o.delete(t)&&c()},e.clockNotSent=l,e.useClockNotSent=function(o){const[,c]=(0,t.useState)(0);return(0,t.useEffect)(()=>{const t=()=>c(t=>t+1);u.add(t);const o=n.mutationQueue.subscribe(t);return()=>{u.delete(t),o()}},[]),l(o)};var t=r(d[0]),n=r(d[1]);const o=new Map,u=new Set,c=()=>{for(const t of u)t()};let s=()=>!1;function l(t){if(!t)return!1;return n.mutationQueue.pending.some(n=>'attendance'===n.table&&n.rowKey===t)||o.has(t)&&s()}n.mutationQueue.onDone(t=>{'attendance'===t.table&&o.delete(t.rowKey)&&c()})},975,[17,976]); __d(function(g,_r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"MutationQueue",{enumerable:!0,get:function(){return l}}),Object.defineProperty(_e,"mutationQueue",{enumerable:!0,get:function(){return o}});var t=_r(d[0]),e=_r(d[1]),s=_r(d[2]);const n='queue:v1',r='queue:failed:v1',h=t=>`${t.table}|${t.venueId}|${t.rowKey}`;class l{items=[];failedItems=[];loaded=null;flushing=null;flushingSince=0;exec=null;listeners=new Set;onFailure=new Set;onSaved=new Set;retryTimer=null;waitTimer=null;backoffMs=2e3;now=()=>Date.now();constructor(){(0,t.onConnectivity)(t=>{t&&this.flush()})}setExecutor(t){this.exec=t}load(){return this.loaded||(this.loaded=(async()=>{const t=await e.kv.get(n,[]);this.items=[...t.map(t=>({...t,nextAt:void 0})),...this.items],this.failedItems=await e.kv.get(r,[]),this.emit()})()),this.loaded}get pending(){return this.items}get waiting(){return this.items.filter(t=>t.attempts>0)}get failed(){return this.failedItems}hasPending(t,e,s){return this.items.some(n=>n.table===t&&n.venueId===e&&n.rowKey===s)}async enqueue(t){await this.load();const s={...t,id:(0,e.uuid)(),createdAt:(new Date).toISOString(),attempts:0};return this.items.push(s),await this.persist(),this.flush(),s}nextReady(){const t=new Set,e=this.now();for(const s of this.items){const n=h(s);if(!t.has(n)){if(!(s.nextAt&&s.nextAt>e))return s;t.add(n)}}}remove(t){this.items=this.items.filter(e=>e!==t)}flush(){if(this.flushing&&Date.now()-this.flushingSince<6e4)return this.flushing;this.flushingSince=Date.now();let e=null;return e=(async()=>{for(await this.load();this.exec;){if(this.flushing&&this.flushing!==e)return;const n=this.nextReady();if(!n)break;if(!(0,t.isOnline)()){this.scheduleRetry();break}try{const t=await this.exec(n);this.remove(n),this.backoffMs=2e3,'conflict'===t?this.fail(n,'conflict','Row changed on the server (version conflict) or is not visible to you'):this.onSaved.forEach(t=>t(n))}catch(e){n.attempts+=1,n.lastError=String(e?.message??e);const r=e??{};n.lastErr={code:r.code?String(r.code):void 0,status:Number(r.status)||void 0,message:n.lastError.slice(0,300)};const h=(0,s.classifyWriteError)(e);if('network'===h){n.attempts-=1,(0,t.setOnline)(!1),this.scheduleRetry(),await this.persist();break}'retry'===h?n.nextAt=this.now()+(0,s.retryDelayMs)(n.attempts):(this.remove(n),this.fail(n,'rejected',n.lastError))}await this.persist()}this.flushing===e&&(this.flushing=null),this.scheduleWaiting()})(),this.flushing=e,e}retryNow(){for(const t of this.items)t.nextAt=void 0;return this.flush()}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}onFailed(t){return this.onFailure.add(t),()=>{this.onFailure.delete(t)}}onDone(t){return this.onSaved.add(t),()=>{this.onSaved.delete(t)}}async clearFailed(){this.failedItems=[],await e.kv.set(r,[]),this.emit()}fail(t,s,n){const h={...t,lastError:n,failedAt:(new Date).toISOString(),reason:s};this.failedItems=[h,...this.failedItems].slice(0,100),e.kv.set(r,this.failedItems),this.onFailure.forEach(t=>t(h))}scheduleWaiting(){this.waitTimer&&(clearTimeout(this.waitTimer),this.waitTimer=null);const t=this.items.map(t=>t.nextAt??0).filter(t=>t>0);if(!t.length)return;const e=Math.max(500,Math.min(...t)-this.now());this.waitTimer=setTimeout(()=>{this.waitTimer=null,this.flush()},e)}scheduleRetry(){if(this.retryTimer)return;const e=this.backoffMs;this.backoffMs=Math.min(2*this.backoffMs,6e4),this.retryTimer=setTimeout(()=>{this.retryTimer=null,(0,t.setOnline)(!0),this.flush()},e)}async persist(){await e.kv.set(n,this.items),this.emit()}emit(){this.listeners.forEach(t=>t())}}const o=new l},976,[973,972,977]); __d(function(g,r,i,a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.classifyWriteError=function(o){if((0,e.isNetworkError)(o))return'network';const{code:n,status:c,msg:l}=t(o);return s(o)?'refused':/^(08|53|57|58)/.test(n)||['40001','40P01','55P03','23505','23503'].includes(n)||/^PGRST30[0-3]$/.test(n)||/jwt|token.*expired/i.test(l)||401===c||408===c||425===c||429===c||c>=500?'retry':409!==c||n?'refused':'retry'},Object.defineProperty(_e,"retryDelayMs",{enumerable:!0,get:function(){return o}}),_e.describeWrite=function(e){const t='rpc'===e.kind?(e.fn??'change').replace(/_/g,' '):n[e.table]??e.table.replace(/_/g,' ').replace(/s$/,''),s=e.values??{},o=s.guest_name??s.name??s.display_name??s.title??s.reason,c='string'==typeof o&&o.trim()?` for ${o.trim().slice(0,60)}`:'';return'delete'===e.kind?`deleting a ${t}${c}`:`the ${t}${c}`},_e.plainReason=function(e,o){const{code:n,status:c,msg:l}=t(e);if('refused'===o)return s(e)?'more than 20 deletes in 10 minutes from one sign-in are stopped to keep your data safe':'42501'===n||403===c||/row-level security|permission/i.test(l)?'your sign-in isn\u2019t allowed to change this':'conflict'===n?'it was changed or removed on another device first':/^(22|23)/.test(n)?'the shared system says some of the details aren\u2019t valid':'P0001'===n&&l?l.slice(0,140):l?`the shared system said: ${l.slice(0,120)}`:'the shared system refused it';return'23505'===n?'the shared system already has another copy of it':'23503'===n?'a related change has to save first':/^PGRST30/.test(n)||401===c||/jwt/i.test(l)?'your sign-in is being refreshed':'the shared system is busy'};var e=r(d[0]);const t=e=>{const t=e&&'object'==typeof e?e:{};return{msg:String(t.message??e??''),code:String(t.code??''),status:Number(t.status??0)||0,hint:String(t.hint??'')}},s=e=>{const s=t(e);return/delete guard/i.test(s.hint)||/too many .* deleted in 10 minutes/i.test(s.msg)};const o=e=>Math.min(5e3*Math.pow(3,Math.max(0,e-1)),3e5),n={bookings:'booking',walk_ins:'walk-in',blocks:'blocked time',sold_out_items:'sold-out mark',sold_out_links:'dish stock link',staff:'staff details',rota_shifts:'rota shift',stock_items:'stock item',stock_events:'stock count',stock_counts:'stock count',chat_messages:'chat message',recipe_cards:'recipe card',order_lists:'order list',order_list_items:'order list item',daily_task_ticks:'task tick',daily_tasks:'daily task',attendance:'clock in or out',cash_ups:'cash-up',table_plans:'table plan',guest_profiles:'guest profile',floor_live:'table status',venues:'venue settings',time_requests:'clock correction request',staff_leave:'time off',scheduled_notifications:'reminder',suppliers:'supplier',supplier_orders:'supplier order',takeaway_orders:'takeaway order'}},977,[973]); -__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.214'},978,[]); +__d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"APP_VERSION",{enumerable:!0,get:function(){return t}});const t='v0.3.12.215'},978,[]); __d(function(g,_r,i,a,_m,e,_d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"TableRepository",{enumerable:!0,get:function(){return d}}),e.executeMutation=async function(t){const n=(t,n)=>{throw Object.assign(t,{status:n})};if('rpc'===t.kind){const{error:r,status:s}=await l().rpc(t.fn,t.values??{});return r&&n(r,s),'ok'}const r=l().from(t.table);if('upsert'===t.kind||'insert'===t.kind){const{error:s,status:o}=await r.upsert(t.values??{},{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});if(s&&'stock_events'===t.table&&'23503'===s.code&&/undoes/i.test(String(s.message??''))&&t.values?.undoes){t.values={...t.values,undoes:null};const s=await r.upsert(t.values,{onConflict:t.conflictKey??'id',ignoreDuplicates:'insert'===t.kind});return s.error&&n(s.error,s.status),'ok'}return s&&await h(t,(0,c.resolveUniqueConflict)(t,s))||s&&n(s,o),'ok'}let s='update'===t.kind?r.update(t.values??{}):r.delete();for(const[n,r]of Object.entries(t.match??{}))s=s.eq(n,r);const{data:o,error:u,status:d}=await s.select();if(u&&await h(t,(0,c.resolveUniqueConflict)(t,u)))return'ok';u&&n(u,d);if('update'===t.kind&&(!o||0===o.length)){const n=(0,c.resolveMissingUpdate)(t);return'already-saved'===n.kind||'update-unversioned'===n.kind&&await h(t,n)?'ok':'conflict'}return'ok'};var t=_r(_d[0]),n=_r(_d[1]),r=_r(_d[2]),s=_r(_d[3]),o=_r(_d[4]),u=_r(_d[5]),c=_r(_d[6]);const l=()=>(0,r.getSupabase)();class d{constructor(t,n={}){this.table=t,this.opts=n,this.keyOf=n.keyOf??(t=>String(t.id)),this.keyColumns=n.keyColumns??['id'],this.venueCol=n.venueColumn??'venue_id'}rows(t){return n.cache.rows(this.table,t)}get(t,r){return n.cache.get(this.table,t,r)}subscribe(t,r){return n.cache.subscribe(this.table,t,r)}hydrate(t){return n.cache.hydrate(this.table,t)}async refresh(r,s={}){const o=()=>{let t=l().from(this.table).select('*').eq(this.venueCol,r);return this.opts.orderBy&&(t=t.order(this.opts.orderBy.column,{ascending:this.opts.orderBy.ascending??!0})),s.filter&&(t=s.filter(t)),t},c='bookings'===this.table?await(0,t.readPages)(async(t,n)=>{const{data:r,error:s}=await o().order('id').range(t,n);if(s)throw s;return r??[]}):await(async()=>{const{data:t,error:n}=await o().limit(this.opts.limit??1e3);if(n)throw n;return t??[]})();return n.cache.replace(this.table,r,c.map(t=>[this.keyOf(t),t]),t=>u.mutationQueue.hasPending(this.table,r,t)),c}async create(t,r){const o={...1===this.keyColumns.length&&'id'===this.keyColumns[0]?{id:(0,s.uuid)()}:{},...r,[this.venueCol]:t},c=this.keyOf(o);return n.cache.put(this.table,t,c,o),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'insert'===this.opts.writeMode?'insert':'upsert',rowKey:c,values:o,conflictKey:this.opts.conflictKey??'id'}),o}async update(t,r,s,o={}){const c=n.cache.get(this.table,t,r),l={...this.matchFor(r,c),...o,[this.venueCol]:t};n.cache.patch(this.table,t,r,{...s,updated_at:(new Date).toISOString()}),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'update',rowKey:r,values:s,match:l})}async remove(t,r){const s=n.cache.get(this.table,t,r),o={...this.matchFor(r,s),[this.venueCol]:t};n.cache.remove(this.table,t,r),await u.mutationQueue.enqueue({table:this.table,venueId:t,kind:'delete',rowKey:r,match:o})}matchFor(t,n){if(1===this.keyColumns.length&&'id'===this.keyColumns[0])return{id:t};const r={};for(const t of this.keyColumns)r[t]=n?.[t];return r}}async function h(t,n){if('already-saved'===n.kind)return!0;if('unresolved'===n.kind)return!1;if('merge'===n.kind&&'name-ci'===n.lookup){const r=String(n.match.venue_id??t.venueId??'');if(!r)return!1;const{data:s,error:u}=await l().from(n.table).select('id,name,deleted_at').eq('venue_id',r).is('deleted_at',null);if(u||!s)return!1;const c=(0,o.findSavedPlanByName)(s,String(n.match.name??''));if(!c)return!1;return!(await l().from(n.table).update(n.patch).eq('id',c.id).is('deleted_at',null)).error}if('merge'===n.kind||'update-unversioned'===n.kind){let r=l().from('merge'===n.kind?n.table:t.table).update(n.patch);for(const[t,s]of Object.entries(n.match))r=r.eq(t,s);const s=await r.select();return!s.error&&!!s.data?.length}return!1}},979,[980,981,928,972,982,976,983]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.readPages=async function(t,n=1e3){const s=[];for(let c=0;;c+=n){const o=await t(c,c+n-1);if(s.push(...o),o.length`cache:${t}:${n}`;function f(t){let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}function p(n){s.delete(n),c.get(n)?.forEach(t=>t());const u=o.get(n);u&&clearTimeout(u),o.set(n,setTimeout(()=>{o.delete(n),t.kv.set(n,Array.from(f(n).entries()))},250))}const w={async hydrate(n,s){const c=l(n,s);if(u.has(c))return;u.add(c);const o=await t.kv.get(c,[]),w=f(c);let h=0;for(const[t,n]of o)w.has(t)||(w.set(t,n),h++);h&&p(c)},rows(t,n){const c=l(t,n);let o=s.get(c);return o||(o=Array.from(f(c).values()),s.set(c,o)),o},get:(t,n,s)=>f(l(t,n)).get(s),put(t,n,s,c){f(l(t,n)).set(s,c),p(l(t,n))},patch(t,n,s,c){const o=f(l(t,n)),u=o.get(s);u&&(o.set(s,{...u,...c}),p(l(t,n)))},remove(t,n,s){f(l(t,n)).delete(s)&&p(l(t,n))},replace(t,s,c,o=()=>!1){const u=l(t,s),w=f(u),h=new Map(c);w.forEach((t,n)=>{o(n)&&h.set(n,t)}),n.set(u,h),p(u)},subscribe(t,n,s){const o=l(t,n);let u=c.get(o);return u||(u=new Set,c.set(o,u)),u.add(s),()=>{u?.delete(s)}},async clearVenue(o,f){for(const p of f){const f=l(p,o);n.delete(f),s.delete(f),u.delete(f),await t.kv.remove(f),c.get(f)?.forEach(t=>t())}}}},981,[972]); @@ -1235,7 +1235,7 @@ __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esMod __d(function(g,r,_i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"ingredientQty",{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,"ingredientSpeech",{enumerable:!0,get:function(){return f}});var t=r(d[0]),n=r(d[1]);const i=(i,f,u)=>(0,n.fishInStone)(i,f)?(0,n.fishQtyText)(i,f,u):(0,t.fmtQty)(u,f.unit||''),f=(t,f,u)=>(0,n.fishInStone)(t,f)?(0,n.fishQtySpeech)(t,f,u):i(t,f,u)},1152,[1138,896]); __d(function(g,_r,_i,_a,_m,_e,_d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.SoldOutList=f,_e.SoldOutSheet=function({visible:e,onClose:t,rid:s,by:o,hideLinks:n=!0,testID:i="soldout-sheet"}){return(0,k.jsx)(l.Sheet,{visible:e,onClose:t,title:"Add sold out",maxWidth:520,testID:i,children:(0,k.jsx)(f,{rid:s,by:o,hideLinks:n})})};var e,t=_r(_d[0]),s=_r(_d[1]),o=_r(_d[2]),n=(e=o)&&e.__esModule?e:{default:e},l=_r(_d[3]),i=_r(_d[4]),d=_r(_d[5]),r=_r(_d[6]),a=_r(_d[7]),u=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),m=_r(_d[11]),k=_r(_d[12]);const y=e=>{const t=new Date(e);return`${String(t.getHours()).padStart(2,'0')}:${String(t.getMinutes()).padStart(2,'0')}`},x=e=>{const t=new Date(globalThis.__ccNow??Date.now()).toISOString();for(const s of['kitchen','foh'])r.useOwner.getState().sys(s,e,t)};function f({rid:e,by:o,canMark:r=!0,hideLinks:f=!1}){const b=(0,d.useSoldOut)(e=>e.entries),p=(0,i.useStore)(e=>e.clock),w=(0,i.useStore)(e=>e.menu),S=(0,i.useStore)(t=>t.restaurants.find(t=>t.id===e)),[I,$]=(0,s.useState)(''),C=(0,h.nowFrom)(p),D=(0,a.activeSoldOut)(b,e,C),M=new Set(D.map(e=>e.itemId)),L=(0,a.soldOutSettingsOf)(S?.settings?.soldOut),T=(0,u.useAutoSoldOutView)(e),v=b.filter(t=>t.rid===e&&!t.on&&t.kept&&T.reason(t.itemId)),O=(0,s.useMemo)(()=>w.filter(t=>t.restaurantId===e&&!t.hidden&&!M.has(t.id)&&(!I.trim()||t.name.toLowerCase().includes(I.trim().toLowerCase()))).sort((e,t)=>e.name.localeCompare(t.name)),[w,e,I,D.length]),B=t=>d.useSoldOut.getState().entries.some(s=>s.rid===e&&s.itemId===t&&s.on),A=(t,s)=>{const n=b.some(s=>s.rid===e&&s.itemId===t&&s.auto&&T.reason(t));w.some(e=>e.id===t)&&(0,d.setSoldOut)(t,!1,o),B(t)&&d.useSoldOut.getState().back(e,t,o),x(`Back on: ${s}${n?' (kept on until the count changes)':''}`)};return(0,k.jsxs)(n.default,{testID:"soldout-list",style:{gap:10},children:[(0,k.jsx)(l.Muted,{children:"A reminder for staff. Dishes you mark sold out show on the Display and in the Sold out list in every staff app, within seconds. It doesn't change your till."}),(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Sold out now"}),(0,k.jsx)(l.T,{size:13,colour:D.length?m.colours.amber:m.colours.muted,children:D.length?(0,a.soldOutCount)(D.length):'Nothing sold out'})]}),D.length?D.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-row-${e.itemId}`,style:{flexDirection:'row',flexWrap:'wrap',gap:8,justifyContent:'space-between',alignItems:'center',paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border},children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160,gap:2},children:[(0,k.jsx)(l.T,{weight:"semibold",children:(0,c.withReason)(e.name,T.reason(e.itemId))}),(0,k.jsxs)(l.Muted,{children:["Since ",y(e.at),e.auto?' \xb7 Auto, from the counts \xb7 clears when the count is back up':`${e.by?` \xb7 ${e.by}`:''}${e.clearAfter?` \xb7 clears at ${y(e.clearAfter)}`:''}`]})]}),r?(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back on",testID:`soldout-back-${e.itemId}`,accessibilityLabel:`Cancel sold out: ${e.name}, put ${e.name} back on`,onPress:()=>A(e.itemId,e.name)}):null]},e.itemId)):(0,k.jsx)(l.Muted,{children:"When a dish runs out, mark it here so everyone knows."}),v.length?(0,k.jsx)(n.default,{testID:"soldout-kept",children:(0,k.jsxs)(l.Muted,{children:["Kept on by hand while the count is short: ",v.map(e=>e.name).join(', '),". They stay on until the count changes."]})}):null,(0,k.jsxs)(l.Muted,{children:["Clears by itself: ",a.SOLD_OUT_CLEAR_LABEL[L.clear].toLowerCase(),". ",L.auto?'Dishes marked from the counts clear when the count is back up. ':'',"Managers can change this in Settings \u203a Advanced."]})]}),!f&&T.items.length?(0,k.jsx)(j,{rid:e,by:o,canEdit:r,auto:L.auto,view:T}):null,r?(0,k.jsxs)(l.Card,{children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Mark a dish sold out"}),(0,k.jsx)(t.TextInput,{testID:"soldout-search",value:I,onChangeText:$,placeholder:"Find a dish",placeholderTextColor:m.colours.muted,accessibilityLabel:"Find a dish",style:{minHeight:46,borderRadius:12,borderWidth:1,borderColor:m.colours.accentBorder,backgroundColor:m.colours.surface2,color:m.colours.text,paddingHorizontal:12,fontSize:16}}),O.slice(0,60).map(t=>(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center',paddingVertical:4},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{children:t.name}),(0,k.jsx)(l.Muted,{children:t.section})]}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Mark sold out",testID:`soldout-mark-${t.id}`,accessibilityLabel:`Mark sold out: ${t.name}`,onPress:()=>{return s=t.id,n=t.name,(0,d.setSoldOut)(s,!0,o),B(s)||d.useSoldOut.getState().mark(e,s,n,o),void x(`Sold out: ${n}`);var s,n}})]},t.id)),O.length?null:(0,k.jsx)(l.Muted,{children:I?'No dish matches that.':'Every dish is marked sold out.'})]}):null]})}const b={link:'set by staff',card:'from its recipe card',description:'from its description',name:'from its name',none:''},p=e=>.5===e?'\xbd':Number.isInteger(e)?String(e):`${Math.floor(e)}\xbd`;function j({rid:e,by:t,canEdit:o,auto:i,view:d}){const[r,a]=(0,s.useState)(!1),[h,y]=(0,s.useState)(null),[x,f]=(0,s.useState)([]),j=d.dishes.filter(t=>t.uses.length||'none'===t.source&&d.links.some(s=>s.rid===e&&s.itemId===t.id&&!s.auto)),w=(r?d.dishes:j).slice().sort((e,t)=>e.name.localeCompare(t.name)),S=d.items.map(e=>`${e.name.toLowerCase()} ${p(d.counts[e.key]??0)}`).join(', '),I=(e,t,s)=>f(o=>o.map(o=>o.key===e?{...o,qty:Math.max(0,Math.min(20,o.qty+s*('half'===t.unit?.5:1)))}:o)),$=(s,o)=>{u.useSoldOutLinks.getState().setLink(e,s,o,t),y(null)};return(0,k.jsx)(n.default,{testID:"soldout-links",children:(0,k.jsxs)(l.Card,{children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsx)(l.T,{weight:"semibold",size:17,children:"Dishes linked to the counts"}),(0,k.jsx)(n.default,{testID:"soldout-links-counts",children:(0,k.jsxs)(l.T,{size:13,colour:m.colours.muted,children:["Counts now: ",S]})})]}),(0,k.jsx)(l.Muted,{children:i?'When a count runs out, or drops below what a dish needs, the dish is marked sold out by itself, and put back on when the count is back up. Dishes you mark by hand are left alone.':'Marking dishes from the counts is off for this venue (Settings \u203a Advanced \u203a Sold out reminders).'}),w.map(e=>(0,k.jsxs)(n.default,{testID:`soldout-link-${e.id}`,style:{paddingVertical:6,borderTopWidth:1,borderTopColor:m.colours.border,gap:6},children:[(0,k.jsxs)(l.Row,{style:{justifyContent:'space-between',alignItems:'center'},wrap:!0,children:[(0,k.jsxs)(n.default,{style:{flexShrink:1,flexGrow:1,flexBasis:160},children:[(0,k.jsx)(l.T,{weight:"semibold",children:e.name}),(0,k.jsxs)(l.Muted,{children:[e.uses.length?`Uses ${(0,c.usesText)(e.uses,d.items)}`:'Not linked to the counts',b[e.source]?` \xb7 ${b[e.source]}`:'']})]}),o&&h!==e.id?(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Change",testID:`soldout-link-edit-${e.id}`,accessibilityLabel:`Change what ${e.name} uses`,onPress:()=>{return t=e.id,s=e.uses,y(t),void f(d.items.map(e=>({key:e.key,qty:s.find(t=>t.key===e.key)?.qty??0})));var t,s}}):null]}),h===e.id?(0,k.jsxs)(n.default,{style:{gap:6},children:[d.items.map(t=>{const s=x.find(e=>e.key===t.key)?.qty??0;return(0,k.jsxs)(l.Row,{style:{alignItems:'center',gap:8},children:[(0,k.jsx)(l.T,{style:{flexGrow:1},children:t.name}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"\u2013",testID:`soldout-link-${e.id}-${t.key}-minus`,accessibilityLabel:`Fewer ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,-1)}),(0,k.jsx)(n.default,{testID:`soldout-link-${e.id}-${t.key}-qty`,style:{minWidth:28},children:(0,k.jsx)(l.T,{weight:"semibold",style:{textAlign:'center'},children:p(s)})}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"+",testID:`soldout-link-${e.id}-${t.key}-plus`,accessibilityLabel:`More ${t.plural.toLowerCase()}`,onPress:()=>I(t.key,t,1)})]},t.key)}),(0,k.jsxs)(l.Muted,{children:["Per portion. ",x.some(e=>e.qty>0)?`Uses ${(0,c.usesText)(x.filter(e=>e.qty>0),d.items)}.`:'Not linked: never marked from the counts.']}),(0,k.jsxs)(l.Row,{style:{gap:8},wrap:!0,children:[(0,k.jsx)(l.Button,{small:!0,label:"Save",testID:`soldout-link-save-${e.id}`,onPress:()=>$(e.id,x.filter(e=>e.qty>0))}),(0,k.jsx)(l.Button,{small:!0,kind:"secondary",label:"Back to automatic",testID:`soldout-link-reset-${e.id}`,accessibilityLabel:`Back to automatic: ${e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'}`,onPress:()=>$(e.id,null)}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:"Cancel",onPress:()=>y(null)})]}),(0,k.jsxs)(l.Muted,{children:["Automatic: ",e.guess.length?(0,c.usesText)(e.guess,d.items):'not linked'," (from the recipe card, description or name)."]})]}):null]},e.id)),w.length?null:(0,k.jsx)(l.Muted,{children:"No dish is linked yet."}),(0,k.jsx)(l.Button,{small:!0,kind:"ghost",label:r?'Show linked dishes only':'Link another dish',testID:"soldout-links-all",onPress:()=>a(!r)})]})})}},1153,[812,17,85,777,858,891,876,892,893,894,816,804,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TABLE_ORDER_DEFAULT",{enumerable:!0,get:function(){return e}}),Object.defineProperty(_e,"cleanToken",{enumerable:!0,get:function(){return t}}),Object.defineProperty(_e,"isTableNo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(_e,"fromRow",{enumerable:!0,get:function(){return n}}),Object.defineProperty(_e,"toRow",{enumerable:!0,get:function(){return o}}),Object.defineProperty(_e,"hm",{enumerable:!0,get:function(){return l}}),_e.openAt=function(e,t){const r=a(t),n=e.openFrom?a(e.openFrom):null,o=e.lastOrders?a(e.lastOrders):null;return null!==n&&null!==o?n<=o?r>=n&&r=n||r=n:null===o||r{const t=(e??'').trim().toUpperCase();return/^[A-Z2-9]{16}$/.test(t)?t:null},r=e=>/^[0-9]{1,4}$/.test(e),n=t=>t?{on:!!t.is_on,tables:Array.isArray(t.tables)?t.tables.map(String):null,staffAccept:!1!==t.staff_accept,openFrom:t.open_from?String(t.open_from).slice(0,5):null,lastOrders:t.last_orders?String(t.last_orders).slice(0,5):null,guestTip:t.guest_tip??''}:{...e},o=e=>({is_on:e.on,tables:e.tables&&e.tables.length?e.tables.filter(r):null,staff_accept:e.staffAccept,open_from:e.openFrom,last_orders:e.lastOrders,guest_tip:e.guestTip.slice(0,300)}),a=e=>{const[t,r]=e.split(':').map(Number);return 60*t+r},l=e=>`${String(Math.floor(e/60)%24).padStart(2,'0')}:${String(e%60).padStart(2,'0')}`;const s=(e,t)=>e.reduce((e,r)=>e+r.qty*(t.find(e=>e.id===r.id)?.pricePence??0),0),u=(e,t,r)=>e.map(e=>t.find(t=>t.id===e.id)).filter(e=>!!e&&(e.allergens.some(e=>r.includes(e))||e.mayContain.some(e=>r.includes(e)))),c=(e,t)=>`${e.replace(/\/$/,'')}/t?k=${t}`,f=(e,t)=>`${e.replace(/\/$/,'')}/customer-app/index.html?table=${t}`,p=e=>{const t=e.trim();return t.length>=2&&t.length<=40&&/\p{L}/u.test(t)},b=e=>{const t=e.trim();return!t||/^\+?[0-9][0-9 ()-]{6,19}$/.test(t)},m=e=>'table'===e.type&&'table-qr'===e.channel,y=e=>m(e)&&!!e.held&&!e.accepted&&'cancelled'!==e.status,h=e=>!y(e),O=e=>'cancelled'===e.status?e.cancelReason?`Cancelled: ${e.cancelReason}`:'Cancelled by the staff.':e.held&&!e.accepted?'Sent. Waiting for a member of staff to accept it.':'served'===e.status||'collected'===e.status||'closed'===e.status?'Served. Enjoy!':'ready'===e.status?'Ready: on its way to your table.':'Accepted: the kitchen has your order.',P=['Sold out','Wrong table','Sent twice','Kitchen closed','Guest asked to cancel'],j='Pay at the bar or with your server. Paying by card from your phone is coming later.'},1154,[]); -__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return I}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:l}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,I]=(0,n.useState)('free-from'),[w,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===l&&(0,m.canEditCards)(s.role),v=P?u:u.filter(e=>!!e.signOff),L=(0,n.useMemo)(()=>{const e='all'===w?v:v.filter(e=>(0,m.cardState)(e)===w);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[v,p,b,j,w]),R=u.filter(e=>!e.signOff).length,M=D?u.find(e=>e.id===D):void 0,A=k&&'new'!==k?u.find(e=>e.id===k)??null:null,N=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===l?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>I('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>I('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(i.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>N(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${u.length})`,selected:'all'===w,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${R})`,selected:'awaiting'===w,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${u.length-R})`,selected:'signed-off'===w,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[L.length," ",1===L.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),L.map(e=>(0,C.jsx)(z,{c:e,actor:s,mode:l,editable:P,onPress:()=>T(e.id)},e.id)),L.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:u.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!M&&!k,onClose:()=>T(null),title:M?.dish??'',maxWidth:640,testID:"card-sheet",children:M?(0,C.jsx)(B,{card:M,mode:l,actor:'read'===l?{...s,role:'staff'}:s,onEdit:P?()=>S(M.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${A?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:A,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:l}){const i=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const I=x?c.find(e=>e.id===x):void 0,w=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:i.length?`${i.length} ${1===i.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),i.map(({item:e,card:s,at:n})=>{const i=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${i}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:i})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),l?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:l,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!I&&!y,onClose:()=>b(null),title:I?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:I?(0,C.jsx)(B,{card:I,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(I.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${w?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&w?(0,C.jsx)(O,{rid:e,card:w,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),l=e(_r(_d[3])),i=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const I=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},w=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':w(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",I(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:i,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=i&&a?`Photo ${i} of ${a}`:'Plating photo';return h?(0,C.jsx)(l.default,{testID:i?`card-photo-${i}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:l="edit"}){const[i,a]=(0,n.useState)(null),c=(0,m.signOffBlock)(e),h=D[e.origin],f=(0,m.cardPhotos)(e),p=(0,m.maySignOff)(t,e),x=(0,b.useCardCosting)(e,t.role,l);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[f.length?(0,C.jsx)(k,{dish:e.dish,photo:f[0],height:220,index:1,total:f.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),f.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:f.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:f.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[h?(0,C.jsx)(d.Badge,{label:h,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),x&&x.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:x.summary.batch/Math.max(1,x.summary.perPortion||1)>1.5?`Makes ${Math.round(x.summary.batch/x.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",I(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=x?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${w(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:w(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",(0,m.canEditCards)(t.role)?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:l}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",I(e.updatedAt)," by ",e.updatedBy]}),(0,m.canEditCards)(t.role)&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,p&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[c?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:c}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!c,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),a(null)}catch(e){a(e?.message??'Could not sign off.')}}})]}):null,!(0,m.canEditCards)(t.role)||p||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),i?(0,C.jsx)(d.Banner,{kind:"danger",children:i}):null]})}const L=()=>`i-${Math.random().toString(36).slice(2,9)}`,R=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:L(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:l,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>R(l,b[0]??'Mains',c.name)),[I,w]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=e=>j(t=>({...t,...e})),v=y.ingredients.filter(e=>e.name.trim()),B={ingredients:v,allergens:y.allergens,dismissed:y.dismissed},O=(0,m.suggestAllergens)(v),E=(0,m.unresolved)(B),A=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',P({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],P({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},N=(e,t)=>P({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>P({steps:y.steps.map((s,n)=>n===e?t:s)}),H=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],P({steps:s}))},_=y.photos.length+y.pending.length,F=async e=>{if(D(null),_>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(P({pending:[...y.pending,t]}),D(`Photo ${_+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[G,V]=(0,n.useState)(!1),U=y.dish||l?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[l?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>P({dish:e}),placeholder:"e.g. Cullen skink"}),(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>P({createdBy:e}),placeholder:"Chef's name"}),l?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>P({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>P({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>P({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,photo:e,height:160,index:t+1,total:_||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${U}`,onPress:()=>P({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:U,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:_}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>P({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),_?null:(0,C.jsx)(k,{dish:U,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:_>=m.MAX_RECIPE_PHOTOS,onPress:()=>F('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const l=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>N(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>N(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>N(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>P({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),l.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",l.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>P({ingredients:[...y.ingredients,{id:L(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>H(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(i.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>H(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>P({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>P({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),E.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${E.length} suggested allergen${1===E.length?'':'s'}`,children:E.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(v,e).join(', ')})`).join('; ')}),E.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>P({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>P({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};E.forEach(t=>{e[t]='contains'}),P({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=O.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,l='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(i.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>A(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:l,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>P({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),(0,C.jsxs)(i.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:E.length>0},disabled:E.length>0,onPress:()=>P({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:E.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:E.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),I?(0,C.jsx)(d.Banner,{kind:"danger",children:I}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:G?'Saving\u2026':l?'Save changes':'Save card',disabled:G,onPress:async()=>{w(null);const t=M(y.price);if(!y.dish.trim())return w('Give the dish a name.');if('bad'===t)return w('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();V(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const i=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:v.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:i,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(l)await s.update(l.id,{...o,confirmAllergens:y.confirm},c),h(l.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){w(e?.message??'Could not save the card.')}finally{V(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),l?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(l)try{await(0,u.recipeCards)().remove(l.id,c),h(null)}catch(e){w(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function z({c:e,actor:t,mode:s,editable:n,onPress:l}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(i.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:l,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${I(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); +__d(function(g,_r,_i,_a,_m,_e,_d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"fmtDate",{enumerable:!0,get:function(){return w}}),_e.SignOffLine=T,_e.CardView=B,_e.CardEditor=O,_e.RecipeCards=function({rid:e,actor:s,mode:i}){const h=(0,a.useRecipeCards)(e),u=(0,n.useMemo)(()=>h.filter(e=>!c.OFF_CARD_LIST.has(e.menuItemId)),[h]),[p,x]=(0,n.useState)(''),[b,y]=(0,n.useState)([]),[j,w]=(0,n.useState)('free-from'),[I,$]=(0,n.useState)('all'),[D,T]=(0,n.useState)(null),[k,S]=(0,n.useState)(null),P='edit'===i&&(0,m.canEditCards)(s.role),v='own'===i&&!!s.ownRef,R=e=>v&&(0,m.ownsCard)(s,e),L=P?u:u.filter(e=>!!e.signOff||R(e)),M='edit'===i?'edit':'read',A=(0,n.useMemo)(()=>{const e='all'===I?L:L.filter(e=>(0,m.cardState)(e)===I);return(0,m.filterCards)(e,p,b,j).slice().sort((e,t)=>e.section.localeCompare(t.section)||E(e.dish).localeCompare(E(t.dish)))},[L,p,b,j,I]),z=L.filter(e=>!e.signOff).length,H=D?u.find(e=>e.id===D):void 0,W=k&&'new'!==k?u.find(e=>e.id===k)??null:null,_=e=>y(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);return(0,C.jsxs)(r.default,{testID:"recipe-cards",style:{gap:12},children:['read'===i?(0,C.jsx)(d.Banner,{kind:"info",title:"Read-only",children:"Signed-off recipe cards only. The head chef keeps these up to date."}):v?(0,C.jsx)(d.Banner,{kind:"info",title:"Your recipe cards",children:"Signed-off cards, plus the cards you create. Only you can change your own cards. The Head Chef, an owner or a manager signs off the allergens before a card goes live."}):(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(s,{createdBy:s.name,createdByRole:s.role})?'You can add, edit and sign off cards. A card goes live once it is signed off. Editing a card clears the sign-off.':'You can add and edit cards. The Head Chef, an owner or a manager signs it off before it goes live. Editing a card clears the sign-off.'}),u.some(e=>'example'===e.origin)?(0,C.jsx)(d.Banner,{kind:"example",title:"Example data",children:"Cards marked \u201cExample data\u201d are made-up examples to show how recipe cards work. Replace them with your own dishes."}):null,P||v?(0,C.jsx)(d.Button,{testID:"new-card",label:"New recipe card",onPress:()=>S('new')}):null,(0,C.jsx)(t.TextInput,{testID:"card-search",accessibilityLabel:"Search recipe cards",value:p,onChangeText:x,placeholder:"Search dishes or ingredients",placeholderTextColor:"#7D776C",style:d.styles.input}),(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,children:"Allergens:"}),(0,C.jsx)(d.Chip,{label:"Free from",selected:'free-from'===j,onPress:()=>w('free-from')}),(0,C.jsx)(d.Chip,{label:"Contains",selected:'contains'===j,onPress:()=>w('contains')}),b.length?(0,C.jsx)(d.Chip,{label:"Clear",onPress:()=>y([])}):null]}),(0,C.jsx)(d.Row,{gap:6,wrap:!0,children:f.ALLERGENS.map(e=>(0,C.jsx)(l.default,{testID:`filter-${e.id}`,accessibilityRole:"button",accessibilityState:{selected:b.includes(e.id)},onPress:()=>_(e.id),style:{paddingVertical:5,paddingHorizontal:10,minHeight:44,minWidth:44,justifyContent:'center',borderRadius:14,borderWidth:1,borderColor:b.includes(e.id)?o.colours.gold:o.colours.border,backgroundColor:b.includes(e.id)?o.colours.gold:'transparent'},children:(0,C.jsx)(d.T,{size:13,colour:b.includes(e.id)?o.colours.onGold:o.colours.text,children:e.short})},e.id))}),P||v?(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.Chip,{label:`All (${L.length})`,selected:'all'===I,onPress:()=>$('all')}),(0,C.jsx)(d.Chip,{label:`Awaiting sign-off (${z})`,selected:'awaiting'===I,onPress:()=>$('awaiting')}),(0,C.jsx)(d.Chip,{label:`Signed off (${L.length-z})`,selected:'signed-off'===I,onPress:()=>$('signed-off')})]}):null,(0,C.jsx)(r.default,{testID:"card-count",children:(0,C.jsxs)(d.Muted,{center:!0,children:[A.length," ",1===A.length?'card':'cards',b.length?` ${'free-from'===j?'free from':'containing'} ${b.map(f.allergenLabel).join('free-from'===j?' and ':' or ')}`:'']})}),A.map(e=>(0,C.jsx)(N,{c:e,actor:s,mode:M,editable:P||R(e),onPress:()=>T(e.id)},e.id)),A.length?null:(0,C.jsx)(r.default,{testID:"cards-empty",style:{alignItems:'center',paddingVertical:16},children:(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:L.length?'No cards match.':'No recipe cards yet.'})}),(0,C.jsx)(d.Sheet,{visible:!!H&&!k,onClose:()=>T(null),title:H?.dish??'',maxWidth:640,testID:"card-sheet",children:H?(0,C.jsx)(B,{card:H,mode:M,actor:'edit'===i?s:{...s,role:'staff'},onEdit:P||R(H)?()=>S(H.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!k,onClose:()=>S(null),title:'new'===k?'New recipe card':`Edit: ${W?.dish??''}`,maxWidth:680,testID:"editor-sheet",children:k?(0,C.jsx)(O,{rid:e,card:W,actor:s,onDone:e=>{S(null),T(e)}},k):null})]})},Object.defineProperty(_e,"addedLabel",{enumerable:!0,get:function(){return m.addedLabel}}),Object.defineProperty(_e,"allergenSentence",{enumerable:!0,get:function(){return m.allergenSentence}}),Object.defineProperty(_e,"unsignedOldestFirst",{enumerable:!0,get:function(){return m.unsignedOldestFirst}}),_e.useUnsignedDishes=A,_e.UnsignedDishList=function({rid:e,actor:t,onClose:s,onOpenCards:i}){const l=A(e),c=(0,a.useRecipeCards)(e),[f,p]=(0,n.useState)(null),[x,b]=(0,n.useState)(null),[y,j]=(0,n.useState)(null);(0,h.useBackLayer)(!0,s);const w=x?c.find(e=>e.id===x):void 0,I=y?c.find(e=>e.id===y)??null:null,$=async e=>{try{await(0,u.recipeCards)().signOff(e.id,t),p(null)}catch(t){p({id:e.id,text:t?.message??'Could not sign off.'})}};return(0,C.jsxs)(r.default,{testID:"unsigned-list",style:{gap:12,alignItems:'stretch'},children:[(0,C.jsx)(h.BackButton,{onPress:s,testID:"unsigned-back"}),(0,C.jsx)(d.T,{center:!0,size:22,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",style:{alignSelf:'stretch'},children:"Dishes not signed off"}),(0,C.jsx)(d.Muted,{center:!0,testID:"unsigned-status",children:l.length?`${l.length} ${1===l.length?'dish':'dishes'} waiting, oldest first.`:'Every dish is signed off.'}),l.map(({item:e,card:s,at:n})=>{const l=(0,m.allergenSentence)(s?s.allergens:e.allergens),a=!!s&&(0,m.maySignOff)(t,s),c=s?(0,m.signOffBlock)(s):null;return(0,C.jsxs)(d.Card,{highlight:o.colours.amber,style:{alignItems:'center',gap:8},children:[(0,C.jsxs)(r.default,{testID:`unsigned-row-${e.id}`,accessible:!0,accessibilityLabel:`${e.name}, ${(0,m.addedLabel)(n)}, ${l}`,style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,children:e.name}),(0,C.jsx)(d.T,{center:!0,children:(0,m.addedLabel)(n)}),(0,C.jsx)(d.Muted,{center:!0,children:l})]}),s&&a&&!c?(0,C.jsx)(d.Button,{testID:`unsigned-sign-${e.id}`,kind:"success",label:"Sign off",accessibilityLabel:`Sign off ${e.name} as ${t.name}`,onPress:()=>$(s),style:{alignSelf:'stretch'}}):null,s&&a&&c?(0,C.jsx)(d.Muted,{center:!0,children:c}):null,s&&!a?(0,C.jsx)(d.Muted,{center:!0,children:"Only the Head Chef, an owner or a manager can sign it off."}):null,s?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",testID:`unsigned-open-${e.id}`,label:a&&c?'Check the recipe card':'Open recipe card',accessibilityLabel:`Open the recipe card for ${e.name}`,onPress:()=>b(s.id),style:{alignSelf:'stretch'}}):(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(d.Muted,{center:!0,children:"No recipe card yet."}),i?(0,C.jsx)(d.Button,{small:!0,kind:"secondary",label:"Open recipe cards",onPress:i,style:{alignSelf:'stretch'}}):null]}),f&&s&&f.id===s.id?(0,C.jsx)(d.Banner,{kind:"danger",children:f.text}):null]},e.id)}),(0,C.jsx)(d.Sheet,{visible:!!w&&!y,onClose:()=>b(null),title:w?.dish??'',maxWidth:640,testID:"unsigned-card-sheet",children:w?(0,C.jsx)(B,{card:w,actor:t,onEdit:(0,m.canEditCards)(t.role)?()=>j(w.id):void 0}):null}),(0,C.jsx)(d.Sheet,{visible:!!y,onClose:()=>j(null),title:`Edit: ${I?.dish??''}`,maxWidth:680,testID:"unsigned-editor-sheet",children:y&&I?(0,C.jsx)(O,{rid:e,card:I,actor:t,onDone:e=>{j(null),b(e)}},y):null})]})};var t=_r(_d[0]),s=_r(_d[1]),n=_r(_d[2]),i=e(_r(_d[3])),l=e(_r(_d[4])),r=e(_r(_d[5])),o=_r(_d[6]),d=_r(_d[7]),a=_r(_d[8]),c=_r(_d[9]),h=_r(_d[10]),u=_r(_d[11]),f=_r(_d[12]),m=_r(_d[13]),p=_r(_d[14]),x=_r(_d[15]),b=_r(_d[16]),y=_r(_d[17]),j=_r(_d[18]),C=_r(_d[19]);const w=e=>{const t=new Date(e.length<=10?`${e}T12:00:00`:e);return isNaN(+t)?e:t.toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'})},I=e=>`\xa3${(Math.round(e)/100).toFixed(2)}`,$=e=>null==e?'Price on the board':I(e),D={example:p.EXAMPLE_TAG,imported:'Imported from the menu',new:null};function T({card:e,testID:t}){return e.signOff?(0,C.jsx)(r.default,{testID:t??'card-signed-off',accessibilityLabel:`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`,style:{alignItems:'center',gap:4,width:'100%'},children:(0,C.jsxs)(d.T,{center:!0,weight:"bold",colour:o.colours.gold,children:["Signed off by ",e.signOff.by,", ",w(e.signOff.at)]})}):(0,C.jsxs)(r.default,{testID:t??'card-signed-off',accessibilityLabel:"Not signed off yet",style:{alignItems:'center',gap:4,width:'100%'},children:[(0,C.jsx)(d.T,{center:!0,weight:"semibold",colour:o.colours.gold,children:m.STATE_LABEL.awaiting}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:c.portionCardItemIds.includes(e.menuItemId)?'A portion card for the kitchen. The dish on the menu is not changed by this card.':e.wasLive?'Edited since the last sign-off. Guests see it as awaiting sign-off until a chef signs it again.':'This dish stays off the menu until a chef signs it off.'})]})}function k({dish:e,photo:t,height:s=180,pending:n,index:l,total:a,radius:c=12}){const h=n?{uri:n}:t?(0,u.recipeCards)().photoSource(t):null,f=l&&a?`Photo ${l} of ${a}`:'Plating photo';return h?(0,C.jsx)(i.default,{testID:l?`card-photo-${l}`:'card-photo',accessibilityLabel:`${f}${e?`: ${e}`:''}`,source:h,style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.surface2},resizeMode:"cover"}):(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:"No plating photo yet"+(e?`, ${e}`:''),style:{width:'100%',height:s,borderRadius:c,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',borderWidth:1.5,borderColor:o.colours.gold,gap:2},children:[(0,C.jsx)(d.T,{center:!0,size:Math.min(64,Math.max(30,Math.round(.38*s))),weight:"bold",colour:o.colours.gold,children:(e.trim()[0]??'?').toUpperCase()}),s>=120?(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:o.colours.goldLight,children:"No plating photo yet"}):null]})}function S({map:e}){const t=f.ALLERGENS.filter(t=>e[t.id]).map(e=>e.id);return t.length?(0,C.jsx)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:t.map(t=>{const s='may'===e[t],n=s?`May contain ${(0,f.allergenLabel)(t).toLowerCase()}`:(0,f.allergenLabel)(t);return(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:s?n:`Contains ${(0,f.allergenLabel)(t).toLowerCase()}`,style:{paddingHorizontal:12,paddingVertical:6,borderRadius:999,borderWidth:1.5,borderColor:s?o.colours.amber:o.colours.gold,backgroundColor:s?'transparent':o.colours.gold,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"semibold",center:!0,colour:s?o.colours.amber:o.colours.onGold,children:n})},t)})}):(0,C.jsx)(d.Muted,{center:!0,children:"None of the UK 14 allergens."})}const P=({label:e,gold:t,testID:s})=>(0,C.jsx)(r.default,{testID:s,style:{paddingHorizontal:12,paddingVertical:5,borderRadius:999,borderWidth:1,borderColor:t?o.colours.gold:o.colours.accentBorder,backgroundColor:t?o.colours.goldTint:o.colours.surface,maxWidth:'100%'},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",center:!0,colour:t?o.colours.goldLight:o.colours.text,children:e})}),v=({title:e})=>(0,C.jsxs)(r.default,{style:{width:'100%',alignItems:'center',gap:4,paddingTop:4},children:[(0,C.jsx)(d.T,{size:13,weight:"semibold",center:!0,colour:o.colours.goldMuted,accessibilityRole:"header",children:e.toUpperCase()}),(0,C.jsx)(r.default,{style:{width:36,height:2,borderRadius:1,backgroundColor:o.colours.gold}})]});function B({card:e,actor:t,onEdit:s,mode:i="edit"}){const l=(0,m.canEditCards)(t.role)||!!t.ownRef,[a,c]=(0,n.useState)(null),h=(0,m.signOffBlock)(e),f=D[e.origin],p=(0,m.cardPhotos)(e),x=(0,m.maySignOff)(t,e),y=(0,b.useCardCosting)(e,t.role,i);return(0,C.jsxs)(r.default,{testID:"card-view",style:{gap:12,alignItems:'center',width:'100%'},children:[p.length?(0,C.jsx)(k,{dish:e.dish,photo:p[0],height:220,index:1,total:p.length,radius:18}):(0,C.jsx)(k,{dish:e.dish,height:180,radius:18}),p.length>1?(0,C.jsx)(d.Row,{gap:8,style:{width:'100%'},children:p.slice(1).map((t,s)=>(0,C.jsx)(r.default,{style:{flex:1,minWidth:0},children:(0,C.jsx)(k,{dish:e.dish,photo:t,height:72,index:s+2,total:p.length})},t))}):null,(0,C.jsx)(d.T,{center:!0,size:26,weight:"bold",colour:o.colours.gold,accessibilityRole:"header",children:e.dish}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[f?(0,C.jsx)(d.Badge,{label:f,kind:'example'===e.origin?'blue':'neutral'}):null,(0,C.jsx)(P,{label:e.section,gold:!0}),(0,C.jsx)(P,{label:$(e.price)}),y&&y.summary.lines.length?(0,C.jsx)(P,{testID:"card-yield",label:y.summary.batch/Math.max(1,y.summary.perPortion||1)>1.5?`Makes ${Math.round(y.summary.batch/y.summary.perPortion)} portions`:'1 portion'}):null]}),(0,C.jsx)(r.default,{accessible:!0,accessibilityLabel:`Created by ${e.createdBy||'not recorded'}`,style:{width:'100%',alignItems:'center'},children:(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,testID:"card-created-by",children:["Created by ",e.createdBy||'Not recorded']})}),(0,C.jsx)(r.default,{style:{width:'100%',paddingVertical:8,paddingHorizontal:10,borderRadius:14,borderWidth:1,borderColor:e.signOff?o.colours.accentBorder:o.colours.amber,backgroundColor:e.signOff?o.colours.accentBg:o.colours.amberBg},children:(0,C.jsx)(T,{card:e,testID:"card-status"})}),'example'!==e.origin?(0,C.jsx)(j.TakeawaySwitch,{itemId:e.menuItemId,dish:e.dish,role:t.role,me:t.name,signedOff:!!e.signOff,priced:null!=e.price&&e.price>0}):null,(0,C.jsx)(v,{title:"Allergens"}),(0,C.jsx)(r.default,{testID:"card-allergens",style:{width:'100%'},children:(0,C.jsx)(S,{map:e.allergens})}),e.allergenNotes?(0,C.jsx)(d.Muted,{center:!0,children:e.allergenNotes}):null,e.allergensConfirmed?(0,C.jsxs)(d.Muted,{center:!0,children:["Allergen list confirmed by ",e.allergensConfirmed.by," on ",w(e.allergensConfirmed.at),"."]}):null,(0,C.jsx)(v,{title:"Ingredients"}),e.ingredients.length?(0,C.jsx)(r.default,{testID:"card-ingredients",style:{width:'100%',borderRadius:14,borderWidth:1,borderColor:o.colours.border,backgroundColor:o.colours.surface,overflow:'hidden'},children:e.ingredients.map((e,t)=>{const s=[e.qty,e.unit].filter(Boolean).join(' '),n=y?.byRecipeIng[e.id];return(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`${e.name}${s?`, ${s}`:''}${n?`, ${I(n.cost)}`:''}`,style:{flexDirection:'row',alignItems:'center',gap:10,paddingVertical:10,paddingHorizontal:12,borderTopWidth:t?1:0,borderColor:o.colours.border,minHeight:48},children:[(0,C.jsx)(d.T,{style:{flex:1,minWidth:0},children:e.name}),(0,C.jsxs)(r.default,{style:{alignItems:'flex-end',flexShrink:0,maxWidth:'40%'},children:[(0,C.jsx)(d.T,{weight:"semibold",colour:o.colours.goldLight,style:{textAlign:'right'},children:s||'\u2013'}),n?(0,C.jsx)(d.T,{size:o.font.small,colour:o.colours.muted,style:{textAlign:'right'},children:I(n.cost)}):null]})]},e.id)})}):(0,C.jsx)(d.Muted,{center:!0,children:"No ingredients on this card yet."}),(0,C.jsx)(v,{title:"Method"}),e.steps.length?(0,C.jsx)(r.default,{testID:"card-method",style:{width:'100%',gap:10},children:e.steps.map((e,t)=>(0,C.jsxs)(r.default,{accessible:!0,accessibilityLabel:`Step ${t+1}. ${e}`,style:{flexDirection:'row',gap:12,alignItems:'flex-start'},children:[(0,C.jsx)(r.default,{style:{width:32,height:32,borderRadius:16,borderWidth:1.5,borderColor:o.colours.gold,backgroundColor:o.colours.goldTint,alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,C.jsx)(d.T,{size:o.font.small,weight:"bold",colour:o.colours.gold,children:t+1})}),(0,C.jsx)(d.T,{style:{flex:1,minWidth:0,paddingTop:4},children:e})]},t))}):(0,C.jsxs)(d.Muted,{center:!0,children:["No method yet.",s?' Tap Edit to add the steps.':'']}),(0,C.jsx)(b.CardGpPanel,{card:e,actor:t,mode:i}),(0,C.jsxs)(d.Muted,{center:!0,children:["Version ",e.version," \xb7 last changed ",w(e.updatedAt)," by ",e.updatedBy]}),l&&s?(0,C.jsx)(d.Button,{testID:"edit-card",kind:"secondary",label:"Edit card",accessibilityLabel:`Edit ${e.dish}`,onPress:s,style:{alignSelf:'stretch'}}):null,x&&!e.signOff?(0,C.jsxs)(r.default,{style:{gap:6,width:'100%'},children:[h?(0,C.jsx)(d.Banner,{kind:"warn",title:"Not ready to sign off",children:h}):null,(0,C.jsx)(d.Button,{testID:"sign-off",kind:"success",label:`Sign off as ${t.name}`,accessibilityLabel:`Sign off ${e.dish} as ${t.name}`,disabled:!!h,onPress:async()=>{try{await(0,u.recipeCards)().signOff(e.id,t),c(null)}catch(e){c(e?.message??'Could not sign off.')}}})]}):null,!l||x||e.signOff?null:(0,C.jsx)(d.Banner,{kind:"info",title:"Sign-off",children:"Only the Head Chef, an owner or a manager can sign it off."}),a?(0,C.jsx)(d.Banner,{kind:"danger",children:a}):null]})}const R=()=>`i-${Math.random().toString(36).slice(2,9)}`,L=(e,t,s)=>e?{id:e.id,dish:e.dish,section:e.section,price:null==e.price?'':(e.price/100).toFixed(2),description:'',createdBy:e.createdBy??'',ingredients:e.ingredients.map(e=>({...e})),steps:[...e.steps],allergens:{...e.allergens},dismissed:[...e.dismissed],allergenNotes:e.allergenNotes??'',photos:(0,m.cardPhotos)(e),pending:[],confirm:!!e.allergensConfirmed}:{id:(0,m.uuid)(),dish:'',section:t,price:'',description:'',createdBy:s,ingredients:[{id:R(),name:'',qty:'',unit:''}],steps:[''],allergens:{},dismissed:[],allergenNotes:'',photos:[],pending:[],confirm:!1},M=e=>{if(!e.trim())return null;const t=(0,y.parseMoneyInput)(e);return null!=t&&t>=0?Math.round(100*t):'bad'};function O({rid:e,card:i,actor:c,onDone:h}){const p=(0,a.useRestaurant)(e),b=p?.sections??['Mains'],[y,j]=(0,n.useState)(()=>L(i,b[0]??'Mains',c.name)),[w,I]=(0,n.useState)(null),[$,D]=(0,n.useState)(null),[T,S]=(0,n.useState)(!1),P=!(0,m.canEditCards)(c.role)&&!!c.ownRef,v=e=>j(t=>({...t,...e})),B=y.ingredients.filter(e=>e.name.trim()),O={ingredients:B,allergens:y.allergens,dismissed:y.dismissed},E=(0,m.suggestAllergens)(B),A=(0,m.unresolved)(O),N=e=>{const t=y.allergens[e],s={...y.allergens};t?'contains'===t?s[e]='may':delete s[e]:s[e]='contains',v({allergens:s,dismissed:y.dismissed.filter(t=>t!==e),confirm:!1})},z=e=>{const t={...y.allergens};delete t[e],v({allergens:t,dismissed:[...new Set([...y.dismissed,e])],confirm:!1})},H=(e,t)=>v({ingredients:y.ingredients.map((s,n)=>n===e?{...s,...t}:s),confirm:!1}),W=(e,t)=>v({steps:y.steps.map((s,n)=>n===e?t:s)}),_=(e,t)=>{const s=[...y.steps],n=e+t;n<0||n>=s.length||([s[e],s[n]]=[s[n],s[e]],v({steps:s}))},F=y.photos.length+y.pending.length,G=async e=>{if(D(null),F>=m.MAX_RECIPE_PHOTOS)D('A card can hold 5 photos.');else try{const t=await(0,x.capturePlatingPhoto)(e);t&&(v({pending:[...y.pending,t]}),D(`Photo ${F+1} of ${m.MAX_RECIPE_PHOTOS}. Compressed on this device: ${t.width}\xd7${t.height}, ${(0,x.kb)(t.bytes)}${t.originalBytes?` (was ${(0,x.kb)(t.originalBytes)})`:''}.`))}catch(e){D(e?.message??'Could not read that photo.')}},[V,U]=(0,n.useState)(!1),q=y.dish||i?.dish||'this dish';return(0,C.jsxs)(r.default,{testID:"card-editor",style:{gap:12},children:[i?.signOff?(0,C.jsx)(d.Banner,{kind:"warn",title:"Saving a change clears the sign-off",children:"This card is signed off. Any change you save clears it until the Head Chef, an owner or a manager signs it off again."}):null,(0,C.jsx)(d.Field,{testID:"dish-name",label:"Dish name",value:y.dish,onChangeText:e=>v({dish:e}),placeholder:"e.g. Cullen skink"}),P||i?.authorRef?(0,C.jsx)(d.Muted,{center:!0,testID:"card-created-by-fixed",children:`Created by ${P?c.name:i?.createdBy||'Not recorded'}.${P?' Only you can change this card.':''}`}):(0,C.jsx)(d.Field,{testID:"card-created-by-field",label:"Created by",value:y.createdBy,onChangeText:e=>v({createdBy:e}),placeholder:"Chef's name"}),i?null:(0,C.jsx)(d.Field,{testID:"dish-description",label:"Menu description (optional)",value:y.description,onChangeText:e=>v({description:e}),placeholder:"What guests read on the menu"}),(0,C.jsx)(d.T,{size:o.font.small,weight:"medium",colour:o.colours.muted,children:"Menu section"}),(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:b.map(e=>(0,C.jsx)(d.Chip,{label:e,selected:y.section===e,onPress:()=>v({section:e})},e))}),(0,C.jsx)(d.Field,{money:!0,testID:"dish-price",label:"Price (\xa3)",value:y.price,onChangeText:e=>v({price:e}),placeholder:"Blank = price on the board",keyboardType:"decimal-pad"}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Photos"}),(0,C.jsx)(d.T,{center:!0,colour:o.colours.muted,children:"Up to 5 photos."}),(0,C.jsxs)(r.default,{testID:"card-photos",style:{gap:10,width:'100%',alignItems:'center'},children:[y.photos.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,photo:e,height:160,index:t+1,total:F||y.photos.length}),(0,C.jsx)(d.Button,{testID:`photo-remove-${t+1}`,kind:"ghost",label:`Remove photo ${t+1}`,accessibilityLabel:`Remove photo ${t+1} of ${q}`,onPress:()=>v({photos:y.photos.filter((e,s)=>s!==t)})})]},e)),y.pending.map((e,t)=>(0,C.jsxs)(r.default,{style:{width:'100%',gap:6,alignItems:'center'},children:[(0,C.jsx)(k,{dish:q,pending:e.dataUrl,height:160,index:y.photos.length+t+1,total:F}),(0,C.jsx)(d.Button,{testID:`photo-remove-new-${t+1}`,kind:"ghost",label:`Remove photo ${y.photos.length+t+1}`,accessibilityLabel:`Remove new photo ${y.photos.length+t+1}`,onPress:()=>v({pending:y.pending.filter((e,s)=>s!==t)})})]},`new-${t}`)),F?null:(0,C.jsx)(k,{dish:q,height:160})]}),(0,C.jsx)(d.Button,{testID:"photo-camera",kind:"secondary",label:"Take photo",accessibilityLabel:"Take a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('camera')}),(0,C.jsx)(d.Button,{testID:"photo-library",kind:"secondary",label:"Choose photo",accessibilityLabel:"Choose a photo for this recipe card",disabled:F>=m.MAX_RECIPE_PHOTOS,onPress:()=>G('library')}),$?(0,C.jsx)(r.default,{testID:"photo-info",children:(0,C.jsx)(d.Muted,{center:!0,children:$})}):(0,C.jsx)(d.Muted,{center:!0,children:'shared'===(0,u.recipeCards)().mode?'Photos are shrunk on this device, then shared with the team. Staff and guests only see them once the card is signed off.':'Photos are shrunk on this device before they are saved.'}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Ingredients"}),(0,C.jsx)(d.Muted,{children:"Quantity, unit and ingredient. We suggest allergens from the ingredient names."}),y.ingredients.map((e,n)=>{const i=e.name.trim()?(0,m.suggestAllergens)([e]):[];return(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsxs)(d.Row,{gap:6,children:[(0,C.jsx)(t.TextInput,{testID:`ing-qty-${n}`,accessibilityLabel:`Quantity ${n+1}`,value:e.qty,onChangeText:e=>H(n,{qty:e}),placeholder:"Qty",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:64}]}),(0,C.jsx)(t.TextInput,{testID:`ing-unit-${n}`,accessibilityLabel:`Unit ${n+1}`,value:e.unit,onChangeText:e=>H(n,{unit:e}),placeholder:"g / ml / each",placeholderTextColor:"#7D776C",style:[d.styles.input,{width:92}]}),(0,C.jsx)(t.TextInput,{testID:`ing-name-${n}`,accessibilityLabel:`Ingredient ${n+1}`,value:e.name,onChangeText:e=>H(n,{name:e}),placeholder:"Ingredient",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1}]}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove ingredient ${n+1}`,onPress:()=>v({ingredients:y.ingredients.filter((e,t)=>t!==n)})})]}),i.length?(0,C.jsxs)(d.Muted,{children:["Suggests: ",i.map(f.allergenLabel).join(', ')]}):null]},e.id)}),(0,C.jsx)(d.Button,{testID:"ing-add",small:!0,kind:"ghost",label:"Add ingredient",onPress:()=>v({ingredients:[...y.ingredients,{id:R(),name:'',qty:'',unit:''}]})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Method"}),y.steps.map((e,n)=>(0,C.jsxs)(d.Row,{gap:6,style:{alignItems:'flex-start'},children:[(0,C.jsx)(d.T,{colour:o.colours.gold,style:{width:20,paddingTop:10},children:n+1}),(0,C.jsx)(t.TextInput,{testID:`step-${n}`,accessibilityLabel:`Step ${n+1}`,value:e,onChangeText:e=>W(n,e),multiline:!0,placeholder:"Describe this step",placeholderTextColor:"#7D776C",style:[d.styles.input,{flex:1,minHeight:56,textAlignVertical:'top'}]}),(0,C.jsxs)(r.default,{style:{gap:4},children:[(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} up`,onPress:()=>_(n,-1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25b2"})}),(0,C.jsx)(l.default,{accessibilityLabel:`Move step ${n+1} down`,onPress:()=>_(n,1),hitSlop:6,children:(0,C.jsx)(d.T,{colour:o.colours.muted,children:"\u25bc"})}),(0,C.jsx)(s.GoldClose,{size:"sm",label:`Remove step ${n+1}`,onPress:()=>v({steps:y.steps.filter((e,t)=>t!==n)})})]})]},n)),(0,C.jsx)(d.Button,{testID:"step-add",small:!0,kind:"ghost",label:"Add step",onPress:()=>v({steps:[...y.steps,'']})}),(0,C.jsx)(d.Divider,{}),(0,C.jsx)(d.H2,{children:"Allergens (UK 14)"}),(0,C.jsx)(d.Muted,{children:"Tap to cycle: contains \u2192 may contain \u2192 none. Suggested allergens are marked \u201c?\u201d until you add or rule them out."}),A.length?(0,C.jsxs)(r.default,{testID:"allergen-suggestions",style:{gap:6},children:[(0,C.jsx)(d.Banner,{kind:"warn",title:`Check ${A.length} suggested allergen${1===A.length?'':'s'}`,children:A.map(e=>`${(0,f.allergenLabel)(e)} (from ${(0,m.suggestedBy)(B,e).join(', ')})`).join('; ')}),A.map(e=>(0,C.jsxs)(d.Row,{gap:6,wrap:!0,children:[(0,C.jsx)(d.T,{style:{flex:1},children:(0,f.allergenLabel)(e)}),(0,C.jsx)(d.Button,{testID:`suggest-add-${e}`,small:!0,label:"Contains",onPress:()=>v({allergens:{...y.allergens,[e]:'contains'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-may-${e}`,small:!0,kind:"secondary",label:"May contain",onPress:()=>v({allergens:{...y.allergens,[e]:'may'},confirm:!1})}),(0,C.jsx)(d.Button,{testID:`suggest-dismiss-${e}`,small:!0,kind:"ghost",label:"Not in this dish",onPress:()=>z(e)})]},e)),(0,C.jsx)(d.Button,{testID:"apply-suggestions",small:!0,kind:"secondary",label:"Add all suggestions as \u2018contains\u2019",onPress:()=>{const e={...y.allergens};A.forEach(t=>{e[t]='contains'}),v({allergens:e,confirm:!1})}})]}):null,(0,C.jsx)(d.Row,{wrap:!0,gap:6,children:f.ALLERGENS.map(e=>{const t=y.allergens[e.id],s=E.includes(e.id)&&!t&&!y.dismissed.includes(e.id),n='contains'===t?o.colours.redBg:'may'===t?o.colours.amberBg:o.colours.surface2,i='contains'===t?o.colours.red:'may'===t?o.colours.amber:s?o.colours.gold:o.colours.border;return(0,C.jsx)(l.default,{testID:`allergen-${e.id}`,accessibilityRole:"button",accessibilityLabel:`${e.short}: ${'contains'===t?'contains':'may'===t?'may contain':'not marked'}`,onPress:()=>N(e.id),style:{paddingVertical:6,paddingHorizontal:10,borderRadius:16,borderWidth:s?2:1,borderStyle:s?'dashed':'solid',borderColor:i,backgroundColor:n},children:(0,C.jsxs)(d.T,{size:o.font.small,colour:'contains'===t?'#FFD9D4':'may'===t?'#FFE2A8':o.colours.text,children:[e.short,'may'===t?' (may)':'',s?' ?':'']})},e.id)})}),y.dismissed.length?(0,C.jsxs)(d.Muted,{children:["Ruled out: ",y.dismissed.map(f.allergenLabel).join(', ')]}):null,(0,C.jsx)(d.Field,{testID:"allergen-notes",label:"Allergen notes (optional)",value:y.allergenNotes,onChangeText:e=>v({allergenNotes:e}),placeholder:"e.g. Cooked in the shared fryer"}),P?(0,C.jsx)(d.Muted,{center:!0,testID:"allergens-checked-by-chef",children:"The Head Chef, an owner or a manager checks and confirms the allergens before this card goes live."}):(0,C.jsxs)(l.default,{testID:"confirm-allergens",accessibilityRole:"checkbox",accessibilityState:{checked:y.confirm,disabled:A.length>0},disabled:A.length>0,onPress:()=>v({confirm:!y.confirm}),style:{flexDirection:'row',gap:10,alignItems:'center',padding:10,borderRadius:10,borderWidth:1,borderColor:y.confirm?o.colours.ok:o.colours.border,opacity:A.length?.5:1},children:[(0,C.jsx)(r.default,{style:{width:22,height:22,borderRadius:4,borderWidth:2,borderColor:y.confirm?o.colours.ok:o.colours.muted,alignItems:'center',justifyContent:'center',backgroundColor:y.confirm?o.colours.okBg:'transparent'},children:y.confirm?(0,C.jsx)(d.T,{colour:o.colours.ok,children:"\u2713"}):null}),(0,C.jsx)(d.T,{style:{flex:1},children:A.length?'Check the suggested allergens above first':`I have checked the allergen list against the ingredients (${c.name})`})]}),w?(0,C.jsx)(d.Banner,{kind:"danger",children:w}):null,(0,C.jsx)(d.Button,{testID:"card-save",label:V?'Saving\u2026':i?'Save changes':'Save card',disabled:V,onPress:async()=>{I(null);const t=M(y.price);if(!y.dish.trim())return I('Give the dish a name.');if('bad'===t)return I('Price should be in pounds, e.g. 14.50 (or leave it blank for "price on the board").');const s=(0,u.recipeCards)();U(!0);try{const n=[...y.photos];for(const t of y.pending){if(n.length>=m.MAX_RECIPE_PHOTOS)break;n.push(await s.savePhoto(e,y.id,t))}const l=y.steps.map(e=>e.trim()).filter(Boolean),r=y.createdBy.trim(),o={dish:y.dish.trim(),section:y.section,price:t,ingredients:B.map(e=>({...e,name:e.name.trim(),qty:e.qty.trim(),unit:e.unit.trim()})),steps:l,allergens:y.allergens,dismissed:y.dismissed,allergenNotes:y.allergenNotes.trim()||void 0,photo:n[0],photos:n,createdBy:r||void 0};if(i)await s.update(i.id,{...o,confirmAllergens:y.confirm},c),h(i.id);else{const t=await s.create(e,{...o,id:y.id,description:y.description.trim()||void 0},c);y.confirm&&await s.update(t.id,{confirmAllergens:!0},c),h(t.id)}}catch(e){I(e?.message??'Could not save the card.')}finally{U(!1)}}}),(0,C.jsx)(d.Muted,{center:!0,children:(0,m.maySignOff)(c,{createdBy:y.createdBy||c.name,createdByRole:c.role})?'After saving, sign the card off so it goes live.':'After saving, the Head Chef, an owner or a manager signs it off before it goes live.'}),i?T?(0,C.jsxs)(d.Row,{gap:8,children:[(0,C.jsx)(d.Button,{testID:"card-delete-yes",small:!0,kind:"danger",label:"Yes, remove this dish",onPress:async()=>{if(i)try{await(0,u.recipeCards)().remove(i.id,c),h(null)}catch(e){I(e?.message??'Could not remove the card.')}}}),(0,C.jsx)(d.Button,{small:!0,kind:"ghost",label:"Keep it",onPress:()=>S(!1)})]}):(0,C.jsx)(d.Button,{testID:"card-delete",small:!0,kind:"ghost",label:"Remove card and dish from the menu",onPress:()=>S(!0)}):null]})}const E=e=>e.replace(/ \xb7 Starter$/,' \xb7 1').replace(/ \xb7 Main$/,' \xb7 2');function A(e){const t=(0,a.useAllMenu)(e),s=(0,a.useRecipeCards)(e);return(0,n.useMemo)(()=>{const e=new Map(s.map(e=>[e.menuItemId,e]));return(0,m.unsignedOldestFirst)(t,t=>e.get(t.id)??(t.recipeCardId?s.find(e=>e.id===t.recipeCardId):void 0))},[t,s])}function N({c:e,actor:t,mode:s,editable:n,onPress:i}){const a=(0,m.cardPhotos)(e),c=(0,b.useCardCosting)(e,'read'===s?'staff':t.role,s),h=f.ALLERGENS.filter(t=>e.allergens[t.id]).length,u=c?.summary.gp,x=c?.summary.tone,y='ok'===x?o.colours.ok:'amber'===x?o.colours.amber:'red'===x?o.colours.red:o.colours.muted,j=`${e.dish}, ${e.section}, ${$(e.price)}, ${h?`${h} allergen${1===h?'':'s'}`:'no allergens marked'}${null!=u?`, GP ${u.toFixed(1)} percent`:''}, created by ${e.createdBy||'not recorded'}, ${e.signOff?`signed off by ${e.signOff.by}`:'awaiting sign-off'}`;return(0,C.jsxs)(l.default,{testID:`card-${e.menuItemId}`,accessibilityRole:"button",accessibilityLabel:j,onPress:i,style:({pressed:t})=>({width:'100%',minHeight:48,flexDirection:'row',gap:12,alignItems:'center',padding:10,borderRadius:18,borderWidth:1,borderColor:!e.signOff&&n?o.colours.amber:o.colours.accentBorder,backgroundColor:t?o.colours.tilePressed:o.colours.tile}),children:[(0,C.jsx)(r.default,{style:{width:84,flexShrink:0},children:(0,C.jsx)(k,{dish:e.dish,photo:a[0],height:84,radius:14})}),(0,C.jsxs)(r.default,{style:{flex:1,minWidth:0,gap:4,alignItems:'center'},children:[(0,C.jsx)(d.T,{center:!0,weight:"bold",size:18,colour:o.colours.gold,children:e.dish}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,colour:o.colours.muted,children:[e.section," \xb7 ",$(e.price),'example'===e.origin?` \xb7 ${p.EXAMPLE_TAG}`:'']}),(0,C.jsxs)(d.Row,{wrap:!0,gap:6,style:{justifyContent:'center'},children:[(0,C.jsx)(P,{label:h?`${h} allergen${1===h?'':'s'}`:'No allergens marked'}),null!=u?(0,C.jsx)(r.default,{testID:`card-gp-${e.menuItemId}`,style:{paddingHorizontal:10,paddingVertical:4,borderRadius:999,borderWidth:1.5,borderColor:y},children:(0,C.jsxs)(d.T,{size:o.font.small,weight:"bold",colour:y,children:["GP ",u.toFixed(1),"%"]})}):null]}),(0,C.jsxs)(d.T,{center:!0,size:o.font.small,testID:`card-created-${e.menuItemId}`,children:["Created by ",e.createdBy||'Not recorded']}),(0,C.jsx)(d.T,{center:!0,size:o.font.small,colour:e.signOff?o.colours.goldLight:o.colours.amber,children:e.signOff?`Signed off by ${e.signOff.by}, ${w(e.signOff.at)}`:m.STATE_LABEL.awaiting})]})]})}},1155,[812,779,17,319,385,85,804,777,858,1156,1026,867,845,847,870,1082,1157,840,1158,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"portionCardItemIds",{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,"OFF_CARD_LIST",{enumerable:!0,get:function(){return n}});const t=['a-langoustines-starter','a-langoustines-main','a-moules-starter','a-moules-main'],n=new Set(['a-scallops'])},1156,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CREATOR_TITLE",{enumerable:!0,get:function(){return n}}),e.DishCreator=function(n){return null},e.useCardCosting=function(...n){return null},e.CardGpPanel=function(n){return null};const n='New dish creator'},1157,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"TAKEAWAY_SWITCH_LABEL",{enumerable:!0,get:function(){return f}}),_e.TakeawaySwitch=function({itemId:e,dish:n,role:h,me:w,signedOff:y,priced:b}){const k=(0,l.useStaffTakeaway)(e=>e.rows),j=(0,l.useStaffTakeaway)(e=>e.canSet),T=(0,l.useStaffTakeaway)(e=>e.busy),x=(0,l.useStaffTakeaway)(t=>t.errorItem===e?t.error:'');(0,t.useEffect)(()=>{(0,l.loadStaffTakeaway)()},[]);const S=k?.[e]??(k&&(0,l.isPitch)()?(0,l.pitchRow)(e):void 0),p={width:'100%',gap:6,paddingVertical:8,paddingHorizontal:12,borderRadius:14,borderWidth:1,borderColor:c.colours.border,backgroundColor:c.colours.surface};if(null===k)return(0,u.jsx)(s.default,{testID:"takeaway-switch-offline",style:p,children:(0,u.jsxs)(o.Muted,{center:!0,children:[f,": connect to the venue to see or change this."]})});if(!S)return null;const v=S.onMenu,_=v&&!y?'Guests can order it for takeaway once it is signed off.':v&&!b?'Guests can order it for takeaway once it has a price.':v?'Guests can order it for collection.':'Guests see it on the takeaway menu as \u201cNot available for takeaway today\u201d.';return(0,u.jsxs)(s.default,{testID:"takeaway-switch-box",style:p,children:[(0,l.showsSwitch)(j,h)?(0,u.jsx)(o.Toggle,{testID:"takeaway-switch",label:f,a11y:`${f}, ${n}`,value:v,disabled:T===e,onChange:t=>{(0,l.setTakeawayAvailable)(e,t,w).catch(()=>{})}}):(0,u.jsxs)(s.default,{accessible:!0,accessibilityLabel:`${f}: ${v?'yes':'no'}. Only the Head Chef, a manager or an owner can change this.`,children:[(0,u.jsxs)(o.T,{testID:"takeaway-switch-readonly",children:[f,": ",v?'Yes':'No']}),(0,u.jsx)(o.Muted,{children:"Only the Head Chef, a manager or an owner can change this."})]}),(0,u.jsx)(o.Muted,{children:_}),x&&null===T?(0,u.jsx)(o.Banner,{kind:"danger",children:x}):null]})};var e,t=r(d[0]),n=r(d[1]),s=(e=n)&&e.__esModule?e:{default:e},o=r(d[2]),c=r(d[3]),l=r(d[4]),u=r(d[5]);const f='Available for takeaway'},1158,[17,85,777,804,1159,8]); @@ -1494,7 +1494,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return f}});var t=r(d[0]);r(d[1]);var n=r(d[2]),u=r(d[3]),c=r(d[4]);function f(){return'owner'!==u.APP_VARIANT?(0,c.jsx)(t.Redirect,{href:u.ENTRY[u.APP_VARIANT]}):(0,c.jsx)(n.OwnerApp,{})}},1411,[13,17,1412,856,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.OwnerApp=function(){return null}},1412,[]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"default",{enumerable:!0,get:function(){return c}});var t=r(d[0]);r(d[1]);var n=r(d[2]),f=r(d[3]),u=r(d[4]);function c(){return(0,n.canShow)('staff')?(0,u.jsx)(f.StaffApp,{}):(0,u.jsx)(t.Redirect,{href:n.ENTRY[n.APP_VARIANT]})}},1413,[13,17,856,1414,8]); -__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),i=_r(d[2]),o=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),C=_r(d[19]),S=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),ie=_r(d[53]),oe=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Ce=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Se={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const Ie=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Oe,We]=(0,P.useState)('home'),[Le,ze]=(0,P.useState)(null),[Ee,He]=(0,P.useState)(!1),De=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ne=(0,G.useChatUnread)().total,Fe=!0===(0,R.useCashAccess)(e=>e.mine),Ue=(0,P.useRef)({t:'home',s:null});Ue.current={t:Oe,s:Le};const Ve=(0,P.useRef)([]),$e=(0,P.useCallback)((e,s=null)=>{const t=Ue.current;t.t===e&&t.s===s||(Ve.current=[...Ve.current,{...t,y:Qe.leave()}].slice(-30),Qe.restore(0)),We(e),ze(s)},[]),Ge=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=Ue.current;let s=Ve.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ve.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Qe.leave(),We(t.t),ze(t.s),Qe.restore(t.y??0),!0},[]);(0,f.useWebBack)(Ge);const Ye=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{C.PITCH&&(globalThis.__pitchGo=$e,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[$e]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>$e('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&$e('me','orderlists'),'chat'===e&&(Fe?$e('me','staffchat'):$e('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Qe=(0,h.useScrollMemory)(De),Je=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Fe?$e('me','staffchat'):$e('chat'):'cashup'===e?$e('cashup'):'clock'===s?$e('clock'):'rota'===s?$e('rota'):s&&Me.some(e=>e.id===s)?$e('me',s):'blocks'===s&&pe?$e('me','mgr-blocks'):void $e('home'===e?'home':'me'),[$e,pe,Fe]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Ge);return()=>e.remove()},[Ge]);const Ke=Fe?[Te,...Me]:Me,qe='me'===Oe&&Le?Ke.find(e=>e.id===Le)??(pe?Ae.find(e=>e.id===Le):void 0):void 0,Xe=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),Ze=Ke.filter(e=>('suppliers'!==e.id||Ie)&&('orderlists'!==e.id||Xe||B&&'staff'!==B.role)),es=Fe?Ce:ve,ss='cashup'===Oe||'cashup'===qe?.id?'cashup':Oe;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Fe&&'chat'===Oe&&$e('me','staffchat')},[Fe,Oe,$e]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,o.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>He(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:De,...Qe.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Oe?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Oe?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Oe&&!Le||Ye),onBack:Ge,title:qe?qe.title:Se[Oe]}),'home'===Oe&&pe?(0,je.jsx)(ie.ManagerFeaturesNote,{}):null,'home'===Oe&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Oe&&B?(0,je.jsx)(S.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Oe?(0,je.jsx)(Be,{go:Je}):null,'clock'===Oe?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Oe?(0,je.jsx)(ue.Rota,{}):null,'chat'===Oe||'staffchat'===qe?.id?(0,je.jsx)(G.Chat,{go:Je}):null,'cashup'===Oe?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Oe||qe?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ze.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Ae.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>$e('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(ie.ManagerFeaturesAbout,{})]}):null,Ie?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&qe?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===qe.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===qe.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===qe.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===qe.id?(0,je.jsx)(ie.TablesToClear,{rid:r}):null,'mgr-blocks'===qe.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===qe.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===qe.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===qe.id?(0,je.jsx)(ie.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===qe.id?(0,je.jsx)(ie.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===qe?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===qe?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===qe?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===qe?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===qe?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===qe?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===qe?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===qe?.id?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===qe?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===qe?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===qe?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===qe?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===qe?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===qe?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===qe?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===qe?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===qe?.id?Ie?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===qe?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,o.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,i.soutersSurface)('#0d0d0d'),active:ss,onPress:e=>$e(e),tabs:es.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ne||'me'===e.id&&Fe&&Ne?{text:String(Ne),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:Ee,onClose:()=>He(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(oe.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),i=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),i?null:(0,je.jsx)(r.CoversToday,{rid:s}),i?(0,je.jsx)(pe.DayView,{rid:s,day:i,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:i}){const o=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==o?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:i.replace(' (example)','')}})}},1414,[1415,1419,813,912,1072,1420,1203,1204,1028,1025,1026,1421,1423,1426,1153,891,978,1428,975,880,1031,1032,1429,914,1008,915,17,1155,1231,1235,1197,356,385,278,85,409,19,777,857,876,804,1161,1430,1066,1084,1086,1081,1027,1010,1057,1437,1438,1439,1447,1448,920,219,1236,1176,1183,1444,1196,1179,1453,1180,878,1206,1207,884,776,899,8]); +__d(function(g,_r,_i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.StaffApp=function(){return(0,je.jsx)(ee.StaffAppCtx.Provider,{value:!0,children:(0,je.jsx)(Ae,{})})};var s=_r(d[0]),t=_r(d[1]),o=_r(d[2]),i=_r(d[3]),r=_r(d[4]),l=_r(d[5]),n=_r(d[6]),c=_r(d[7]),u=_r(d[8]),h=_r(d[9]),f=_r(d[10]),p=_r(d[11]),b=_r(d[12]),y=_r(d[13]),x=_r(d[14]),k=_r(d[15]),j=_r(d[16]),w=_r(d[17]),v=_r(d[18]),S=_r(d[19]),C=_r(d[20]),T=_r(d[21]),M=_r(d[22]),R=_r(d[23]),A=_r(d[24]),B=_r(d[25]),P=_r(d[26]),I=_r(d[27]),O=_r(d[28]),W=_r(d[29]),L=_r(d[30]),z=e(_r(d[31])),E=e(_r(d[32])),H=e(_r(d[33])),_=e(_r(d[34])),D=e(_r(d[35])),N=_r(d[36]),F=_r(d[37]),U=_r(d[38]),V=_r(d[39]),$=_r(d[40]),G=_r(d[41]),Y=_r(d[42]),Q=_r(d[43]),J=_r(d[44]),K=_r(d[45]),q=_r(d[46]),X=_r(d[47]),Z=_r(d[48]),ee=_r(d[49]),se=_r(d[50]),te=_r(d[51]),ae=_r(d[52]),oe=_r(d[53]),ie=_r(d[54]),re=_r(d[55]);_r(d[56]);var le=_r(d[57]),ne=_r(d[58]),de=_r(d[59]),ce=_r(d[60]),ue=_r(d[61]),he=_r(d[62]),fe=_r(d[63]),pe=_r(d[64]),ge=_r(d[65]),me=_r(d[66]),be=_r(d[67]),ye=_r(d[68]),xe=_r(d[69]),ke=_r(d[70]),je=_r(d[71]);const we=ge.ROSTER.find(e=>'chef'===e.app)?.id,ve=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'chat',label:'Chat',icon:'chat'},{id:'me',label:'Me',icon:'user'}],Se=[{id:'home',label:'Home',icon:'home'},{id:'clock',label:'Clock',icon:'clock'},{id:'rota',label:'Rota',icon:'bookings'},{id:'cashup',label:'Cash up',icon:'cashup'},{id:'me',label:'Me',icon:'user'}],Ce={home:'Today',clock:'Clock in / out',rota:'Rota, swaps & leave',chat:'Staff chat',me:'Me',cashup:'Cash up'},Te={id:'staffchat',title:'Staff chat',sub:'Messages with the team on this venue'},Me=[{id:'mytips',title:'Tips',sub:'The venue tip pot and today\u2019s tips'},{id:'reviews',title:'Reviews',sub:'Published reviews, newest first'},{id:'bookings',title:'Bookings',sub:'Any day, back or forward: tables, Covers, Unseat and Undo'},{id:'loyalty',title:'Stamp card',sub:'Find a guest, add a stamp or use a reward'},{id:'guests',title:'Guest profiles',sub:'Look a guest up: visits, Covers, allergies they told us, preferences'},{id:'giftcards',title:'Gift cards',sub:'Check a balance, take it off the bill, mark paid at the till'},{id:'tableorders',title:'Table orders',sub:'Orders from guests\u2019 phones at the table: accept, mark served or cancel'},{id:'soldout',title:'Sold out',sub:'What\u2019s run out today. Mark sold out or Back on; shows on the Display'},{id:'board',title:'Question board',sub:'Ask the team anything anonymously, and vote'},{id:'recipecards',title:'Recipe cards',sub:'Signed-off dishes: photo, ingredients, method and allergens (read-only)'},{id:'avatar',title:'My avatar',sub:'Your space-age avatar, or create one from a photo'},{id:'cashup',title:'Cash up',sub:'End-of-night takings: type in the cash up, including paid outs, or upload a spreadsheet (if a manager has switched it on for you)'},{id:'haccp',title:'Food safety checks',sub:'Record fridge, freezer, cooking and other checks'},{id:'accidents',title:'Accident book',sub:'Report an accident or near miss; see your own entries'},{id:'mypay',title:'My hours & pay',sub:'Shifts, paid hours and estimated pay'},{id:'timesheets',title:'My timesheets',sub:'Your clock-ins, breaks and any changes'},{id:'orderlists',title:'Order lists',sub:'Add what\u2019s running low (Alsons drinks, Cash and carry)'},{id:'phone',title:'Turn on alerts',sub:'Get your reminders on this phone, even with the app closed'},{id:'suppliers',title:'Suppliers',sub:'Contacts and order days (if your manager allows)'},{id:'privacy',title:'Privacy & location',sub:'What CoverCharge for Staff stores about you'}],Re=[{id:'mgr-plan',title:'Tables & areas',sub:'Edit the table plan, areas, seats and joined tables'},{id:'mgr-times',title:'Booking times',sub:'Kitchen hours, table times and Covers per booking slot'},{id:'mgr-bookings',title:'Bookings (manager)',sub:'New, edit and cancel bookings, walk-ins, seat, move and finish tables, deposit status'},{id:'mgr-clear',title:'Tables to clear',sub:'Tables waiting to be cleared; mark them cleared'},{id:'mgr-blocks',title:'Block bookings',sub:'Block now, add a block, close the garden'},{id:'mgr-allergy',title:'Allergy checks',sub:'Every allergy order\u2019s sign-offs and the allergen log'},{id:'mgr-stock',title:'Tracked stock',sub:'What\u2019s counted live through service; add or change items'},{id:'mgr-clock',title:'Who\u2019s clocked in',sub:'Today\u2019s clock-ins for the team (read only)'},{id:'mgr-swaps',title:'Shift swaps',sub:'Approve swaps and cover, or give a shift to someone else'}];function Ae(){const{r:e,rid:r,me:n,meId:T,today:M,now:A}=(0,ee.useCtx)(3e4);(0,W.useReviewAlerts)(r),(0,he.useStaffTipsNotice)(r,M);const B=(0,ee.useSignedIn)(),fe=B?.ownerAccess&&'owner'!==B.role?'owner privileges':B?.managerAccess&&'staff'===B.role?'manager privileges':'',pe=(0,ee.useShiftManager)(),ge=(0,ke.useSync)(e=>e.perms),Ae=(0,ke.useSync)(e=>e.staffRef),Ie=ge.includes('recipes.create_own'),Oe=Re.filter(e=>'mgr-swaps'===e.id?ge.includes('rota.swap'):'mgr-times'!==e.id||(ge.includes('bookings.settings')||ge.includes('*')));(0,k.useSoldOutLink)(!0,n);(0,V.useOwner)(e=>e.staff);const We=(0,V.useOwner)(e=>e.staffCanViewSuppliers),[Le,ze]=(0,P.useState)('home'),[Ee,He]=(0,P.useState)(null),[De,Ne]=(0,P.useState)(!1),Fe=(0,P.useRef)(null);(0,P.useEffect)(()=>{(0,ee.ensureAttendance)(M,A),(0,G.ensureChat)(A)},[M]),globalThis.__ccNow=A.getTime();const Ue=(0,G.useChatUnread)().total,Ve=!0===(0,R.useCashAccess)(e=>e.mine),$e=(0,P.useRef)({t:'home',s:null});$e.current={t:Le,s:Ee};const Ge=(0,P.useRef)([]),Ye=(0,P.useCallback)((e,s=null)=>{const t=$e.current;t.t===e&&t.s===s||(Ge.current=[...Ge.current,{...t,y:Ke.leave()}].slice(-30),Ke.restore(0)),ze(e),He(s)},[]),Qe=(0,P.useCallback)(()=>{if((0,f.runBackLayer)())return!0;const e=$e.current;let s=Ge.current.pop();for(;s&&s.t===e.t&&s.s===e.s;)s=Ge.current.pop();if(!s&&'home'===e.t&&!e.s)return!1;const t=s??{t:'home',s:null};return Ke.leave(),ze(t.t),He(t.s),Ke.restore(t.y??0),!0},[]);(0,f.useWebBack)(Qe);const Je=(0,f.useInnerBackShown)();(0,P.useEffect)(()=>{S.PITCH&&(globalThis.__pitchGo=Ye,globalThis.__pitchClock={setClockServer:v.setClockServer,markClockSent:v.markClockSent,markClockUnsent:v.markClockUnsent})},[Ye]),(0,P.useEffect)(()=>(0,w.startForegroundRefresh)(),[]),(0,Q.useShiftReminders)({rid:r,staffId:T,name:n,onStartBreak:()=>Ye('clock')}),(0,J.useScheduledNotices)({rid:r,staffId:B?.id??'',name:n,onOpen:e=>{'orderlists'===e&&Ye('me','orderlists'),'chat'===e&&(Ve?Ye('me','staffchat'):Ye('chat'))}}),(0,K.useOffRotaPrompt)({rid:r,staffId:B?.id??''});const Ke=(0,h.useScrollMemory)(Fe),qe=(0,P.useCallback)((e,s=null)=>'chat'===e||'staffchat'===s||'chat'===s?Ve?Ye('me','staffchat'):Ye('chat'):'cashup'===e?Ye('cashup'):'clock'===s?Ye('clock'):'rota'===s?Ye('rota'):s&&Me.some(e=>e.id===s)?Ye('me',s):'blocks'===s&&pe?Ye('me','mgr-blocks'):void Ye('home'===e?'home':'me'),[Ye,pe,Ve]);(0,P.useEffect)(()=>{const e=z.default.addEventListener('hardwareBackPress',Qe);return()=>e.remove()},[Qe]);const Xe=(Ze=Ve?[Te,...Me]:Me,Ie?Ze.map(e=>'recipecards'===e.id?{...e,sub:'Signed-off dishes, and the cards you create: photo, ingredients, method and allergens'}:e):Ze);var Ze;const es='me'===Le&&Ee?Xe.find(e=>e.id===Ee)??(pe?Oe.find(e=>e.id===Ee):void 0):void 0,ss=(0,Z.useOrderLists)(e=>e.settings[r]?.allowStaff??!0),ts=Xe.filter(e=>('suppliers'!==e.id||We)&&('orderlists'!==e.id||ss||B&&'staff'!==B.role)),as=Ve?Se:ve,os='cashup'===Le||'cashup'===es?.id?'cashup':Le;(0,P.useEffect)(()=>{V.useOwner.getState().staffAs&&V.useOwner.setState({staffAs:void 0})},[]),(0,P.useEffect)(()=>{Ve&&'chat'===Le&&Ye('me','staffchat')},[Ve,Le,Ye]);(0,D.default)().width;return(0,je.jsxs)(N.SafeAreaView,{style:{flex:1,backgroundColor:$.colours.bg},edges:['top','left','right','bottom'],children:[(0,je.jsxs)(_.default,{style:{position:'relative',paddingHorizontal:14,paddingTop:6,paddingBottom:8,borderBottomWidth:1,borderColor:$.colours.border,gap:6},children:[(0,je.jsx)(_.default,{testID:"header-me-wrap",style:{alignItems:'flex-start',minHeight:44,justifyContent:'center',maxWidth:'100%'},children:(0,je.jsx)(E.default,{testID:"header-me",accessibilityRole:"button",accessibilityLabel:`${(0,i.privateClockVenue)(r)?`Signed in as ${n}`:'Signed in as'}${fe?`, ${fe}`:''}`,onPress:()=>Ne(!0),hitSlop:6,style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:22,paddingHorizontal:10,paddingVertical:4,maxWidth:'100%',minHeight:44,justifyContent:'center'},children:(0,je.jsxs)(F.Row,{gap:6,style:{justifyContent:'flex-start'},children:[(0,je.jsx)(ye.StaffAvatar,{id:T,size:24,ring:!1}),(0,je.jsxs)(_.default,{style:{flexShrink:1},children:[(0,je.jsxs)(F.T,{size:13,weight:"semibold",colour:$.colours.gold,numberOfLines:1,style:{flexShrink:1},children:[n.replace(' (example)',''),B?'':' (preview)'," \u25be"]}),fe?(0,je.jsx)(F.Muted,{center:!1,size:10,numberOfLines:1,children:fe}):null]})]})})}),(0,je.jsx)(U.VenueHeaderBlock,{rid:e.id,name:e.name,badge:"STAFF",place:"Front of House"+(e.location?` \xb7 ${e.location.split(',').slice(0,2).join(',')}`:'')})]}),(0,je.jsxs)(H.default,{ref:Fe,...Ke.props,contentContainerStyle:{padding:14,paddingBottom:16,gap:12,width:'100%',maxWidth:760,alignSelf:'center'},keyboardShouldPersistTaps:"handled",children:['home'===Le?(0,je.jsx)(u.AlertsBanner,{}):null,'home'===Le?(0,je.jsx)(c.WhosOnShift,{}):null,(0,je.jsx)(f.BackTitleRow,{back:!('home'===Le&&!Ee||Je),onBack:Qe,title:es?es.title:Ce[Le]}),'home'===Le&&pe?(0,je.jsx)(oe.ManagerFeaturesNote,{}):null,'home'===Le&&B&&'staff'!==B.role&&!pe&&'undefined'!=typeof window?(0,je.jsxs)(_.default,{testID:"manager-access-banner",style:{borderWidth:1,borderColor:$.colours.gold,borderRadius:12,padding:10,gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"You have manager access"}),(0,je.jsx)(F.Muted,{children:"The Manager app has everything here plus bookings, the rota, staff and settings."}),(0,je.jsx)(E.default,{accessibilityRole:"button",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)},style:{alignSelf:'flex-start',borderWidth:1,borderColor:$.colours.gold,borderRadius:14,paddingHorizontal:12,paddingVertical:5,minHeight:44,justifyContent:'center'},children:(0,je.jsx)(F.T,{size:14,colour:$.colours.gold,children:"Open the Managers app \u203a"})})]}):null,'home'===Le&&B?(0,je.jsx)(C.MyTasksToday,{rid:r,staffId:B.id,name:B.name,onShift:(0,Q.shiftNow)(B.id,A.getTime()).on}):null,'home'===Le?(0,je.jsx)(Be,{go:qe}):null,'clock'===Le?(0,je.jsx)(ue.ClockInOut,{}):null,'rota'===Le?(0,je.jsx)(ue.Rota,{}):null,'chat'===Le||'staffchat'===es?.id?(0,je.jsx)(G.Chat,{go:qe}):null,'cashup'===Le?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'me'!==Le||es?null:(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.border,backgroundColor:$.colours.surface,overflow:'hidden'},children:ts.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),pe?(0,je.jsxs)(_.default,{testID:"manager-features",style:{gap:6},children:[(0,je.jsx)(F.T,{weight:"semibold",colour:$.colours.gold,children:"Manager features"}),(0,je.jsx)(_.default,{style:{borderRadius:14,borderWidth:1,borderColor:$.colours.gold,backgroundColor:$.colours.surface,overflow:'hidden'},children:Oe.map((e,s)=>(0,je.jsx)(E.default,{testID:`audit-page-${e.id}`,accessibilityRole:"button",accessibilityLabel:e.title,onPress:()=>Ye('me',e.id),style:({pressed:e})=>({padding:12,borderTopWidth:s?1:0,borderColor:$.colours.border,backgroundColor:e?'#1d1a14':'transparent'}),children:(0,je.jsxs)(F.Row,{style:{justifyContent:'space-between'},children:[(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"medium",children:e.title}),(0,je.jsx)(F.Muted,{children:e.sub})]}),(0,je.jsx)(F.T,{colour:$.colours.muted,children:"\u203a"})]})},e.id))}),(0,je.jsx)(oe.ManagerFeaturesAbout,{})]}):null,We?null:(0,je.jsx)(F.Muted,{children:"Suppliers are hidden: your manager hasn\u2019t shared them with staff."}),(0,je.jsxs)(F.Muted,{center:!0,children:["Staff app \xb7 ",j.APP_VERSION," \xb7 ",'live'===ke.useSync.getState().mode?'shared with your team':'saved on this device until it connects']})]}),pe&&es?.id.startsWith('mgr-')?(0,je.jsxs)(ee.ShiftMgrScope.Provider,{value:!0,children:['mgr-plan'===es.id?(0,je.jsx)(s.TablePlan,{}):null,'mgr-times'===es.id?(0,je.jsx)(t.StaffBookingTimes,{}):null,'mgr-bookings'===es.id?(0,je.jsx)(Y.Bookings,{}):null,'mgr-clear'===es.id?(0,je.jsx)(oe.TablesToClear,{rid:r}):null,'mgr-blocks'===es.id?(0,je.jsx)(se.BlocksPage,{}):null,'mgr-allergy'===es.id?(0,je.jsx)(te.AllergenSignOffLog,{}):null,'mgr-stock'===es.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(ae.TrackedStockPage,{}),(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)','')})]}):null,'mgr-clock'===es.id?(0,je.jsx)(oe.ClockOverview,{today:M,now:A}):null,'mgr-swaps'===es.id?(0,je.jsx)(oe.SwapApprovals,{today:M,me:n}):null]}):null,'loyalty'===es?.id?(0,je.jsx)(p.StaffLoyalty,{venue:e.name,canWrite:pe}):null,'guests'===es?.id?(0,je.jsx)(b.GuestProfiles,{me:n.replace(' (example)',''),manager:!1}):null,'bookings'===es?.id?(0,je.jsx)(Y.Bookings,{}):null,'giftcards'===es?.id?(0,je.jsx)(y.GiftCardsPage,{me:n.replace(' (example)',''),canWrite:pe}):null,'tableorders'===es?.id?(0,je.jsx)(l.StaffTableOrders,{rid:r,me:n.replace(' (example)',''),canWrite:pe}):null,'soldout'===es?.id?(0,je.jsx)(x.SoldOutList,{rid:r,by:n.replace(' (example)',''),canMark:pe}):null,'board'===es?.id?(0,je.jsx)(L.QuestionBoard,{rid:r,today:M,manager:!1,by:""}):null,'recipecards'===es?.id?Ie&&Ae?(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n.replace(' (example)',''),role:'staff',ownRef:Ae},mode:"own"}):(0,je.jsx)(I.RecipeCards,{rid:e.id,actor:{name:n,role:'staff'},mode:"read"}):null,'avatar'===es?.id?(0,je.jsx)(xe.AvatarMaker,{meId:T,me:n}):null,'cashup'===es?.id?(0,je.jsx)(Pe,{rid:r,today:M,meId:T,me:n}):null,'haccp'===es?.id?(0,je.jsx)(be.HaccpLog,{mode:"staff",me:n,meId:T,now:A,rid:e.id}):null,'accidents'===es?.id?(0,je.jsx)(me.AccidentBook,{app:"staff",me:n,meId:T,now:A,seeAll:!1}):null,'mypay'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ne.MyHoursPay,{staffId:T})]}):null,'mytips'===es?.id?(0,je.jsx)(he.MyTips,{}):null,'reviews'===es?.id?(0,je.jsx)(O.ReviewsSection,{rid:r,mode:"read",venueName:e.name}):null,'timesheets'===es?.id?(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(de.MyPeriods,{staffId:T}),(0,je.jsx)(ue.Timesheets,{})]}):null,'orderlists'===es?.id?(0,je.jsx)(q.OrderListsScreen,{rid:r,today:M,editor:!!B&&'staff'!==B.role&&!pe,who:{id:T,name:n.replace(' (example)','')}}):null,'phone'===es?.id?(0,je.jsx)(X.PhoneAlerts,{}):null,'suppliers'===es?.id?We?(0,je.jsx)(ce.Suppliers,{}):(0,je.jsx)(F.Muted,{children:"Your manager hasn\u2019t shared suppliers with staff."}):null,'privacy'===es?.id?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,i.privateClockVenue)(r)?(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(F.T,{size:14,children:"Location is checked only when you choose Clock in at the pub. Only a pass or fail is saved with the clock-in time, or an audited manager override."}),(0,je.jsx)(F.T,{size:14,children:"Your position, accuracy and distance are never saved. There are no location trails, background/arrival checks, clock-out checks or break checks."})]}):(0,je.jsxs)(je.Fragment,{children:[" ",(0,je.jsx)(F.T,{size:14,children:"\u2022 Location is checked when you tap Clock in, Clock out, Start break or End break, and (if you allowed location) while the app is open to ask if you want to clock in when you\u2019re at the venue but not on the rota. Never in the background."}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Each clock record keeps the location reading, how accurate it was, whether it was inside the venue area, and the time. Managers can see these."})]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 You see only your own hours, pay estimates and tips. Managers see the team\u2019s."}),(0,je.jsxs)(F.T,{size:14,children:["\u2022 Chat messages stay within ",e.name,"\u2019s team."]}),(0,je.jsx)(F.T,{size:14,children:"\u2022 Pay figures are estimates before tax and deductions; your payslip is the official record."})]}):null]}),(0,je.jsx)(le.BottomTabs,{background:(0,o.soutersSurface)('#0d0d0d'),active:os,onPress:e=>Ye(e),tabs:as.map(e=>({id:e.id,label:e.label,icon:e.icon,badge:'chat'===e.id&&Ue||'me'===e.id&&Ve&&Ue?{text:String(Ue),bg:$.colours.red}:null}))}),(0,je.jsx)(F.Sheet,{visible:De,onClose:()=>Ne(!1),title:"Signed in as",children:B?(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsxs)(F.Row,{gap:10,children:[(0,je.jsx)(ye.StaffAvatar,{id:B.id,size:48}),(0,je.jsxs)(_.default,{style:{flex:1},children:[(0,je.jsx)(F.T,{weight:"semibold",children:B.name}),(0,je.jsx)(F.Muted,{children:(0,re.levelJob)(B.level??'Staff',B.job)})]})]}),(0,je.jsx)(F.Muted,{children:"Signed in with your personal link. This phone remembers you."}),pe?(0,je.jsx)(F.Muted,{children:"Manager features are on for you in this app."}):null,'staff'===B.role||pe?null:(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Managers",onPress:()=>{const e=(0,re.appUrl)('owner');e&&window.location.assign(e)}}),B.id===we?(0,je.jsx)(F.Button,{kind:"secondary",label:"Back to CoverCharge for Head Chef",onPress:()=>{const e=(0,re.appUrl)('chef');e&&window.location.assign(e)}}):null]}):(0,je.jsxs)(_.default,{style:{gap:8},children:[(0,je.jsx)(F.Muted,{children:"Not signed in: this is a preview. Open your personal link, or paste it here, to sign in as yourself."}),(0,je.jsx)(ie.SignInWithLink,{})]})})]})}function Be({go:e}){const{rid:s,today:t}=(0,ee.useCtx)(3e4),o=(0,pe.useTravelDay)('staff',t);return(0,je.jsxs)(_.default,{style:{gap:10},children:[(0,je.jsx)(n.WhoBar,{}),(0,je.jsx)(pe.DayBar,{app:"staff",today:t}),o?null:(0,je.jsx)(r.CoversToday,{rid:s}),o?(0,je.jsx)(pe.DayView,{rid:s,day:o,today:t,app:"staff"}):(0,je.jsx)(fe.StaffHome,{go:e})]})}function Pe({rid:e,today:s,meId:t,me:o}){const i=(0,R.useCashAccess)(e=>e.mine),r=(0,R.useCashAccess)(e=>e.takings),l=(0,R.useCashAccess)(e=>e.tradingDate),n=(0,ke.useSync)(e=>e.perms),c=!1===r||null==r&&!n.includes('*')&&!n.includes('takings.view'),u=l??(0,B.tradingDay)();return(0,P.useEffect)(()=>{c&&(0,A.forgetPastTakings)(e,u)},[c,e,u]),!0!==i?(0,je.jsx)(M.NoCashUpAccess,{}):(0,je.jsx)(T.CashUpScreen,{rid:e,today:c?u:s,canEdit:!0,closer:c,who:{id:t??'me',name:o.replace(' (example)','')}})}},1414,[1415,1419,813,912,1072,1420,1203,1204,1028,1025,1026,1421,1423,1426,1153,891,978,1428,975,880,1031,1032,1429,914,1008,915,17,1155,1231,1235,1197,356,385,278,85,409,19,777,857,876,804,1161,1430,1066,1084,1086,1081,1027,1010,1057,1437,1438,1439,1447,1448,920,219,1236,1176,1183,1444,1196,1179,1453,1180,878,1206,1207,884,776,899,8]); __d(function(g,_r,i,_a,_m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.TablePlan=function({startStep:e}){const{rid:s,r:n,now:w,me:f,role:S}=(0,b.useCtx)(6e4),T=(0,x.usePlan)(s),[P,C]=(0,t.useState)(null),[D,I]=(0,t.useState)(T.areas[0]?.id??''),[M,B]=(0,t.useState)(null),N=T.areas.find(e=>e.id===D)??T.areas[0],O=(0,x.planCounts)(T),A=(0,p.closedAreasAt)((0,p.useBlocks)(e=>e.blocks),s,(0,y.ymd)(w),`${String(w.getHours()).padStart(2,'0')}:${String(w.getMinutes()).padStart(2,'0')}`);return(0,k.jsxs)(a.default,{style:{gap:12},testID:"tableplan-page",children:[(0,k.jsxs)(h.Muted,{children:["The table plan for ",n.name,". Each venue has its own plan; it drives the Display floor view, walk-ins and which tables online bookings can use."]}),(0,k.jsxs)(h.Card,{children:[(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},wrap:!0,gap:8,children:[(0,k.jsxs)(a.default,{children:[(0,k.jsxs)(h.T,{size:20,weight:"bold",colour:j.colours.gold,children:[O.tables," tables \xb7 ",O.seats," seats"]}),(0,k.jsxs)(h.Muted,{children:[T.areas.length," areas \xb7 ",T.joins.length," joined ",1===T.joins.length?"pair":"pairs"]})]}),(0,k.jsx)(h.Button,{label:"Open table plan designer",testID:"open-designer",onPress:()=>C(e??'arrange')})]}),v.RELEASE.planPhoto?(0,k.jsx)(m.PlanPhoto,{rid:s}):null,(0,k.jsx)(a.default,{style:{gap:6},children:T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return(0,k.jsxs)(a.default,{testID:`area-summary-${e.id}`,style:{width:'100%',minWidth:0,gap:8,alignItems:'stretch',borderTopWidth:1,borderTopColor:j.colours.border,paddingTop:12,paddingBottom:6},children:[(0,k.jsx)(h.T,{center:!0,weight:"semibold",colour:(0,j.brandColour)(e.colour),children:e.name}),e.dogs||e.outdoor?(0,k.jsxs)(h.Row,{wrap:!0,gap:8,style:{justifyContent:'center'},children:[e.dogs?(0,k.jsx)(h.Badge,{kind:"gold",label:"\ud83d\udc3e Dogs allowed"}):null,e.outdoor?(0,k.jsx)(h.Badge,{kind:A.has(e.id)?'red':'neutral',label:A.has(e.id)?'\ud83c\udf27 Closed for weather':'\ud83c\udf26 Outdoor'}):null]}):null,e.label?(0,k.jsx)(h.Muted,{center:!0,size:14,children:e.label}):null,(0,k.jsxs)(h.Muted,{center:!0,children:[s.tables," tables \xb7 ",s.seats," seats"]})]},e.id)})}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Areas",onPress:()=>C('areas')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Tables",onPress:()=>C('tables')}),(0,k.jsx)(h.Button,{small:!0,kind:"secondary",label:"Arrange",onPress:()=>C('arrange')})]})]}),T.areas.some(e=>e.outdoor)?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(h.T,{weight:"semibold",children:"Weather"}),(0,k.jsx)(h.Muted,{children:"Closes the outdoor areas for the rest of today: no online bookings or walk-ins there, and the Display shows them as closed. Uses Block bookings, so you can reopen in one tap."}),(0,k.jsx)(c.CloseGardenButton,{rid:s,r:n,now:w,by:f})]}):null,N?(0,k.jsxs)(h.Card,{children:[(0,k.jsx)(o.AreaTabs,{plan:T,area:N.id,onPick:I,closed:A,counts:Object.fromEntries(T.areas.map(e=>{const s=(0,x.planCounts)(T,e.id);return[e.id,`${s.tables} \xb7 ${s.seats}`]}))}),(0,k.jsx)(a.default,{pointerEvents:"none",style:{borderRadius:12,overflow:'hidden'},children:(0,k.jsx)(r.FloorCanvas,{plan:T,areaId:N.id,mode:"live",fit:"width",maxH:360,sectionColours:!0})}),(0,k.jsx)(h.Muted,{children:"Preview only. Open the designer to change it."})]}):null,M?(0,k.jsx)(h.Banner,{kind:"success",title:M}):null,(0,k.jsx)(l.default,{visible:!!P,animationType:"slide",onRequestClose:()=>C(null),presentationStyle:"fullScreen",children:(0,k.jsx)(a.default,{style:{flex:1,backgroundColor:j.colours.bg},children:P?(0,k.jsx)(u.PlanDesigner,{initial:T,venue:n.name,mode:"managers",role:S,startStep:P,onSave:e=>{x.useFloor.getState().setPlan(s,e),C(null),B('Table plan saved. The Display uses it straight away.')},onLiveChange:e=>{x.useFloor.getState().setPlan(s,e),B('Live seating plan updated on every screen.')},onCancel:()=>C(null)}):null})})]})},_e.DisplaySettingsPage=function(){const{rid:e,role:s}=(0,b.useCtx)(6e4),t=(0,x.useDisplaySettings)(e),n=s=>x.useFloor.getState().setSettings(e,s);return(0,k.jsxs)(a.default,{style:{gap:14},children:[(0,k.jsxs)(a.default,{style:{gap:6},testID:"privacy-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Privacy on the Display"}),'owner'===s?(0,k.jsx)(h.Toggle,{label:"Privacy mode (recommended)",value:t.privacy,onChange:e=>n({privacy:e})}):(0,k.jsxs)(h.Row,{style:{justifyContent:'space-between'},children:[(0,k.jsx)(h.T,{children:"Privacy mode"}),(0,k.jsxs)(h.T,{weight:"semibold",children:[t.privacy?'On':'Off'," \xb7 owner only"]})]}),(0,k.jsx)(h.Muted,{children:"On: guest surnames show as initials (Campbell \u2192 C.), and no phone numbers, emails, notes or allergy details appear on the main screen (an icon only). Staff tap for details in a panel that closes after 20 seconds."})]}),(0,k.jsxs)(a.default,{style:{gap:6},children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Screensaver"}),(0,k.jsx)(h.T,{size:14,children:"Start after nobody touches the Display for"}),(0,k.jsx)(h.Row,{gap:6,children:[1,2,5,10].map(e=>(0,k.jsx)(a.default,{testID:`idle-${e}`,children:(0,k.jsx)(h.Chip,{label:`${e} min`,selected:t.idleMins===e,onPress:()=>n({idleMins:e})})},e))}),(0,k.jsx)(h.Toggle,{label:"Ask for a staff PIN on wake",value:t.pinOn,onChange:e=>n({pinOn:e})}),t.pinOn?(0,k.jsx)(S,{rid:e}):null,(0,k.jsx)(h.Muted,{children:"Used on this Display until a screensaver is saved in Settings \u203a Display screensaver (style, idle time and night dim for every Display, changed live). Any touch wakes it straight away and that first touch doesn\u2019t press anything. Where the browser allows, the Display also asks to keep the screen on."})]}),(0,k.jsx)(T,{}),(0,k.jsxs)(a.default,{style:{gap:6},testID:"wipe-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Shared tablet or phone"}),(0,k.jsx)(h.Muted,{children:"Selling or handing over this device, or it was used by someone who has left? Sign out and wipe it."}),(0,k.jsx)(f.WipeDevice,{})]}),(0,k.jsx)(h.Banner,{kind:"info",title:"Settings live on this device",children:"They\u2019re saved in this browser for the venue and picked up by the Display app on the same device."})]})};var s=_r(d[0]),t=_r(d[1]),n=_r(d[2]),l=e(_r(d[3])),a=e(_r(d[4])),o=_r(d[5]),r=_r(d[6]),u=_r(d[7]),c=_r(d[8]),h=_r(d[9]),p=_r(d[10]),x=_r(d[11]),y=_r(d[12]),j=_r(d[13]),b=_r(d[14]),w=_r(d[15]),f=_r(d[16]),m=_r(d[17]),v=_r(d[18]),k=_r(d[19]);function S({rid:e}){const n=(0,x.useDisplaySettings)(e),[l,o]=(0,t.useState)(''),[r,u]=(0,t.useState)(''),[c,p]=(0,t.useState)(null),y=l?(0,w.wakePinProblem)(l):null,b=[h.styles.input,{width:130}];return(0,k.jsxs)(a.default,{style:{gap:6},testID:"wake-pin-setting",children:[n.pinDefault?(0,k.jsx)(a.default,{testID:"wake-pin-default",children:(0,k.jsx)(h.Banner,{kind:"warn",title:"Change the wake PIN",children:"This Display still uses the starting PIN, 2580, which anyone could guess. Set a new 6 to 8 digit PIN below."})}):(0,k.jsxs)(h.Muted,{children:["A wake PIN of ",n.pinLen," digits is set. Type a new one to change it."]}),(0,k.jsxs)(h.Row,{gap:8,wrap:!0,children:[(0,k.jsx)(s.TextInput,{testID:"wake-pin-new",accessibilityLabel:"New wake PIN",value:l,onChangeText:e=>{o(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"New PIN (6\u20138 digits)",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(s.TextInput,{testID:"wake-pin-again",accessibilityLabel:"New wake PIN again",value:r,onChangeText:e=>{u(e.replace(/\D/g,'').slice(0,8)),p(null)},placeholder:"Type it again",placeholderTextColor:j.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",style:b}),(0,k.jsx)(h.Button,{small:!0,testID:"wake-pin-save",label:"Save PIN",disabled:!l||!r,onPress:()=>{const s=(0,w.wakePinProblem)(l);s?p(s):l===r?(x.useFloor.getState().setSettings(e,(0,w.makeWakePin)(l)),o(''),u(''),p('Wake PIN saved. Tell the team in person; it isn\u2019t shown again.')):p('The two PINs don\u2019t match.')}})]}),c||y?(0,k.jsx)(h.Muted,{children:c??y}):null]})}function T(){const[e,s]=(0,t.useState)((0,n.flapSoundOn)());return(0,k.jsxs)(a.default,{style:{gap:6},testID:"flap-sound-setting",children:[(0,k.jsx)(h.T,{weight:"semibold",colour:j.colours.gold,children:"Covers counter sound"}),(0,k.jsx)(h.Toggle,{label:"Soft flap click when the Covers change (Display only)",value:e,onChange:e=>{(0,n.setFlapSound)(e),s(e)}}),(0,k.jsx)(h.Muted,{children:"Off by default. Only this device clicks; phones never do."})]})}},1415,[812,17,1018,378,85,1108,1109,1361,1394,777,995,998,863,804,1057,999,1416,1417,1020,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.WipeDevice=function({compact:e}){const f=(0,u.useDisplaySettings)(p.VENUE_RID),[v,T]=(0,s.useState)(!1),[w,j]=(0,s.useState)(''),[D,C]=(0,s.useState)(!1),I='display'===h.APP_VARIANT&&f.pinOn,P=!I||(0,b.wakePinMatches)(f,w);return v?(0,x.jsxs)(o.default,{testID:"wipe-confirm-box",style:{gap:6,marginTop:6},children:[(0,x.jsx)(l.T,{size:e?12:14,children:"Sign out and remove everything CoverCharge keeps on this device: sign-ins, pairing, saved screens and any changes not sent yet. The venue\u2019s shared data is not touched. To use it again, open a personal link or pair the Display again."}),I?(0,x.jsx)(t.TextInput,{testID:"wipe-pin",value:w,onChangeText:j,placeholder:"Display wake PIN",placeholderTextColor:c.colours.muted,secureTextEntry:!0,keyboardType:"number-pad",accessibilityLabel:"Display wake PIN",style:{borderWidth:1,borderColor:'rgba(255,255,255,0.2)',borderRadius:8,paddingHorizontal:10,paddingVertical:6,color:c.colours.text}}):null,(0,x.jsxs)(o.default,{style:{flexDirection:'row',gap:8},children:[(0,x.jsx)(n.default,{testID:"wipe-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, wipe this device",disabled:!P||D,onPress:()=>{C(!0),(0,y.wipeThisDevice)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:P?c.colours.red:'rgba(255,255,255,0.08)'},children:(0,x.jsx)(l.T,{size:12,weight:"semibold",children:D?'Wiping\u2026':'Yes, wipe this device'})}),(0,x.jsx)(n.default,{accessibilityRole:"button",accessibilityLabel:"Cancel",onPress:()=>{T(!1),j('')},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,x.jsx)(l.T,{size:12,children:"Cancel"})})]})]}):(0,x.jsx)(n.default,{testID:"wipe-device",accessibilityRole:"button",accessibilityLabel:"Sign out and wipe this device",onPress:()=>T(!0),style:{alignSelf:'flex-start',marginTop:e?4:0,minHeight:44,justifyContent:'center'},children:(0,x.jsx)(l.T,{size:e?12:14,colour:c.colours.gold,children:"Sign out and wipe this device\u2026"})})};var t=r(d[0]),s=r(d[1]),n=e(r(d[2])),o=e(r(d[3])),l=r(d[4]),c=r(d[5]),u=r(d[6]),p=r(d[7]),b=r(d[8]),h=r(d[9]),y=r(d[10]),x=r(d[11])},1416,[812,17,385,85,777,804,998,805,999,856,899,8]); __d(function(g,r,_i,_a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.PlanPhoto=function({rid:e}){const t=(0,n.usePlan)(e),b=(0,n.useFloor)(e=>e.setPlan),[y,f]=(0,a.useState)(null),[x,w]=(0,a.useState)(null),[v,j]=(0,a.useState)(null),[k,S]=(0,a.useState)(''),[P,T]=(0,a.useState)(!1),I=async e=>{let a;T(!0);try{const{data:t,error:l}=await(0,u.getSupabase)().functions.invoke('plan-photo-read',{body:{image:e}});a=l?{ok:!1,message:'The plan could not be read. The photo is still here.'}:{ok:!0,tables:(0,o.cleanFindings)(t)}}catch{a={ok:!1,message:'The plan could not be read. The photo is still here.'}}finally{T(!1)}const t=(0,o.planReadAfter)(e,a);w(t.photo),f(t.rows&&t.rows.length?t.rows:null),S(t.note)},L=async()=>{S('');const e=(await(0,c.pickPhotos)({source:'camera'}))[0];e?(w(e),await I(e)):S('No photo taken.')};return(0,p.jsxs)(l.default,{testID:"plan-photo",style:{width:'100%',alignItems:'center',gap:10},children:[(0,p.jsx)(s.Button,{testID:"plan-photo-camera",label:P?'Reading the plan\u2026':'Take a picture of the table plan',accessibilityLabel:"Take a picture of a hand-drawn table plan",disabled:P,onPress:()=>{L()}}),k?(0,p.jsx)(s.Muted,{center:!0,testID:"plan-photo-note",children:k}):null,x&&!P?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-retry",label:"Read this photo again",accessibilityLabel:"Read this photo again",onPress:()=>{I(x)}}):null,y?(0,p.jsx)(l.default,{testID:"plan-photo-review",style:{width:'100%'},children:(0,p.jsxs)(s.Card,{style:{alignItems:'center',width:'100%'},children:[(0,p.jsx)(s.T,{center:!0,weight:"bold",colour:h.colours.gold,children:"Check what was read"}),(0,p.jsx)(s.Muted,{center:!0,children:"Nothing is saved until you tap Save the plan."}),y.map((e,a)=>(0,p.jsxs)(l.default,{style:{width:'100%',gap:6},children:[(0,p.jsx)(s.Field,{label:"Area",accessibilityLabel:`Area ${a+1}`,value:e.area,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,area:e}:t))}),(0,p.jsx)(s.Field,{label:"Table",accessibilityLabel:`Table ${a+1}`,value:e.name,onChangeText:e=>f(y.map((t,l)=>l===a?{...t,name:e}:t))}),(0,p.jsx)(s.Field,{label:"Seats",accessibilityLabel:`Seats at table ${a+1}`,value:String(e.seats),keyboardType:"number-pad",onChangeText:e=>f(y.map((t,l)=>l===a?{...t,seats:Math.max(1,Math.min(30,Number(e.replace(/\D/g,''))||1))}:t))}),(0,p.jsx)(s.Button,{kind:"ghost",label:`Remove ${e.name||'table'}`,accessibilityLabel:`Remove ${e.name||'table'}`,onPress:()=>f(y.filter((e,t)=>t!==a))})]},`${e.area}-${e.name}-${a}`)),(0,p.jsx)(s.Button,{testID:"plan-photo-save",label:"Save the plan",accessibilityLabel:"Save the checked table plan",disabled:!y.length,onPress:()=>{if(!y?.length)return;j(t);const a=[...t.areas],l=[...t.tables];for(const e of y){let t=a.find(a=>a.name.toLowerCase()===e.area.toLowerCase());t||(t={id:(0,i.fid)('area'),name:e.area},a.push(t));const s=(0,i.sizeFor)(e.seats),n=l.filter(e=>e.areaId===t.id).length;l.push({id:(0,i.fid)('t'),name:e.name,areaId:t.id,shape:s.shape,minSeats:1,maxSeats:e.seats,x:40+n%6*140,y:40+120*Math.floor(n/6),w:s.w,h:s.h,rot:0,online:!0})}b(e,{...t,areas:a,tables:l}),f(null),S('Plan saved. Undo puts the previous plan back.')}})]})}):null,v?(0,p.jsx)(s.Button,{kind:"ghost",testID:"plan-photo-undo",label:"Undo table plan",accessibilityLabel:"Undo the table plan and restore the previous one",onPress:()=>{b(e,v),j(null),S('Previous plan restored.')}}):null]})};var e,a=r(d[0]),t=r(d[1]),l=(e=t)&&e.__esModule?e:{default:e},s=r(d[2]),n=r(d[3]),o=r(d[4]),i=r(d[5]),h=r(d[6]),c=r(d[7]),u=r(d[8]),p=r(d[9])},1417,[17,85,777,998,1418,842,804,1038,928,8]); @@ -1570,7 +1570,7 @@ __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{v __d(function(g,_r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.CarGate=function(){const e=(0,u.useSync)(e=>'device'===e.kind&&!!e.venueId),s=(0,u.useSync)(e=>e.mode),[o,l]=(0,t.useState)(c.useSession.persist.hasHydrated()),[x,b]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{h.PITCH&&(globalThis.__pitchCarBoot=e=>b(!!e))},[]),(0,t.useEffect)(()=>{const e=c.useSession.persist.onFinishHydration(()=>l(!0));return c.useSession.persist.hasHydrated()&&l(!0),e},[]),o?h.PITCH&&x?(0,p.jsx)(T,{}):h.PITCH||e?null:s&&'connecting'!==s?(0,p.jsx)(I,{}):(0,p.jsx)(T,{}):(0,p.jsx)(r.default,{style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3}]})};var t=_r(d[0]),n=e(_r(d[1])),r=e(_r(d[2])),s=e(_r(d[3])),o=_r(d[4]),l=_r(d[5]),c=_r(d[6]),u=_r(d[7]),h=_r(d[8]),x=_r(d[9]),y=_r(d[10]),b=_r(d[11]),f=_r(d[12]),p=_r(d[13]);let j=null,w=null;async function C(e){return!e&&w&&Date.now()-w.at<6e4&&new Date(w.r.expiresAt).getTime()-Date.now()>12e4?w.r:j||(j=(0,u.carPairStart)().then(e=>(e.ok&&(w={r:e,at:Date.now()}),e)).finally(()=>{j=null}),j)}function I(){const{width:e,height:c}=(0,s.default)(),[h,j]=(0,t.useState)(null),[w,I]=(0,t.useState)('starting'),[T,k]=(0,t.useState)(''),[D,M]=(0,t.useState)(0),S=(0,t.useRef)(!1),z=(0,t.useCallback)(async(e=!0)=>{if(S.current)return;S.current=!0,I('starting'),k('');const t=await C(e);if(S.current=!1,!t.ok)return I('error'),void k(t.error);j({id:t.requestId,code:t.code,until:new Date(t.expiresAt).getTime()}),I('waiting')},[]);(0,t.useEffect)(()=>{z(!1)},[]),(0,t.useEffect)(()=>{if(!h||'waiting'!==w)return;const e=setInterval(async()=>{M(Math.max(0,Math.round((h.until-Date.now())/1e3)));('expired'===await(0,u.carPairPoll)(h.id)||Date.now()>h.until)&&I('expired')},3e3);return()=>clearInterval(e)},[h,w]);const P=Math.min(120,Math.max(64,Math.round(Math.min(e/9,c/7)))),R=h?.code??'',H=R?`${R.slice(0,3)} ${R.slice(3)}`:'\xb7\xb7\xb7 \xb7\xb7\xb7';return(0,p.jsx)(r.default,{testID:"car-pairing",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24}],children:(0,p.jsxs)(r.default,{style:{width:'100%',maxWidth:880,alignItems:'center',gap:c<820?10:16},children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:c<820?64:88}),(0,p.jsx)(o.T,{center:!0,size:28,weight:"semibold",accessibilityRole:"header",children:"The Anchorage \xb7 car screen"}),(0,p.jsx)(f.ParkedOnly,{}),'waiting'===w||'starting'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:18,colour:y.colours.muted,children:"Pair this car from your phone"}),(0,p.jsx)(r.default,{testID:"car-code",accessible:!0,accessibilityLabel:R?`Car code ${(0,b.spokenCode)(R)}`:'Making a code',accessibilityLiveRegion:"polite",style:{paddingHorizontal:32,paddingVertical:10,borderRadius:20,borderWidth:1.5,borderColor:y.colours.gold,backgroundColor:'rgba(201,162,74,0.10)'},children:(0,p.jsx)(o.T,{center:!0,size:P,weight:"bold",colour:y.colours.goldLight,style:{letterSpacing:P/8,lineHeight:1.2*P},children:H})}),R?(0,p.jsx)(o.Muted,{center:!0,children:`This code works for ${Math.max(1,Math.ceil((D||600)/60))} more minute${1===Math.ceil((D||600)/60)?'':'s'}.`}):null,(0,p.jsxs)(r.default,{testID:"car-steps",style:{gap:4,alignItems:'center'},children:[(0,p.jsx)(o.T,{center:!0,size:18,children:"1. On your phone, open CoverCharge for Managers."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"2. Go to More, then Car screen."}),(0,p.jsx)(o.T,{center:!0,size:18,children:"3. Type these 6 numbers and tap Approve. Only an owner can do this."})]}),(0,p.jsx)(r.default,{style:{flexDirection:'row',gap:12,flexWrap:'wrap',justifyContent:'center'},children:(0,p.jsx)(o.Button,{testID:"car-new-code",kind:"secondary",label:"New code",onPress:()=>{z()},style:{minHeight:64,minWidth:200}})})]}):'expired'===w?(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:22,weight:"semibold",colour:y.colours.goldLight,children:"That code has run out"}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Make a new code",onPress:()=>{z()},style:{minHeight:64,minWidth:280}})]}):(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(o.T,{center:!0,size:20,weight:"semibold",colour:y.colours.amber,children:"Couldn\u2019t make a code"}),(0,p.jsx)(o.Muted,{center:!0,children:T}),(0,p.jsx)(o.Button,{testID:"car-new-code",label:"Try again",onPress:()=>{z()},style:{minHeight:64,minWidth:240}})]}),T&&'error'!==w?(0,p.jsx)(o.T,{center:!0,colour:y.colours.amber,children:T}):null,(0,p.jsx)(o.Muted,{center:!0,style:{maxWidth:640},children:"Don\u2019t open your personal app link in the car: it stays on your phone. Use this screen only when the car is in Park."})]})})}function T(){const[e,s]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{const e=setTimeout(()=>s(!0),15e3);return()=>clearTimeout(e)},[]),(0,p.jsxs)(r.default,{testID:"car-boot",style:[n.default.absoluteFill,{backgroundColor:y.colours.bg,zIndex:1e3,alignItems:'center',justifyContent:'center',padding:24,gap:16}],children:[(0,p.jsx)(l.RestaurantLogo,{rid:x.VENUE_RID,size:72}),(0,p.jsxs)(r.default,{accessible:!0,accessibilityRole:'alert',accessibilityLiveRegion:"polite",accessibilityLabel:e?'Still connecting. Check the car has mobile data or Wi-Fi, or tap Reload.':'The Anchorage car screen. Connecting\u2026',children:[(0,p.jsx)(o.T,{center:!0,size:24,weight:"semibold",children:e?'Still connecting\u2026':'Connecting\u2026'}),e?(0,p.jsx)(o.Muted,{center:!0,children:"Check the car has mobile data or Wi-Fi, or tap Reload."}):null]}),e?(0,p.jsx)(o.Button,{testID:"car-boot-reload",label:"Reload",onPress:()=>{try{location.reload()}catch{}},style:{minHeight:64,minWidth:220}}):null]})}},1487,[17,24,85,409,777,857,920,899,880,805,804,1488,1489,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"CAR_BUTTONS",{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,"MENU_BUTTON",{enumerable:!0,get:function(){return l}}),e.menuSizes=function(o,l){const s=Math.round(Math.max(300,Math.min(o-24,o>=1600?520:o>=1200?460:420))),t=Math.floor((s-40-2)/3),n=Math.floor(Math.max(84,(l-72-40)/4)),c=l>=1e3?15:13,b=Math.round(1.4*c),h=Math.max(52,Math.min(76,n-b-18,t-28));return{panelW:s,colW:t,per:n,circle:h,label:c,lineH:b,icon:Math.round(.44*h),cols:3,rows:4,head:72,pad:20}},Object.defineProperty(e,"spokenCode",{enumerable:!0,get:function(){return s}});const o=[{id:'rota',label:'Rota',short:'Rota',icon:'rota',pages:[{id:'rota',label:'Rota'}]},{id:'signoff',label:'Sign off hours',short:'Sign off',icon:'signoff',pages:[{id:'signoff',label:'Sign off hours'},{id:'timesheets',label:'Timesheets'}]},{id:'menu',label:'Menu & sold out',short:'Menu',icon:'menu',pages:[{id:'soldout',label:'Sold out'},{id:'menu',label:'Menu & allergens'},{id:'tableqr',label:'Table QR codes'}]},{id:'bookings',label:'Bookings',short:'Bookings',icon:'bookings',pages:[{id:'@bookings',label:'Bookings'},{id:'lookback',label:'Look back'}]},{id:'noshows',label:'No-shows',short:'No-shows',icon:'noshow',pages:[{id:'@noshows',label:'No-shows'}]},{id:'chat',label:'Staff chat',short:'Chat',icon:'chat',pages:[{id:'@chat',label:'Staff chat'}]},{id:'stock',label:'Stock & suppliers',short:'Stock',icon:'stock',pages:[{id:'kitchencosts',label:'Deliveries & GP'},{id:'trackedstock',label:'Tracked stock'},{id:'orderlists',label:'Order lists'},{id:'suppliers',label:'Suppliers'}]},{id:'loyalty',label:'Loyalty',short:'Loyalty',icon:'loyalty',pages:[{id:'loyalty',label:'Stamp card'}]},{id:'takings',label:'Takings & tips',short:'Takings',icon:'takings',pages:[{id:'cashup',label:'Cash up & sales'},{id:'tips',label:'Tips'},{id:'spendhead',label:'Spend per head'}]},{id:'safety',label:'Food safety',short:'Safety',icon:'safety',pages:[{id:'haccp',label:'CookSafe log'}]},{id:'reviews',label:'Reviews',short:'Reviews',icon:'reviews',pages:[{id:'reviews',label:'Reviews'}]}],l=56;const s=o=>o.split('').join(' ')},1488,[]); __d(function(g,r,i,a,m,_e,d){"use strict";Object.defineProperty(_e,'__esModule',{value:!0}),_e.ParkedOnly=function({small:e}){return(0,s.jsx)(n.default,{testID:"parked-only",accessible:!0,accessibilityLabel:"Parked only. Use this screen only when the car is in Park.",style:{minHeight:e?28:36,paddingHorizontal:e?8:12,borderRadius:999,borderWidth:1,borderColor:t.colours.amber,backgroundColor:'rgba(232,168,56,0.12)',alignItems:'center',justifyContent:'center',flexShrink:0},children:(0,s.jsx)(o.T,{size:e?11:13,weight:"semibold",colour:t.colours.amber,center:!0,children:"PARKED ONLY"})})},r(d[0]);var e,l=r(d[1]),n=(e=l)&&e.__esModule?e:{default:e},o=r(d[2]),t=r(d[3]),s=r(d[4])},1489,[17,85,777,804,8]); -__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return l}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),n=_r(d[3]);const o=()=>{const c=n.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId};function t(c){if(o()&&!(0,n.can)(c))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':'Only the head chef, managers and owners can change recipe cards.')}const l={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.create(c,s,n)),update:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.update(c,s,n)),signOff:async(c,s)=>(t('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,n)=>{t('recipes.edit');const o=await r.localRecipeCards.remove(s,n);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,n)=>(t('recipes.edit'),r.localRecipeCards.savePhoto(c,s,n)),photoSource:c=>r.localRecipeCards.photoSource(c)};function p(){const c=o()?l:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}p(),n.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||p()})},1490,[905,868,867,899]); +__d(function(g,_r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),Object.defineProperty(e,"sharedRecipeCards",{enumerable:!0,get:function(){return p}});var c=_r(d[0]),r=_r(d[1]),s=_r(d[2]),t=_r(d[3]);const o=()=>{const c=t.useSync.getState();return'live'===c.mode&&'guest'!==c.kind&&!!c.venueId},n=c=>(0,t.can)('recipes.create_own')&&(!c||!!c.authorRef&&c.authorRef===t.useSync.getState().staffRef);function l(c,r){if(o()&&!((0,t.can)(c)||'recipes.edit'===c&&n(r)))throw new Error('recipes.signoff'===c?'Only the Head Chef, an owner or a manager can sign off a recipe card.':(0,t.can)('recipes.create_own')?'You can only change recipe cards you created.':'Only the head chef, managers and owners can change recipe cards.')}const p={mode:'shared',list:c=>r.localRecipeCards.list(c),get:c=>r.localRecipeCards.get(c),byMenuItem:c=>r.localRecipeCards.byMenuItem(c),subscribe:c=>r.localRecipeCards.subscribe(c),create:async(c,s,t)=>(l('recipes.edit'),r.localRecipeCards.create(c,s,t)),update:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(c)),r.localRecipeCards.update(c,s,t)),signOff:async(c,s)=>(l('recipes.signoff'),r.localRecipeCards.signOff(c,s)),remove:async(s,t)=>{l('recipes.edit',r.localRecipeCards.get(s));const o=await r.localRecipeCards.remove(s,t);return c.useGpCalc.getState().removeCardCost(s),o},savePhoto:async(c,s,t)=>(l('recipes.edit',r.localRecipeCards.get(s)),r.localRecipeCards.savePhoto(c,s,t)),photoSource:c=>r.localRecipeCards.photoSource(c)};function u(){const c=o()?p:r.localRecipeCards;(0,s.recipeCards)()!==c&&(0,s.setRecipeCardRepository)(c)}u(),t.useSync.subscribe((c,r)=>{c.mode===r.mode&&c.kind===r.kind&&c.venueId===r.venueId||u()})},1490,[905,868,867,899]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),Object.defineProperty(_e,"STRIP",{enumerable:!0,get:function(){return C}}),Object.defineProperty(_e,"SYNC_CONNECTED_GREEN",{enumerable:!0,get:function(){return I}}),_e.syncTone=S,Object.defineProperty(_e,"syncToneColour",{enumerable:!0,get:function(){return D}}),Object.defineProperty(_e,"syncToneSpoken",{enumerable:!0,get:function(){return R}}),_e.SyncBadge=function(){const e=(0,h.useSync)(),[I,k]=(0,s.useState)(!1),[A,$]=(0,s.useState)(e.refused?.at??''),P=e.refused&&e.refused.at!==A?e.refused:void 0,z=(0,p.useScreensaverAsleep)(e=>e.asleep),[W,L]=(0,s.useState)(()=>Date.now());(0,s.useEffect)(()=>{const e=setInterval(()=>L(Date.now()),5e3);return()=>clearInterval(e)},[]);const N='off'===e.mode&&(x.PITCH||!(0,v.isSupabaseConfigured)());if('customer'===u.APP_VARIANT||'off'===e.mode&&!N)return null;if(z)return(0,w.jsx)(c.default,{testID:"sync-strip-asleep",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:{height:C,backgroundColor:f.colours.bg}});const O=!N&&!!e.venueId&&('live'===e.mode||'offline'===e.mode)&&(e.lastServerAt?(0,o.syncStale)(e.lastServerAt,W):'offline'===e.mode),H=e.lastServerAt?new Date(e.lastServerAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}):'',_='live'===e.mode&&!O,E=e.waiting??0,B=`${E} change${1===E?'':'s'} waiting to save`,G=O?'Out of sync':N?x.PITCH?'Demo \xb7 this device only':'This device only':_?E?B:e.pending?`Live \xb7 sending ${e.pending}`:'Live':'offline'===e.mode?"Offline"+(e.pending?` \xb7 ${e.pending} waiting`:''):'connecting'===e.mode?'Connecting\u2026':'unpaired'===e.mode?'Not paired':'On this device',M=O?'disconnected':S(e.mode,N,E),F=D(M),V=O?`Out of sync: nothing from the shared system since ${H||'this app opened'}. Reconnecting by itself; changes made here are kept and sent when it is back.`:N?x.PITCH?'Demo mode. Nothing is shared or sent: everything you do stays in this browser.':'This copy isn\u2019t connected to a shared system. Everything stays on this device.':_?`Shared live with ${e.venueName??'your venue'}${e.lastSyncAt?`. Last update ${new Date(e.lastSyncAt).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'})}`:''}.`:'offline'===e.mode?'No connection. Changes are saved on this device and sent when you\u2019re back online.':'signin'===e.mode?'Not connected to the shared system. Open your personal invite link once on this device to connect.':'unpaired'===e.mode?'This display isn\u2019t paired. Use a pairing code from Managers \u2192 Displays.':'connecting'===e.mode?'Connecting to the shared system\u2026':'The shared system can\u2019t be reached, so this device is using its own data.';return(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(c.default,{testID:"sync-strip",style:{height:C,paddingHorizontal:10,flexDirection:'row',gap:10,alignItems:'center',justifyContent:'flex-start',backgroundColor:f.colours.bg,borderTopWidth:1,borderTopColor:'rgba(255,255,255,0.06)'},children:[(0,w.jsxs)(l.default,{testID:"sync-badge",accessibilityRole:"button",accessibilityLabel:E&&_?`${B}, ${R(M)}. Kept on this device and tried again by itself. Tap for details.`:`${G}, ${R(M)}. Tap for details.`,accessibilityLiveRegion:"polite",onPress:()=>k(e=>!e),style:{flexDirection:'row',alignItems:'center',gap:6,paddingHorizontal:14,minHeight:44,borderRadius:999,backgroundColor:(0,t.soutersSurface)('rgba(16,14,11,0.92)'),borderWidth:1,borderColor:`${F}80`,maxWidth:320},children:[(0,w.jsx)(c.default,{testID:"sync-dot",style:{width:10,height:10,borderRadius:5,backgroundColor:F}}),(0,w.jsx)(b.T,{size:12,weight:"semibold",children:G})]}),O?(0,w.jsx)(c.default,{testID:"sync-out-banner",accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{flexShrink:1,flexDirection:'row',alignItems:'center',gap:8,paddingHorizontal:14,minHeight:40,borderRadius:10,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red},children:(0,w.jsx)(b.T,{size:13,weight:"semibold",numberOfLines:1,children:"Out of sync, reconnecting\u2026"+(H?` Last synced ${H}`:'')})}):null]}),I?(0,w.jsxs)(c.default,{testID:"sync-detail",style:{position:'absolute',left:10,bottom:52,zIndex:900,maxWidth:320,padding:12,borderRadius:12,backgroundColor:(0,t.soutersSurface)('#15120E'),borderWidth:1,borderColor:'rgba(255,255,255,0.14)',gap:4},children:[(0,w.jsx)(b.T,{size:13,children:V}),E?(0,w.jsxs)(c.default,{testID:"sync-waiting",style:{gap:4},children:[(0,w.jsxs)(b.T,{size:12,colour:f.colours.gold,children:[B,". ",1===E?'It is':'They are'," kept on this device and tried again by ",1===E?'itself':'themselves'," until the shared system takes ",1===E?'it':'them',".",e.waitingWhat?` Waiting: ${e.waitingWhat}.`:'']}),(0,w.jsx)(l.default,{testID:"sync-retry",accessibilityRole:"button",accessibilityLabel:"Try saving again now",onPress:()=>{y.mutationQueue.retryNow()},style:{minHeight:44,justifyContent:'center',alignSelf:'flex-start',paddingHorizontal:12,borderRadius:8,borderWidth:1,borderColor:f.colours.gold},children:(0,w.jsx)(b.T,{size:12,colour:f.colours.gold,children:"Try again now"})})]}):null,e.refused?(0,w.jsxs)(b.T,{size:12,colour:f.colours.red,children:["Last change not saved: ",e.refused.what,". ",e.refused.why,"."]}):null,e.message?(0,w.jsx)(b.T,{size:12,colour:f.colours.muted,children:e.message}):null,(0,w.jsx)(T.SyncDeviceActions,{})]}):null,P?(0,w.jsx)(c.default,{testID:"sync-toast",style:{position:'absolute',left:16,right:16,bottom:C+j+8,zIndex:950,alignItems:'center'},pointerEvents:"box-none",children:(0,w.jsxs)(c.default,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:{padding:12,borderRadius:12,backgroundColor:'#3A1712',borderWidth:1,borderColor:f.colours.red,maxWidth:460,gap:8},children:[(0,w.jsx)(b.T,{size:13,children:`Not saved: ${P.what}. Why: ${P.why}. This device now shows what the shared system has, so please make the change again if it is still needed.`}),(0,w.jsx)(n.ToastClose,{testID:"sync-toast-ok",label:"Close this message",onPress:()=>$(P.at),style:{minHeight:44,minWidth:44,alignSelf:'flex-end'}})]})}):null]})};var t=r(d[0]),n=r(d[1]),s=r(d[2]),o=r(d[3]),l=e(r(d[4])),c=e(r(d[5])),u=r(d[6]),h=r(d[7]),y=r(d[8]),f=r(d[9]),b=r(d[10]),p=r(d[11]),v=r(d[12]),x=r(d[13]),T=r(d[14]),w=r(d[15]);const C=48,j='display'===u.APP_VARIANT?0:57,I='#3DD68C';function S(e,t,n){return t?'disconnected':'live'===e?n?'pending':'connected':'connecting'===e?'pending':'disconnected'}const D=e=>'connected'===e?I:'pending'===e?f.colours.amber:f.colours.red,R=e=>'connected'===e?'connected':'pending'===e?'not connected yet':'not connected'},1491,[813,779,17,974,385,85,856,899,976,804,777,1346,971,880,1492,8]); __d(function(g,r,i,a,m,_e,d){"use strict";function e(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(_e,'__esModule',{value:!0}),_e.SyncDeviceActions=function(){const e=(0,o.useSync)(),[f,p]=(0,s.useState)(!1),h='live'===e.mode||'offline'===e.mode;return e.venueId&&h?(0,b.jsxs)(b.Fragment,{children:[f?(0,b.jsxs)(c.default,{style:{gap:6,marginTop:6},children:[(0,b.jsx)(u.T,{size:12,children:"Disconnect this device? Your changes stay on it; open your personal invite link to connect again."}),(0,b.jsxs)(c.default,{style:{flexDirection:'row',gap:8},children:[(0,b.jsx)(t.default,{testID:"unpair-confirm",accessibilityRole:"button",accessibilityLabel:"Yes, disconnect",onPress:()=>{p(!1),(0,o.disconnectStaff)()},style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,backgroundColor:l.colours.red},children:(0,b.jsx)(u.T,{size:12,weight:"semibold",children:"Yes, disconnect"})}),(0,b.jsx)(t.default,{accessibilityRole:"button",accessibilityLabel:"Keep connected",onPress:()=>p(!1),style:{paddingHorizontal:12,paddingVertical:6,borderRadius:8,borderWidth:1,borderColor:'rgba(255,255,255,0.2)'},children:(0,b.jsx)(u.T,{size:12,children:"Keep"})})]})]}):(0,b.jsx)(t.default,{testID:"unpair",accessibilityRole:"button",accessibilityLabel:"Disconnect this device",onPress:()=>p(!0),style:{marginTop:6,alignSelf:'flex-start'},children:(0,b.jsx)(u.T,{size:12,colour:l.colours.gold,children:"Disconnect this device\u2026"})}),(0,b.jsx)(n.WipeDevice,{compact:!0})]}):null};var s=r(d[0]),n=r(d[1]),t=e(r(d[2])),c=e(r(d[3])),o=r(d[4]),l=r(d[5]),u=r(d[6]),b=r(d[7])},1492,[17,1416,385,85,899,804,777,8]); __d(function(g,r,i,a,m,e,d){"use strict";Object.defineProperty(e,'__esModule',{value:!0}),e.seedPitch=function(){}},1493,[]); diff --git a/staff-app/admin.html b/staff-app/admin.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/admin.html +++ b/staff-app/admin.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer.html b/staff-app/customer.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer.html +++ b/staff-app/customer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage.html b/staff-app/customer/anchorage.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage.html +++ b/staff-app/customer/anchorage.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/book.html b/staff-app/customer/anchorage/book.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/book.html +++ b/staff-app/customer/anchorage/book.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/feedback.html b/staff-app/customer/anchorage/feedback.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/feedback.html +++ b/staff-app/customer/anchorage/feedback.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/gift.html b/staff-app/customer/anchorage/gift.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/gift.html +++ b/staff-app/customer/anchorage/gift.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/lost.html b/staff-app/customer/anchorage/lost.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/lost.html +++ b/staff-app/customer/anchorage/lost.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/loyalty.html b/staff-app/customer/anchorage/loyalty.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/loyalty.html +++ b/staff-app/customer/anchorage/loyalty.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/merch.html b/staff-app/customer/anchorage/merch.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/merch.html +++ b/staff-app/customer/anchorage/merch.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/offers.html b/staff-app/customer/anchorage/offers.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/offers.html +++ b/staff-app/customer/anchorage/offers.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/refer.html b/staff-app/customer/anchorage/refer.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/refer.html +++ b/staff-app/customer/anchorage/refer.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/waitlist.html b/staff-app/customer/anchorage/waitlist.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/waitlist.html +++ b/staff-app/customer/anchorage/waitlist.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/anchorage/whatson.html b/staff-app/customer/anchorage/whatson.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/anchorage/whatson.html +++ b/staff-app/customer/anchorage/whatson.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/basket.html b/staff-app/customer/basket.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/basket.html +++ b/staff-app/customer/basket.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/customer/profile.html b/staff-app/customer/profile.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/customer/profile.html +++ b/staff-app/customer/profile.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/demo.html b/staff-app/demo.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/demo.html +++ b/staff-app/demo.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/display.html b/staff-app/display.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/display.html +++ b/staff-app/display.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/index.html b/staff-app/index.html index 3d80c927654517dfd8d108cd2081a40e1701c6cb..73ca5f615af099bd0912b88afbb1a32f45c1c7b2 100644 --- a/staff-app/index.html +++ b/staff-app/index.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/kitchen.html b/staff-app/kitchen.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/kitchen.html +++ b/staff-app/kitchen.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/owner.html b/staff-app/owner.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/owner.html +++ b/staff-app/owner.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/staff.html b/staff-app/staff.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/staff.html +++ b/staff-app/staff.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - + diff --git a/staff-app/sw.js b/staff-app/sw.js index 340f757954e93b956c4d80346f8ca666686f9b26..e9798c91bda256c16252c051bb5c12b86c0cb7a2 100644 --- a/staff-app/sw.js +++ b/staff-app/sw.js @@ -1,7 +1,7 @@ // Anchorage Staff service worker: precache the app shell so it opens offline after the first visit. -const V = "cc-staff-fe4652eb24"; +const V = "cc-staff-9ef8caeb3d"; const BASE = "/staff-app/"; -const PRECACHE = ["/staff-app/apple-touch-icon.png", "/staff-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/staff-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/staff-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/staff-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/staff-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/staff-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/staff-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/staff-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/staff-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/staff-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/staff-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/staff-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/staff-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/staff-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/staff-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/staff-app/brand-logo.png", "/staff-app/favicon.ico", "/staff-app/icon-192.png", "/staff-app/icon-512.png", "/staff-app/icon-maskable-192.png", "/staff-app/icon-maskable-512.png", "/staff-app/manifest.webmanifest", "/staff-app/index.html", "/staff-app/_expo/static/js/web/bundle.js?v=fe4652eb2461ffd63a913df7bd5b3df8ec6691f1f497262914389a5e0d3a495b"]; +const PRECACHE = ["/staff-app/apple-touch-icon.png", "/staff-app/assets/assets/brand/anchorage-hero.0450b828e4f9c1f4456240096598f6f5.png", "/staff-app/assets/assets/brand/anchorage.fea5ce2f6fd18bf2950aa21c0980ed8e.png", "/staff-app/assets/assets/recipes/fishsupper.1609c58319e1e8721f5c639049fb054e.jpg", "/staff-app/assets/assets/recipes/lobster.2fb3485c8e372972099259017358c1b8.jpg", "/staff-app/assets/assets/recipes/moules.a4f342fc7e7fb62c8a0b5c1678bbea3f.jpg", "/staff-app/assets/assets/recipes/skink.4ce7b7c676f9cdcd0a060eda46f5a00e.jpg", "/staff-app/assets/assets/recipes/stp.1061ced765efdcafff2554adc3fc7113.jpg", "/staff-app/assets/assets/specials/sample-chalkboard.e7b4e4450a8483d4219bc6a214158d8f.jpg", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/400Regular/Poppins_400Regular.093ee89be9ede30383f39a899c485a82.ttf", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/500Medium/Poppins_500Medium.bf59c687bc6d3a70204d3944082c5cc0.ttf", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/600SemiBold/Poppins_600SemiBold.6f1520d107205975713ba09df778f93f.ttf", "/staff-app/assets/node_modules/@expo-google-fonts/poppins/700Bold/Poppins_700Bold.08c20a487911694291bd8c5de41315ad.ttf", "/staff-app/assets/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png", "/staff-app/assets/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png", "/staff-app/assets/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png", "/staff-app/assets/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png", "/staff-app/assets/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png", "/staff-app/assets/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png", "/staff-app/assets/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png", "/staff-app/assets/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png", "/staff-app/brand-logo.png", "/staff-app/favicon.ico", "/staff-app/icon-192.png", "/staff-app/icon-512.png", "/staff-app/icon-maskable-192.png", "/staff-app/icon-maskable-512.png", "/staff-app/manifest.webmanifest", "/staff-app/index.html", "/staff-app/_expo/static/js/web/bundle.js?v=9ef8caeb3d49284d8ca3fed595ca8dff0fc8cd310d765d64405ceabee05a26fa"]; // Hugging Face serves large files (fonts) through a redirect to its CDN. Browsers refuse to hand a *redirected* cached // response to a page, so store a plain copy instead (otherwise fonts, and so the app, fail to load offline). const plain = r => r.redirected ? r.blob().then(b => new Response(b, { status: 200, headers: { 'Content-Type': r.headers.get('Content-Type') || b.type || 'application/octet-stream' } })) : Promise.resolve(r); diff --git a/staff-app/team.html b/staff-app/team.html index 9adf92dcd8da139e905e41b3b0bb3296fc027fb3..d04c1648c4708485ef9e786bd21b19a362c170f9 100644 --- a/staff-app/team.html +++ b/staff-app/team.html @@ -96,5 +96,5 @@ function ccWatch(r){if(r.waiting&&navigator.serviceWorker.controller)ccShowUpdat }, 1000); })(); - +