Repository navigation
Expand file tree
/
Copy pathpos.html
More file actions
2683 lines (2645 loc) · 262 KB
/
Copy pathpos.html
File metadata and controls
2683 lines (2645 loc) · 262 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
customPOS — engine skeleton (v0.4)
==================================
Spine (v0.1) · fan-out (v0.2) · per-item paths + central station, two trades on one engine (v0.3).
v0.4 adds the RULES EVALUATOR — the one mechanism behind several primitives:
• REQUIRED modifiers — a choice that must be made before the line can send (steak temp, drink size, starch)
• SUGGESTED add-ons — an upsell prompted at order time (oat milk, Scotchgard)
• 86 / PAR-COUNT — a remaining-count that decrements and, at zero, disables the item everywhere
All of it is DATA on the catalog item — no code per trade. Pick the demo business up top.
One self-contained file, no build, no deps, localStorage. Neutral demo config only.
Docs: FLOW-SCHEMA.md · MODULE-LIBRARY.md · THE-MODEL.md
-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>customPOS — Live Demo (free POS builder for any business)</title>
<meta name="description" content="Try the customPOS engine live — a working point-of-sale you can click through. Then build your own for any business and download the code, free and open-source.">
<meta name="robots" content="index, follow, max-image-preview:large">
<link rel="canonical" href="https://custompos.org/pos.html">
<meta name="theme-color" content="#1f6feb">
<meta property="og:type" content="website">
<meta property="og:site_name" content="customPOS">
<meta property="og:url" content="https://custompos.org/pos.html">
<meta property="og:title" content="customPOS — live demo point-of-sale">
<meta property="og:description" content="Click through a working POS demo, then build your own for any business and own the code. Free, open-source.">
<meta property="og:image" content="https://custompos.org/og.png">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="customPOS — live demo point-of-sale">
<meta name="twitter:description" content="Click through a working POS demo, then build your own. Free, open-source.">
<meta name="twitter:image" content="https://custompos.org/og.png">
<!-- install-as-app: standalone display + home-screen icon (no service worker; the app is already offline via localStorage) -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="theme-color" content="#1f6feb" id="themeColor">
<style>
/* ===== Design tokens — one professional system, theme-aware. A shop's brand color drives --brand at runtime
(render() sets it from branding.brandColor), so the whole accent — buttons, links, selected states — matches
their brand. Light palette follows the OS unless overridden. ===== */
:root {
--brand:#1f6feb; --brand-ink:#ffffff; --brand-tint:rgba(31,111,235,.12);
--bg:#0e0f13; --surface:#16181f; --surface-2:#1e212b; --line:#2a2e39;
--ink:#eceef3; --dim:#98a1b0; --good:#2ea043; --warn:#e3893c; --bad:#e5484d;
--shadow:0 1px 2px rgba(0,0,0,.35), 0 6px 20px rgba(0,0,0,.20); --radius:12px;
}
@media (prefers-color-scheme: light) {
:root { --bg:#f4f6fa; --surface:#ffffff; --surface-2:#f1f3f8; --line:#e4e8ef; --ink:#1a2230; --dim:#5c6675;
--shadow:0 1px 2px rgba(16,24,40,.05), 0 6px 20px rgba(16,24,40,.07); }
}
* { box-sizing:border-box; }
body { margin:0; font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Inter,system-ui,sans-serif; -webkit-font-smoothing:antialiased; background:var(--bg); color:var(--ink); }
header { display:flex; align-items:center; gap:11px; padding:11px 18px; background:color-mix(in srgb, var(--surface) 85%, transparent); backdrop-filter:saturate(1.5) blur(10px); -webkit-backdrop-filter:saturate(1.5) blur(10px); border-bottom:1px solid var(--line); position:sticky; top:0; z-index:20; }
header .dot { width:24px; height:24px; border-radius:7px; background:var(--brand); color:var(--brand-ink); display:inline-flex; align-items:center; justify-content:center; font-weight:800; font-size:13px; flex:none; }
header .logo { height:28px; width:auto; max-width:132px; border-radius:6px; display:none; flex:none; object-fit:contain; }
header b { font-size:16px; font-weight:700; letter-spacing:-.01em; } header .station { color:var(--dim); } header .spacer { flex:1; }
a.link { color:var(--brand); cursor:pointer; text-decoration:none; font-weight:600; }
header a.link { font-size:13px; }
main { max-width:860px; margin:0 auto; padding:20px 16px 72px; }
h2 { font-size:12.5px; letter-spacing:.06em; text-transform:uppercase; color:var(--dim); margin:26px 0 10px; font-weight:700; }
.card { background:var(--surface); border:1px solid var(--line); border-radius:var(--radius); padding:16px; margin:12px 0; box-shadow:var(--shadow); }
.row { display:flex; align-items:center; gap:10px; } .row .spacer { flex:1; }
button { font:inherit; font-weight:500; color:var(--ink); background:var(--surface-2); border:1px solid var(--line); border-radius:10px; padding:9px 14px; cursor:pointer; transition:transform .05s ease, border-color .12s ease, filter .12s ease, box-shadow .12s ease; }
button:hover { border-color:var(--brand); } button:active { transform:translateY(1px); } button:disabled { opacity:.4; cursor:default; }
button:focus-visible, input:focus-visible, select:focus-visible, a:focus-visible, label:focus-visible { outline:2px solid var(--brand); outline-offset:2px; } /* keyboard nav */
.floorgrid { display:grid; grid-template-columns:repeat(auto-fill,minmax(110px,1fr)); gap:10px; }
.tabletile { border:2px solid transparent; border-radius:12px; padding:12px 10px; color:#fff; text-align:left; cursor:pointer; min-height:76px; box-shadow:var(--shadow); }
.tabletile small { display:block; opacity:.85; font-size:11px; margin-top:3px; }
.tabletile.warn { animation:tablepulse 1.1s ease-in-out infinite; }
@keyframes tablepulse { 0%,100%{ box-shadow:0 0 0 0 rgba(229,72,77,.0); border-color:transparent; } 50%{ box-shadow:0 0 0 3px rgba(229,72,77,.55); border-color:var(--bad); } }
button.primary { background:var(--brand); border-color:var(--brand); color:var(--brand-ink); font-weight:600; box-shadow:0 1px 2px rgba(0,0,0,.16); }
button.primary:hover { filter:brightness(1.07); }
button.good { background:var(--good); border-color:var(--good); color:#fff; }
button.danger { border-color:var(--bad); color:var(--bad); }
button.sel { border-color:var(--brand); color:var(--brand); background:var(--brand-tint); font-weight:600; }
.tile { display:block; width:100%; text-align:left; margin:0; padding:14px; border-radius:12px; background:var(--surface); border:1px solid var(--line); font-weight:600; line-height:1.3; }
.tile:hover { border-color:var(--brand); box-shadow:var(--shadow); transform:translateY(-1px); }
.tile small { display:block; color:var(--dim); font-weight:400; margin-top:5px; }
.tile.eightysix { opacity:.45; }
.muted { color:var(--dim); } .center { text-align:center; }
.pill { font-size:12px; padding:2px 9px; border-radius:20px; background:var(--surface-2); color:var(--dim); border:1px solid var(--line); }
.pill.route { border-color:var(--brand); color:var(--brand); }
.pill.x86 { border-color:var(--bad); color:var(--bad); }
.pill.flag { border-color:var(--bad); color:var(--bad); font-weight:600; }
.pill.clock.good { border-color:var(--good); color:var(--good); }
.pill.clock.warn { border-color:var(--warn); color:var(--warn); }
.pill.clock.bad { border-color:var(--bad); color:var(--bad); }
.line { display:flex; gap:8px; padding:8px 0; border-bottom:1px solid var(--line); align-items:center; }
.line:last-child { border-bottom:0; } .line small.mods { color:var(--dim); display:block; }
.grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(172px,1fr)); gap:10px; }
.empty { color:var(--dim); padding:22px; text-align:center; }
.fld { display:flex; align-items:center; gap:8px; margin:6px 0; } .flab { color:var(--dim); }
.picker button { display:block; width:100%; text-align:left; margin:8px 0; padding:15px; border-radius:12px; }
.picker button b { font-size:16px; } .picker button small { color:var(--dim); }
.flowsel { display:flex; gap:8px; margin:6px 0 18px; flex-wrap:wrap; }
.mgroup { margin:10px 0; } .mgroup .lbl { color:var(--dim); font-size:13px; margin-bottom:5px; }
.mgroup .opts, .opts { display:flex; gap:6px; flex-wrap:wrap; }
input, select { font:inherit; color:var(--ink); background:var(--surface-2); border:1px solid var(--line); border-radius:10px; padding:9px 11px; margin:0 6px 6px 0; }
input[type=color] { padding:2px; width:44px; height:38px; }
#scaffoldBar { display:flex; align-items:center; gap:12px; flex-wrap:wrap; padding:10px 18px; background:var(--brand-tint); border-bottom:1px solid var(--line); font-size:13.5px; color:var(--ink); }
#scaffoldBar .spacer { flex:1; } #scaffoldBar button { padding:6px 12px; font-size:13px; }
</style>
<header>
<img class="logo" id="brandLogo" alt="">
<span class="dot" id="brandDot"></span>
<b id="bizName">customPOS</b>
<span class="station" id="stationLabel"></span>
<span class="spacer"></span>
<a class="link" id="changeStation" style="display:none">change station</a>
</header>
<div id="scaffoldBar" hidden>
<span>🧱 <b>This is a scaffold, not a finished product.</b> A working foundation you — or an AI/human engineer (like Claude Code) — shape into your exact system.</span>
<span class="spacer"></span>
<a class="link" href="https://custompos.org" target="_blank" rel="noopener">how it works</a>
<button id="scaffoldOk" class="primary">Got it</button>
</div>
<main id="app"></main>
<script>
/* ===== CRASH REPORTER (Stage D4) — installed FIRST so a fault during startup (the one you most need to see)
is captured, not lost. A dead station is silent otherwise: a shell whose page threw on load shows a blank
screen and the driver just says "it's broken." We capture window.onerror + unhandledrejection, DEDUPE by
fault signature (a render that throws 400× on a poll is ONE fault, not 400), CAP per page-load, and batch to
a hub endpoint OUTSIDE the synced DB (a crash log must never ride the merge — it would sync a fault to every
station). A re-entrancy guard (finally-cleared) means the reporter can never crash inside its own handler. */
var CRASH = (function(){
var seen = {}, queue = [], sent = 0, CAP = 25, reporting = false;
function sig(e){ return [ (e && e.message) || e, (e && e.source) || '', (e && e.line) || '', (e && e.col) || '' ].join('|'); }
function hubUrl(){ try{ var q=new URL(location.href).searchParams.get('hub'); return q || (typeof window!=='undefined'&&window.CUSTOMPOS_HUB) || localStorage.getItem('custompos_hub') || ''; }catch(_){ return ''; } }
function record(e){
if (reporting) return; // never re-enter (a throw inside here would loop)
reporting = true;
try {
var s = sig(e);
if (seen[s]) { seen[s].n++; return; } // same fault again -> just count it, don't re-queue
if (sent >= CAP) return; // a storm is one event, not a flood of reports
seen[s] = { n:1 };
var rec = { sig:s, message:(e&&e.message)||String(e), source:(e&&e.source)||'', line:(e&&e.line)||0, col:(e&&e.col)||0,
stack:(e&&e.error&&e.error.stack)||'', ts:Date.now(), ua:(navigator&&navigator.userAgent)||'', url:location.href };
queue.push(rec); sent++;
var hub = hubUrl();
if (hub) { try { fetch(hub.replace(/\/$/,'')+'/api/crash', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(rec), keepalive:true }).catch(function(){}); } catch(_){} }
} catch(_) { /* the reporter must never throw */ }
finally { reporting = false; } // ALWAYS clear the guard, even if record() threw
}
if (typeof window !== 'undefined') {
window.addEventListener('error', function(ev){ record({ message:ev.message, source:ev.filename, line:ev.lineno, col:ev.colno, error:ev.error }); });
window.addEventListener('unhandledrejection', function(ev){ var r=ev&&ev.reason; record({ message:'unhandledrejection: '+((r&&r.message)||r), error:r }); });
}
return { record:record, queue:function(){ return queue.slice(); }, count:function(){ return sent; }, distinct:function(){ return Object.keys(seen).length; },
_reset:function(){ seen={}; queue=[]; sent=0; reporting=false; } };
})();
/* ============================================================================
customPOS ENGINE — MAP (search these banners to jump between sections)
----------------------------------------------------------------------------
THE FLOWS ............. demo businesses as config (injected flow replaces these)
MODULES / STATUS ..... module registry (station type → feature) + status labels
ENGINE / SYNC ........ flow selection, localStorage DB, optional hub sync (saveDB)
MONEY MATH ........... subtotal/discount/tax(incl or added)/total/paid/balance, refunds, returns
INVENTORY ............ stock on-hand, low/out, reason-coded adjustments
PAYMENTS / NOTIFY .... processor-agnostic charge/refund + notify seam (sim adapters)
DATA & BACKUP ........ export (JSON/CSV), import, restore
RULES EVALUATOR ...... required modifiers, 86/par, needsConfig
RENDER ............... router (station.type → renderer) + install/PWA
INTAKE ............... catalog, search/scan, config panel, deposits, capacity, quotes
PIPELINE / KDS ....... production stations, checklists, kitchen display + bump
CHECKOUT ............. tips, discounts/coupons, split, tenders, receipts, notify
REPORT ............... Z-report, drawer, labor, inventory, A/R, refunds/returns, backup
TIMECLOCK / BOOKING .. staff PIN + welcome; appointments → check-in
BOARD / TRACKER ...... internal status board; sanitized customer tracker
PICKER / BOOT ........ device setup screen; storage-event resync; first render
==========================================================================*/
/* ===================================== THE FLOWS ===================================== */
const CUSTOMPOS_VERSION = "0.75"; // engine version (the builder stamps this into downloads)
let FLOWS = {
// ===== FLAGSHIP DEMO — a COMPLETE restaurant, not a sample. Real menu, sales tax, food costs, staff on the
// clock, a kitchen display, and a back office that runs the numbers down to net profit. This is what the
// engine is FOR — the same depth that runs a real shop, configured for a burger joint. =====
burgerbarn: {
label:"Hamburger Barn (restaurant)", topology:"hub-and-spoke",
branding:{ name:"Hamburger Barn", brandColor:"#a3312a" },
endpoints:{
customer:{persist:false},
payment:{ tenders:["cash","card"], closeGate:"balanceLE0", tip:{presets:[15,18,20]}, split:true },
tax:{ rate:0.0825, included:false } // 8.25% sales tax, added at checkout (editable in the Office → Settings)
},
timer:{ mode:"aging", warnSec:360, badSec:720, label:"ticket" }, capacity:{ perOrderMins:6, max:15 }, kds:{ warnSec:360, badSec:720 },
labor:{ targetLaborPct:28 },
staff:[ {id:"e1",name:"Marcy",pin:"1111",wage:15}, {id:"e2",name:"Deshawn",pin:"2222",wage:16.5}, {id:"e3",name:"Tara",pin:"3333",wage:14} ],
welcome:{ message:"Fresh off the grill — have a great shift! 🍔", specials:["Push the Blue Plate Special","Upsell a shake"] },
catalog:[
// ---- BURGERS → grill (food cost ~30%) ----
{id:"bubba",name:"Bubba Burger",price:13,cost:4.10,category:"burger",path:["grill"],
modifiers:[{group:"Patty",required:true,options:[{name:"Single",price:0},{name:"Double",price:3}]}],
addons:[{name:"Bacon",price:1.5},{name:"Extra cheese",price:1},{name:"Jalapeños",price:0.5},{name:"Grilled onions",price:0.5}],
flags:["Allergy note"]},
{id:"mushswiss",name:"Mushroom Swiss Burger",price:12.5,cost:3.85,category:"burger",path:["grill"],addons:[{name:"Bacon",price:1.5}]},
{id:"gouda",name:"Gouda Burger",price:12.5,cost:3.80,category:"burger",path:["grill"]},
{id:"chipotle",name:"Chipotle Burger",price:12.5,cost:3.80,category:"burger",path:["grill"]},
{id:"cheeseburger",name:"Cheeseburger",price:9,cost:2.70,category:"burger",path:["grill"],
modifiers:[{group:"Cheese",required:true,options:[{name:"American",price:0},{name:"Swiss",price:0},{name:"Cheddar",price:0},{name:"Pepper Jack",price:0}]}]},
{id:"cfs",name:"Chicken Fried Steak",price:13,cost:4.30,category:"plate",path:["grill"]},
{id:"grillchick",name:"Grilled Chicken Sandwich",price:10,cost:3.10,category:"sandwich",path:["grill"]},
// ---- FRIED APPS & PLATES → fry ----
{id:"onionrings",name:"Onion Rings",price:6,cost:1.60,category:"app",path:["fry"]},
{id:"friedpickles",name:"Fried Pickles",price:6,cost:1.40,category:"app",path:["fry"]},
{id:"greenbeans",name:"Fried Green Beans",price:6,cost:1.55,category:"app",path:["fry"]},
{id:"cheesesticks",name:"Big Cheese Sticks",price:7,cost:2.10,category:"app",path:["fry"]},
{id:"friedmush",name:"Fried Mushrooms",price:6,cost:1.50,category:"app",path:["fry"]},
{id:"trio",name:"Big Teaser Trio",price:9,cost:2.90,category:"app",path:["fry"]},
{id:"catfish",name:"3-pc Catfish Plate",price:13,cost:4.50,category:"plate",path:["fry"]},
{id:"fries",name:"Fries",price:3,cost:0.80,category:"side",path:["fry"]},
// ---- SHAKES → shake bar ----
{id:"shake",name:"Milkshake",price:5,cost:1.30,category:"shake",path:["shakes"],
modifiers:[{group:"Flavor",required:true,options:[{name:"Vanilla",price:0},{name:"Chocolate",price:0},{name:"Strawberry",price:0}]}]},
// ---- DRINKS → handed over at the counter ----
{id:"drink",name:"Fountain Drink",price:2.5,cost:0.40,category:"drink",path:[]},
{id:"tea",name:"Sweet Tea",price:2.5,cost:0.35,category:"drink",path:[]},
// ---- daily special with an 86 count ----
{id:"special",name:"Blue Plate Special",price:10,cost:3.20,category:"plate",path:["grill"],par:10}
],
stations:[
{id:"counter",type:"central", label:"Front Counter", view:{money:true}},
{id:"grill", type:"production", label:"Grill", view:{money:false}},
{id:"fry", type:"production", label:"Fry Station", view:{money:false}},
{id:"shakes", type:"production", label:"Shake Bar", view:{money:false}},
{id:"kds", type:"kds", label:"Kitchen Display", view:{money:false}},
{id:"clock", type:"timeclock", label:"Time Clock", view:{}},
{id:"office", type:"report", label:"Office", view:{money:true}}
]
},
counter: {
label:"Counter shop", topology:"linear",
branding:{ name:"Corner Store", brandColor:"#1f6feb" },
endpoints:{ customer:{persist:false}, payment:{tenders:["cash"], closeGate:"balanceLE0"} },
timer:{ mode:"aging", warnSec:300, badSec:600, label:"prep" }, // ticket ages green->yellow->red
capacity:{ perOrderMins:4, max:3 }, // live wait + cap on orders in the queue
catalog:[
{id:"c1", name:"Coffee", price:3.50, category:"drink", path:["bar"]},
{id:"c2", name:"Latte", price:4.75, category:"drink", path:["bar"],
modifiers:[{group:"Size", required:true, options:[{name:"Small",price:0},{name:"Medium",price:0.50},{name:"Large",price:1.00}]}],
addons:[{name:"Oat milk", price:0.75},{name:"Extra shot", price:0.90}]},
{id:"c3", name:"Muffin", price:3.25, category:"food", path:["kitchen"], par:1, flags:["Nut allergy"]}, // 86 after 1; flag needs ack at kitchen
{id:"c4", name:"Bagel", price:2.75, category:"food", path:["kitchen"]}
],
stations:[
{id:"order", type:"intake", label:"Order Counter", view:{money:true}},
{id:"bar", type:"production", label:"Bar", view:{money:false}},
{id:"kitchen", type:"production", label:"Kitchen", view:{money:false}},
{id:"checkout", type:"fulfillment", label:"Checkout", view:{money:true}},
{id:"board", type:"board", label:"Expo Board", view:{money:false}}
]
},
cleaners: {
label:"Cleaners", topology:"hub-and-spoke",
branding:{ name:"Sunrise Cleaners", brandColor:"#2ea043" },
endpoints:{ customer:{persist:true}, payment:{tenders:["cash","card","account"], closeGate:"balanceLE0", points:["deposit-balance"], deposit:{pct:50}},
notify:{ template:"Hi {name}, your order #{number} at {biz} is ready for pickup." } },
timer:{ mode:"due", promiseSec:172800, warnSec:86400, label:"promise" }, // back-scheduled ready-by date
lifecycle:{ received:"Received — in line", ready:"Ready for pickup", done:"Picked up",
byStation:{ assembly:"In cleaning & pressing", rack:"Being racked" },
public:{ byStation:{ assembly:"Cleaning your order", rack:"Almost ready" } } },
catalog:[
{id:"g1", name:"Shirt", price:6.50, category:"press", path:["assembly","rack"], serialized:true, tagLabel:"HSL",
modifiers:[{group:"Starch", required:true, options:[{name:"None",price:0},{name:"Light",price:0},{name:"Heavy",price:0.50}]}],
flags:["Pre-existing damage"]},
{id:"g2", name:"Pants", price:7.00, category:"press", path:["assembly","rack"], serialized:true, tagLabel:"HSL"},
{id:"g3", name:"Wash & Fold", price:2.75, category:"wf", path:["rack"]}
],
stations:[
{id:"counter", type:"central", label:"Front Counter", view:{money:true}},
{id:"assembly", type:"production", label:"Assembly", view:{money:false}},
{id:"rack", type:"staging", label:"Rack", view:{money:false}},
{id:"board", type:"board", label:"Status Board", view:{money:false}},
{id:"tracker", type:"tracker", label:"Customer Tracker", view:{money:false, external:true}},
{id:"office", type:"report", label:"Office", view:{money:true}}
]
},
repair: { // THIRD trade — added as pure config, no engine changes: approval/waiver gate, split path, aging, deposit
label:"Repair shop", topology:"hub-and-spoke",
branding:{ name:"Fix-It Repair", brandColor:"#e3893c" },
endpoints:{ customer:{persist:true}, payment:{tenders:["cash","card"], closeGate:"balanceLE0", points:["deposit-balance"], deposit:{pct:50}} },
timer:{ mode:"aging", warnSec:600, badSec:1200, label:"in shop" },
catalog:[
{id:"r1", name:"Phone screen", price:129.00, category:"repair", path:["diagnose","repair","ready"],
modifiers:[{group:"Device", required:true, options:[{name:"iPhone",price:0},{name:"Android",price:0},{name:"Other",price:20}]}],
flags:["Data-loss waiver"]},
{id:"r2", name:"Battery", price:59.00, category:"repair", path:["repair","ready"]}, // skips diagnostics
{id:"r3", name:"Diagnostic", price:25.00, category:"repair", path:["diagnose","ready"]}
],
stations:[
{id:"counter", type:"central", label:"Front Counter", view:{money:true}},
{id:"diagnose", type:"production", label:"Diagnostics", view:{money:false}},
{id:"repair", type:"production", label:"Repair Bench", view:{money:false}},
{id:"ready", type:"staging", label:"Ready Shelf", view:{money:false}, checklist:["Powered on & tested","Cleaned","Case sealed"]},
{id:"board", type:"board", label:"Job Board", view:{money:false}},
{id:"tracker", type:"tracker", label:"Customer Tracker", view:{money:false, external:true}}
]
},
salon: { // FOURTH trade — services + per-provider commission + tips + retail, config-only
label:"Salon", topology:"hub-and-spoke",
branding:{ name:"Studio Salon", brandColor:"#b06fdb" },
endpoints:{ customer:{persist:true}, payment:{tenders:["cash","card"], closeGate:"balanceLE0", tip:{presets:[15,18,20]}},
loyalty:{ earnPerDollar:1, redeemPoints:20, redeemValue:5 } }, // earn 1 pt/$1; 20 pts = $5 off
performers:["Alex","Sam","Jordan"],
staff:[{id:"e1",name:"Alex",pin:"1111"},{id:"e2",name:"Sam",pin:"2222"},{id:"e3",name:"Jordan",pin:"3333"}], // clock in by PIN
welcome:{ message:"Make someone's day today ✂️", specials:["Ask about the color special","New: keratin add-on"] },
commission:{ pct:40 }, // 40% of service sales
catalog:[
{id:"s1", name:"Haircut", price:35, category:"service", path:["chair"], performer:true},
{id:"s2", name:"Color", price:85, category:"service", path:["chair"], performer:true},
{id:"s3", name:"Shampoo", price:22, category:"retail", path:[]}, // retail — no performer, no commission
{id:"s4", name:"Gift card $25", price:25, category:"giftcard", path:[]} // sold as a product; credits gift balance
],
stations:[
{id:"desk", type:"central", label:"Front Desk", view:{money:true}},
{id:"chair", type:"production", label:"Chair", view:{money:false}},
{id:"book", type:"booking", label:"Appointments", view:{}},
{id:"clock", type:"timeclock", label:"Time Clock", view:{}},
{id:"office", type:"report", label:"Back Office", view:{money:true}}
]
}
};
/* Module registry: enabling a station of a type auto-enables its module (the module contract). */
const MODULES = {
core: { label:"Core (intake/checkout)", stationTypes:["intake","fulfillment","central"] },
makers: { label:"Production / kitchen", stationTypes:["production"] },
staging: { label:"Staging / rack", stationTypes:["staging"] },
board: { label:"Status board", stationTypes:["board"] },
portal: { label:"Customer tracker", stationTypes:["tracker"] },
office: { label:"Commission / reports", stationTypes:["report"] },
detail: { label:"Detail / itemize", stationTypes:["detail"] },
route: { label:"Delivery route", stationTypes:["route"] },
clock: { label:"Time clock", stationTypes:["timeclock"] },
booking: { label:"Appointments", stationTypes:["booking"] },
kds: { label:"Kitchen display (bump)", stationTypes:["kds"] },
floor: { label:"Floor / table plan", stationTypes:["floor"] },
schedule:{ label:"Staff scheduling", stationTypes:["schedule"] },
worker: { label:"Worker portal", stationTypes:["worker"] }
};
function enabledModules(flow){ const types=new Set(flow.stations.map(s=>s.type)); return Object.keys(MODULES).filter(m=>MODULES[m].stationTypes.some(t=>types.has(t))); }
const STATUS_LABEL = { INPROGRESS:"In progress", READY:"Ready for pickup", PAID:"Ready for pickup", CLOSED:"Picked up" };
/* Config-driven NAMED LIFECYCLE STAGE for an order (e.g. Received → Detailing → Assembly → Racked → Ready → Picked up).
Derives from the least-advanced incomplete line's current station, so the order reads as "where the slowest piece is."
FLOW.lifecycle overrides the labels; FLOW.lifecycle.public overrides the customer-tracker phrasing. No trade code — pure config.
Falls back to sensible defaults (station labels) when no lifecycle config is present, so every trade benefits. */
function stageOf(r, pub){
const base = (FLOW.lifecycle) || {}; const L = (pub && base.public) ? Object.assign({}, base, base.public) : base;
if(r.undetailed) return L.dropped || "Received — being itemized";
if(r.status === "CLOSED") return L.done || "Picked up";
if(r.status === "READY" || r.status === "PAID") return L.ready || "Ready for pickup";
const inc = (r.lines||[]).filter(l => !lineComplete(l));
if(!inc.length) return L.ready || "Ready for pickup";
const started = (r.lines||[]).some(l => (l.stage||0) > 0 || lineComplete(l));
if(!started) return L.received || "Received";
let least = inc[0]; inc.forEach(l => { if((l.stage||0) < (least.stage||0)) least = l; });
const stId = least.path[least.stage||0];
const station = (FLOW.stations||[]).find(s => s.id === stId);
return (L.byStation && L.byStation[stId]) || (station && (station.stageLabel || station.label)) || "In progress";
}
/* ============================================================================ ENGINE */
// A downloaded/built POS injects its single flow before this script runs — then there is no demo picker.
if(typeof window!=="undefined" && window.CUSTOMPOS_FLOW){ const f=window.CUSTOMPOS_FLOW; FLOWS = {}; FLOWS[f.flowId||"business"] = f; }
function flowId(){ try{ const u=new URL(location.href).searchParams.get("flow"); if(u&&FLOWS[u]) return u; }catch(e){} // ?flow=cleaners → a shareable, trade-specific demo link
const s=localStorage.getItem("custompos_flow"); return (s&&FLOWS[s]) ? s : Object.keys(FLOWS)[0]; }
let FLOW = FLOWS[flowId()];
function dkey(){ return "custompos_demo_"+flowId(); }
function skey(){ return "custompos_station_"+flowId(); }
function wkey(){ return "custompos_worker_"+flowId(); } // worker portal: who's signed in on THIS device (personal-device stay-signed-in)
function dbDefaults(d){ d=d||{}; d.records=d.records||[]; d.seq=d.seq||0; d.customers=d.customers||[]; d.punches=d.punches||[]; d.received=d.received||{}; d.bookings=d.bookings||[]; d.quotes=d.quotes||[]; d.adjustLog=d.adjustLog||[]; d.tables=d.tables||{}; d.turns=d.turns||[]; d.shifts=d.shifts||[]; d.schedule=d.schedule||{}; d.timeoff=d.timeoff||[]; d.incidents=d.incidents||[]; d.kudos=d.kudos||[]; d.ageLog=d.ageLog||[]; d.activity=d.activity||[]; d.expenses=d.expenses||[]; return d; }
/* PER-COLLECTION MIRROR (Stage B3) — every save also writes each collection under its OWN key (dkey()+"::"+col).
Two payoffs, both generalized from Ozark's worst failure (a station that opens on an EMPTY shop): (1) a torn
write corrupts one collection's key, not the whole shop; (2) when the main blob is corrupt/missing, loadDB
REBUILDS from the mirror instead of returning empty. The main blob stays the canonical store (written every
save — backward compatible, and the source that heals a corrupt mirror), so the normal read path is unchanged
and a mirror is consulted ONLY when the blob itself fails to parse. */
// A DISTINCT prefix so a mirror key never collides with the blob's own key family — anything that enumerates
// `custompos_*` keys (a backup/export, a flow switch, a test locating the blob) must not trip over the mirror.
function mirrorPrefix(){ return "cpmirror::"+dkey()+"::"; }
function rebuildFromMirror(){
try{ if(localStorage.getItem(mirrorPrefix()+"records")===null) return null; // no mirror -> a genuinely empty shop
const out={}, pfx=mirrorPrefix();
for(let i=0;i<localStorage.length;i++){ const k=localStorage.key(i);
if(k && k.indexOf(pfx)===0){ try{ out[k.slice(pfx.length)]=JSON.parse(localStorage.getItem(k)); }catch(e){} } }
return Array.isArray(out.records) ? out : null; // records must be sane or it isn't a shop worth healing to
}catch(e){ return null; }
}
function loadDB(){
let d=null; try{ d=JSON.parse(localStorage.getItem(dkey())); }catch(e){ d=null; }
if(!d || typeof d!=="object" || !Array.isArray(d.records)) d=rebuildFromMirror(); // heal a corrupt/missing blob
return dbDefaults(d);
}
function persistDB(db){
try{ localStorage.setItem(dkey(), JSON.stringify(db)); }catch(e){} // canonical whole-DB blob (compat + heal source)
try{ const pfx=mirrorPrefix(); // mirror: rewrite only the parts that moved
for(const col in db){ if(!Object.prototype.hasOwnProperty.call(db,col)) continue;
const cs=JSON.stringify(db[col]); if(localStorage.getItem(pfx+col)!==cs) localStorage.setItem(pfx+col, cs); }
}catch(e){}
}
/* OPTIONAL multi-device sync — OFF unless a hub is configured (?hub=… / window.CUSTOMPOS_HUB / localStorage).
When on, every save pushes to the hub and a poller pulls the merged DB, so separate devices share one POS. */
const SYNC = {
url(){ try{ const q=new URL(location.href).searchParams.get("hub"); return q || (typeof window!=="undefined"&&window.CUSTOMPOS_HUB) || localStorage.getItem("custompos_hub") || ""; }catch(e){ return ""; } },
get on(){ return !!this.url(); }, applying:false, rev:0, // rev = the last hub revision this device holds
// DELTA PUSH (Stage B2): send only the records/customers whose content differs from what the hub last
// confirmed it holds (`_pushed` = the hub's known copy, refreshed from every hub response). Ringing one
// order uploads one record, not the whole shop; an idle save uploads nothing (skips the request entirely).
// Safe because the hub upserts and absence never deletes — a partial push can't drop what it omits.
_pushed:{}, _pushedSeq:0, _sig(r){ return JSON.stringify(r); },
push(){ if(!this.on) return;
const db=loadDB();
const recs =(db.records ||[]).filter(r=>this._pushed["r:"+r.id] !==this._sig(r));
const custs=(db.customers||[]).filter(c=>this._pushed["c:"+c.phone]!==this._sig(c));
const seqMoved=(db.seq||0)>(this._pushedSeq||0);
if(!recs.length && !custs.length && !seqMoved) return; // nothing moved since the hub last confirmed
const payload={ records:recs, customers:custs, seq:db.seq||0 };
try{ fetch(this.url().replace(/\/$/,"")+"/api/db",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({db:payload})}).then(r=>r.json()).then(j=>this.applyRemote(j.db, j.rev)).catch(()=>{}); }catch(e){} },
// DELTA PULL (Stage B1): ask only for what moved since the rev we hold. A fresh device (rev 0) gets the
// whole set; a caught-up device gets a few KB. The hub answers {db:{records,customers,seq}, rev, delta?}.
pull(){ if(!this.on) return; try{ fetch(this.url().replace(/\/$/,"")+"/api/db?since="+(this.rev||0)).then(r=>r.json()).then(j=>this.applyRemote(j.db, j.rev)).catch(()=>{}); }catch(e){} },
// Merge the hub's records/customers INTO the local DB (never replace it wholesale). Two reasons: (1) a delta
// carries only what changed, so a merge is the only correct way to fold it in; (2) the hub syncs only
// records+customers, so replacing would wipe this device's local-only collections (punches, bookings…).
// stampNewer picks the winner and the one-way status law holds, exactly as on the hub — a slow local clock
// still can't be clobbered by a stale remote copy, and an order never rolls backward.
applyRemote(db, rev){ if(!db) return; const local=loadDB();
local.records = syncMergeArr(local.records||[], db.records||[], "id", true);
local.customers = syncMergeArr(local.customers||[], db.customers||[], "phone", false);
local.seq = Math.max(local.seq||0, db.seq||0);
// remember exactly what the hub reported it holds, so the next push sends only genuinely-newer local edits
(db.records ||[]).forEach(r=>{ this._pushed["r:"+r.id] =this._sig(r); });
(db.customers||[]).forEach(c=>{ this._pushed["c:"+c.phone]=this._sig(c); });
this._pushedSeq=Math.max(this._pushedSeq||0, db.seq||0);
if(typeof rev==="number") this.rev = Math.max(this.rev||0, rev);
this.applying=true; try{ persistDB(local); }catch(e){} this.applying=false;
DB=loadDB(); render(); },
// THE MIRROR (D1): fingerprint the local collections, ask the hub which disagree, and HEAL a named one by
// forcing a full re-pull (reset rev/_pushed so the next pull is `?since=0` and the merge reconciles both ways).
verify(){ if(!this.on) return Promise.resolve(null); const db=loadDB();
const fp={ records:fingerprint(db.records,"id"), customers:fingerprint(db.customers,"phone") };
try{ return fetch(this.url().replace(/\/$/,"")+"/api/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fp})}).then(r=>r.json()).then(j=>{
if(j && j.disagree && j.disagree.length){ this.rev=0; this._pushed={}; this._pushedSeq=0; this.pull(); } // heal
return j; }).catch(()=>null); }catch(e){ return Promise.resolve(null); } }
};
/* SYNC CLOCK — the same monotonic hybrid clock + comparison the hub uses (hub.js). ⚠️ Keep these three
IDENTICAL in both places; tests/engine-clock.js fails if they drift. A station's wall clock can be wrong
(a dead CMOS battery is a real shop scenario): hlcNow() never goes backward, so an edit made on a slow
clock still supersedes the copy it replaces, and stampScale/stampNewer rank a bare-ms and a hybrid stamp
on one number line without the 1000x error. */
let _hlc=0;
function hlcNow(){ _hlc=Math.max(Date.now()*1000, _hlc+1); return _hlc; }
function stampScale(t){ t=+t||0; return t<1e15 ? t*1000 : t; }
function stampNewer(a,b){ return stampScale(a)>=stampScale(b); }
// One-way status law (mirrors hub.js ORDER_RANK): a stale stamp can pick whose fields win, but it can never
// roll an order's status below what this device already knows — a race the hub also refuses server-side.
const ORDER_RANK={ INPROGRESS:1, READY:2, PAID:3, CLOSED:4, REFUNDED:5 };
// The client half of the hub's mergeArr: fold an incoming (delta or full) set into the base keyed by `key`.
// The base is authoritative for what's PRESENT (absence never deletes — a delta only ever upserts); a record
// replaces its stored copy only when stampNewer says so; with advanceOnly, a winner's status can't fall.
function syncMergeArr(base, incoming, key, advanceOnly){
const by=new Map((base||[]).map(r=>[r[key], r]));
(incoming||[]).forEach(r=>{ const prev=by.get(r[key]);
let win=(!prev || stampNewer(r.upd, prev.upd)) ? r : prev;
if(advanceOnly && prev && ORDER_RANK[prev.status] > (ORDER_RANK[win.status]||0)) win={...win, status:prev.status};
by.set(r[key], win); });
return [...by.values()];
}
// D1 — THE MIRROR. This fingerprint block MUST be byte-identical to the one in hub.js (a fingerprint that means
// something different on each side would invent drift or hide it); tests/mirror-fingerprint.js gates the bytes.
/*<<FP>>*/
function fpHash(s){var h=5381;for(var i=0;i<s.length;i++){h=((h*33)^s.charCodeAt(i))>>>0;}return h;}
function fingerprint(list,key){var a=(list||[]).map(function(r){return String(r&&r[key])+':'+fpHash(JSON.stringify(r));});a.sort();return{n:a.length,hash:fpHash(a.join('|'))};}
/*<</FP>>*/
function saveDB(db){
// stamp a modification time on any record whose content changed, so hub merge keeps the newer copy
try{ const prev=JSON.parse(localStorage.getItem(dkey())||"{}"); const norm=r=>JSON.stringify({...r, upd:0});
const was=new Map((prev.records||[]).map(r=>[r.id, norm(r)]));
(db.records||[]).forEach(r=>{ if(was.get(r.id)!==norm(r)) r.upd=hlcNow(); });
}catch(e){}
persistDB(db); if(SYNC.on && !SYNC.applying) SYNC.push();
}
let DB = loadDB();
/* ADMIN SETTINGS — a shop can change its own tax, tips, name and labor target from the Office without editing
config or re-downloading. Saved settings live in DB.settings and OVERLAY the flow's defaults at load (and
after every save), so the money math and header just read FLOW as before — no per-call lookup, and a reload
re-applies them. Per-flow (DB is per-flow), logged like any other change. */
function applySettings(){ try{ const s=(loadDB().settings)||{};
if(s.bizName) FLOW.branding.name=s.bizName;
if(s.brandColor) FLOW.branding.brandColor=s.brandColor;
if(s.logo!==undefined) FLOW.branding.logo=s.logo||null;
if(s.tax){ FLOW.endpoints.tax=Object.assign({}, FLOW.endpoints.tax||{}, s.tax); }
if(Array.isArray(s.tipPresets) && FLOW.endpoints.payment){ FLOW.endpoints.payment.tip=Object.assign({}, FLOW.endpoints.payment.tip||{}, {presets:s.tipPresets}); }
if(s.targetLaborPct!=null){ FLOW.labor=Object.assign({}, FLOW.labor||{}, {targetLaborPct:+s.targetLaborPct}); }
}catch(e){} }
function saveSettings(patch){ DB=loadDB(); DB.settings=Object.assign({}, DB.settings||{}, patch); saveDB(DB); applySettings(); logActivity("admin", "settings updated · "+Object.keys(patch).join(", ")); }
applySettings();
function setFlow(id){ localStorage.setItem("custompos_flow", id); FLOW=FLOWS[id]; draft=null; pending=null; DB=loadDB(); applySettings(); render(); }
function boundStation(){ const id=localStorage.getItem(skey()); return FLOW.stations.find(s=>s.id===id)||null; }
function bindStation(id){ localStorage.setItem(skey(), id); render(); }
function unbind(){ localStorage.removeItem(skey()); render(); }
/* ===================================== MULTI-STORE (optional) =====================================
A flow with a `stores` list becomes multi-location. Each device is scoped to a store; every order belongs
to a store — the customer's home store if known, else this device's store, else the plant. Orders whose
store is a DROP store are produced at the PLANT and read "assembled at <plant>". Print routing (Stage 4)
keys off the ORDER's storeId, never the workstation. Fully inert when a flow has no `stores` — a
single-store business never sees any of it. Pure data-as-config, no per-trade code. */
function storesOn(){ return Array.isArray(FLOW.stores) && FLOW.stores.length>0; }
function storeList(){ return storesOn() ? FLOW.stores : []; }
function storeById(id){ return storeList().find(s=>s.id===id) || null; }
function storeName(id){ const s=storeById(id); return s ? s.name : ""; }
function isPlantStore(id){ const s=storeById(id); return !!(s && s.plant); }
function plantStore(){ return storeList().find(s=>s.plant) || storeList()[0] || null; }
function defaultStoreId(){ const p=plantStore(); return p ? p.id : null; }
function stkey(){ return "custompos_store_"+flowId(); } // which store THIS device is at
function homeStore(){ if(!storesOn()) return null; const id=localStorage.getItem(stkey()); return storeById(id) ? id : null; }
function setStore(id){ if(id) localStorage.setItem(stkey(), id); else localStorage.removeItem(stkey()); render(); }
function storeForOrder(cust){ return (cust && cust.storeId) || homeStore() || defaultStoreId(); } // an order's home store
function storeChip(r){ if(!storesOn() || !r.storeId) return ""; const nm=storeName(r.storeId); return nm ? " <span class='pill' title='Store'>🏬 "+nm+"</span>" : ""; }
function tableChip(r){ return r.tableId ? " <span class='pill' title='Table'>🍽 "+tableLabel(r.tableId)+"</span>" : ""; }
function assembledAt(r){ if(!storesOn() || !r.storeId) return ""; const p=plantStore(); return (p && r.storeId!==p.id) ? "assembled at "+p.name : ""; } // a drop-store order is done at the plant
/* ===================================== MONEY MATH ===================================== */
function lineSubtotal(r){ return r.lines.reduce((s,l)=> s + l.price*l.qty, 0); }
function recordDiscount(r){ return Math.min(r.discount||0, lineSubtotal(r)); }
function taxIncluded(){ return !!(FLOW.endpoints.tax && FLOW.endpoints.tax.included); }
/* Tax rate for an order. Default is the shop's own (origin) rate. When FLOW.endpoints.tax.zones is configured
(destination-based sales tax — e.g. a delivery into another town/jurisdiction), an order tagged with a
taxZone is taxed at that zone's rate instead. General: delivery, a truck that parks in different towns, a
caterer billing the event's address. Backward-compatible — no zones ⇒ the flat rate, exactly as before. */
function orderTaxRate(r){ const t=FLOW.endpoints.tax; if(!t) return 0;
if(r && r.taxZone && Array.isArray(t.zones)){ const z=t.zones.find(z=>z.name===r.taxZone); if(z) return +z.rate||0; }
return +t.rate||0; }
/* Rate for ONE line. Non-taxable items (taxable:false) and gift cards are 0. When FLOW.endpoints.tax.classes
is configured (states that tax categories differently — grocery exempt, prepared food/soda taxed), an item's
taxClass picks that class's rate; otherwise the order's default (zone-aware) rate applies. Lets a single
basket mix rates line by line. Backward-compatible — no classes ⇒ every taxable line uses the default rate. */
function lineTaxRate(l, r){ const t=FLOW.endpoints.tax; if(!t) return 0;
if(l.taxable===false || l.category==="giftcard") return 0;
const it=(FLOW.catalog||[]).find(i=>i.id===l.catId); const cls=(it&&it.taxClass)||l.taxClass;
if(cls && t.classes && t.classes[cls]!=null) return +t.classes[cls]||0;
return orderTaxRate(r); }
function recordTax(r){ // per-LINE rate (class/zone aware); non-taxable & gift cards excluded; discount prorated
const t=FLOW.endpoints.tax; if(!t) return 0;
const sub=lineSubtotal(r); if(sub<=0) return 0;
const discFactor=(sub-recordDiscount(r))/sub; // spread any discount evenly across lines
let tax=0; const inc=taxIncluded();
r.lines.forEach(l=>{ const rate=lineTaxRate(l,r); if(!rate) return; const base=l.price*l.qty*discFactor;
tax += inc ? base*rate/(1+rate) // VAT-style: tax already inside the price
: base*rate; }); // added on top
return +tax.toFixed(2);
}
function recordNet(r){ return +(lineSubtotal(r) - recordDiscount(r) - (taxIncluded()?recordTax(r):0)).toFixed(2); } // sales excluding tax
function recordTotal(r){ return +(lineSubtotal(r) - recordDiscount(r) + (taxIncluded()?0:recordTax(r)) + (r.tip||0) + (r.roundUp||0)).toFixed(2); } // included tax is already inside the price; roundUp = optional charity add-on
// age-restricted items (tobacco/alcohol/lottery): an item's ageRestricted (true→21, or a number) drives an ID-check gate at checkout
function lineAge(l){ const it=FLOW.catalog.find(i=>i.id===l.catId); const a=it&&it.ageRestricted; return a===true?21:(+a||0); }
function orderAgeReq(r){ return Math.max(0, ...((r.lines||[]).filter(l=>!l.returned).map(lineAge))); }
function recordPaid(r){ return (r.tenders||[]).reduce((s,t)=> s + t.amount, 0); }
function recordBalance(r){ return +(recordTotal(r) - recordPaid(r)).toFixed(2); }
function firstPerformer(r){ const l=r.lines.find(x=>x.performer); return l?l.performer:null; }
// refund reverses every original tender back to itself (card → card, cash → cash) and marks the order REFUNDED
function refundRecord(r){
(r.tenders||[]).filter(t=>!t.refund).forEach(t=>{ if(t.type==="card" && payAdapter().refund){ payAdapter().refund(t.ref, Math.round(t.amount*100)); } });
// reversing a house-account charge also credits the customer's balance (A/R)
if(r.customer){ const cust=(DB.customers||[]).find(x=>x.phone===r.customer.phone); if(cust){ const acct=(r.tenders||[]).filter(t=>!t.refund&&t.type==="account").reduce((s,t)=>s+t.amount,0); if(acct){ cust.balance=+((cust.balance||0)-acct).toFixed(2); if(cust.balance<0) cust.balance=0; } } }
const refunded=(r.tenders||[]).filter(t=>!t.refund).reduce((s,t)=>s+t.amount,0);
(r.tenders||[]).filter(t=>!t.refund).slice().forEach(t=>{ r.tenders.push({ type:t.type, amount:+(-t.amount).toFixed(2), refund:true, ref:t.ref }); });
r.status="REFUNDED"; r.refundedAt=new Date().toISOString().slice(11,16);
logActivity("refund", "full refund "+money(refunded)+" on #"+r.number+" — "+r.lines.length+" item(s)", r.number, refunded);
}
function returnedSubtotal(r){ return (r.lines||[]).filter(l=>l.returned).reduce((s,l)=>s+l.price*l.qty,0); }
// LINE-LEVEL return: refund selected lines' share of the total to the original tender(s), mark them returned
function returnLines(r, lineIds){
const allSub=lineSubtotal(r); if(allSub<=0) return;
const retSub=r.lines.filter(l=>lineIds.includes(l.id)).reduce((s,l)=>s+l.price*l.qty,0); if(retSub<=0) return;
const amount=+((retSub/allSub)*recordTotal(r)).toFixed(2);
const pos=(r.tenders||[]).filter(t=>!t.refund && t.amount>0); const posTotal=pos.reduce((s,t)=>s+t.amount,0)||amount;
pos.forEach(t=>{ const share=+(-(amount*t.amount/posTotal)).toFixed(2); if(share){ if(t.type==="card"&&payAdapter().refund) payAdapter().refund(t.ref, Math.round(-share*100)); r.tenders.push({ type:t.type, amount:share, refund:true, ref:t.ref }); } });
if(r.customer){ const cust=(DB.customers||[]).find(x=>x.phone===r.customer.phone); if(cust){ const acctPos=pos.filter(t=>t.type==="account").reduce((s,t)=>s+t.amount,0); if(acctPos>0){ const acctShare=+((amount*acctPos/posTotal)).toFixed(2); cust.balance=+((cust.balance||0)-acctShare).toFixed(2); if(cust.balance<0) cust.balance=0; } } }
const names=lineIds.map(id=>{ const l=r.lines.find(x=>x.id===id); return l?l.name:null; }).filter(Boolean);
lineIds.forEach(id=>{ const l=r.lines.find(x=>x.id===id); if(l) l.returned=true; });
if(r.lines.every(l=>l.returned)) r.status="REFUNDED";
r.refundedAt=new Date().toISOString().slice(11,16);
logActivity("refund", "line refund "+money(amount)+" on #"+r.number+" — "+names.join(", "), r.number, amount);
saveDB(DB); render();
}
/* Processor-agnostic PAYMENTS interface (matches docs/PAYMENTS-MODULE.md). By default — with no processor
connected — the "record" adapter simply RECORDS a card sale on the order (so the books and the drawer are
right); it does not contact any processor and does not invent an approval or a card number. Connect the
certified CardConnect adapter on your own server to actually charge cards; it swaps in by setting
endpoints.payment.provider. The browser only ever sees a token + last4 + brand — never a card number. */
const PAYMENTS = {
record: {
label:"Record only (no processor connected)",
charge(amountCents, idemKey){ return { status:"approved", recorded:true, ref:"" }; }, // idemKey forwarded to a real processor; nothing is charged here
refund(ref, amountCents){ return { status:"refunded", recorded:true, ref:"" }; } // records the reversal
}
};
function payAdapter(){ const pr=(FLOW.endpoints.payment&&FLOW.endpoints.payment.provider)||"record"; return PAYMENTS[pr]||PAYMENTS.record; }
function cardTenders(r){ return (r.tenders||[]).filter(t=>t.type==="card" && !t.refund); }
/* IDEMPOTENT CARD CHARGE (Stage E3). A double-tapped Pay button or a retried request must never charge twice.
The guard asks the APPEND-ONLY tender ledger, never a boolean flag (a flag gets rolled back by a merge and
double-charges anyway): if a card tender already carries this idempotency key, this is a retry — return the
existing tender WITHOUT charging again. The key is also forwarded to the processor, so the real seam dedups
on its side too. The record is the source of truth. */
function chargeCardOnce(r, payAmt, idemKey){
const dup=(r.tenders||[]).find(t=>t.idem===idemKey && !t.refund);
if(dup) return { status:"approved", dedup:true, tender:dup };
const res=payAdapter().charge(Math.round(payAmt*100), idemKey);
if(res && res.status==="approved"){ const tender={ type:"card", amount:payAmt, last4:res.last4, brand:res.brand, ref:res.ref, idem:idemKey };
(r.tenders=r.tenders||[]).push(tender); return { status:"approved", tender:tender }; }
return res || { status:"error" };
}
function cardLabel(t){ return t && t.brand ? ("💳 "+t.brand+" ••"+t.last4) : "💳 Card"; } // real processor gives brand/last4; record-only just says "Card"
/* NOTIFY — the same processor-agnostic shape as payments. With no hub connected the "record" adapter records
the message so the POS works offline; a hub adapter (Twilio etc.) does the real send server-side. The
browser never holds an API key. */
const NOTIFY = { record: { label:"Record only (connect a hub to send)", send(to, body){ return { status:"sent", to, body }; } } };
function notifyAdapter(){ const pr=(FLOW.endpoints.notify&&FLOW.endpoints.notify.provider)||"record"; return NOTIFY[pr]||NOTIFY.record; }
function composeNotify(r){
const t=(FLOW.endpoints.notify&&FLOW.endpoints.notify.template)||"Hi {name}, your order #{number} at {biz} is ready.";
return t.replace(/\{name\}/g, (r.customer&&r.customer.name)||"there").replace(/\{number\}/g, r.number).replace(/\{biz\}/g, FLOW.branding.name).replace(/\{status\}/g, STATUS_LABEL[r.status]||r.status).replace(/\{balance\}/g, money(Math.max(0,recordBalance(r))));
}
function lineComplete(l){ return l.stage >= l.path.length; }
function allComplete(r){ return r.lines.every(lineComplete); }
// COURSE PACING: with coursing on, only fired courses reach the line; later courses hold until "fired".
function coursingOn(){ return !!(FLOW.endpoints && FLOW.endpoints.coursing); }
function courseOf(l){ return l.course||1; }
function courseReleased(r, l){ return !coursingOn() || courseOf(l) <= (r.firedCourse||1); }
function courseLabel(n){ const c=(FLOW.endpoints&&FLOW.endpoints.coursing&&FLOW.endpoints.coursing.labels)||FLOW.courses; return (c&&c[n-1]) || ("Course "+n); }
function maxCourse(r){ return Math.max(1, ...r.lines.map(courseOf)); }
function heldCourses(r){ return coursingOn() && (r.firedCourse||1) < maxCourse(r) && r.status==="INPROGRESS"; }
function fireNextCourse(r){ r.firedCourse=(r.firedCourse||1)+1; saveDB(DB); render(); }
function linesAtStation(r, stationId){ return r.lines.filter(l => !lineComplete(l) && courseReleased(r,l) && l.path[l.stage]===stationId); }
function afterChange(r){ if(r.status==="INPROGRESS" && allComplete(r)) r.status="READY"; saveDB(DB); }
/* --- TIMER / SLA service: one primitive, aging or back-scheduled-due, threshold colors --- */
function fmtDur(s){ s=Math.max(0,Math.round(s)); if(s>=3600){ const h=Math.floor(s/3600), m=Math.round((s%3600)/60); return h+"h "+m+"m"; } const m=Math.floor(s/60); return m+":"+String(s%60).padStart(2,"0"); }
function clockChip(r){
const t=FLOW.timer; if(!t||!r.ts) return "";
let cls, txt;
if(t.mode==="due"){ const rem=(r.ts + t.promiseSec*1000 - Date.now())/1000;
cls = rem<0 ? "bad" : rem<=t.warnSec ? "warn" : "good"; txt = rem<0 ? "OVERDUE" : "due "+fmtDur(rem); }
else { const el=(Date.now()-r.ts)/1000; cls = el>=t.badSec ? "bad" : el>=t.warnSec ? "warn" : "good"; txt = fmtDur(el); }
return " <span class='pill clock "+cls+"'>"+txt+"</span>";
}
/* --- the RULES EVALUATOR: par/86 remaining, and modifier requirements --- */
function soldOf(catId){
let n = DB.records.reduce((s,r)=> s + r.lines.filter(l=>l.catId===catId).reduce((a,l)=>a+l.qty,0), 0);
if(draft) n += draft.lines.filter(l=>l.catId===catId).reduce((a,l)=>a+l.qty,0);
return n;
}
function remainingOf(item){ return item.par==null ? Infinity : item.par - soldOf(item.id); }
function is86(item){ return remainingOf(item) <= 0; }
// INVENTORY: on-hand = starting stock + any received − everything sold. Tracked only when item.stock is set.
/* ===================================== INVENTORY ===================================== */
function tracksStock(item){ return item.stock!=null; }
function stockOnHand(item){ return (item.stock||0) + ((DB.received||{})[item.id]||0) - soldOf(item.id); }
// reason-coded stock change: receive/transfer add or remove, waste removes, recount sets the on-hand
const STOCK_REASONS = { "Receive":1, "Transfer in":1, "Transfer out":-1, "Waste":-1, "Recount":0 };
function adjustStock(item, qty, reason){
qty=Number(qty)||0; if(!qty && reason!=="Recount") return;
const sign=STOCK_REASONS[reason]!=null?STOCK_REASONS[reason]:1;
const delta = reason==="Recount" ? +(qty - stockOnHand(item)) : sign*Math.abs(qty);
DB.received=DB.received||{}; DB.received[item.id]=(DB.received[item.id]||0)+delta;
DB.adjustLog=DB.adjustLog||[]; DB.adjustLog.push({ catId:item.id, name:item.name, reason, delta, at:new Date().toISOString().slice(11,16), day:todayStr() });
saveDB(DB); logActivity("stock", reason+" "+item.name+" "+(delta>0?"+":"")+delta); render();
}
function isLowStock(item){ return tracksStock(item) && stockOnHand(item) <= (item.reorderAt!=null?item.reorderAt:0); }
function isOutOfStock(item){ return tracksStock(item) && stockOnHand(item) <= 0; }
function needsConfig(item){ return (item.modifiers&&item.modifiers.length) || (item.addons&&item.addons.length) || (item.flags&&item.flags.length) || item.performer; }
/* ============================================================================ RENDER */
function money(n){ return "$"+n.toFixed(2); }
function dayOf(ts){ return new Date(ts||Date.now()).toLocaleDateString("en-CA"); } // local YYYY-MM-DD
function todayStr(){ return new Date().toLocaleDateString("en-CA"); }
function shiftDay(dstr, delta){ const d=new Date(dstr+"T12:00:00"); d.setDate(d.getDate()+delta); return d.toLocaleDateString("en-CA"); }
function flash(msg){ let t=document.getElementById("toast"); if(!t){ t=document.createElement("div"); t.id="toast"; t.setAttribute("role","status"); t.setAttribute("aria-live","polite"); t.style.cssText="position:fixed;left:50%;bottom:24px;transform:translateX(-50%);background:var(--bad);color:#fff;padding:10px 16px;border-radius:8px;z-index:99;font-weight:600"; document.body.appendChild(t); } t.textContent=msg; t.style.display="block"; }
/* ===================================== ACTIVITY LOG (audit trail) =====================================
One durable stream of every meaningful action the POS takes — orders, money, overrides, voids, refunds,
discounts, ID checks, stock changes, staff clock events, station access. NOT literal keystrokes (noise +
privacy); the theft-relevant events, each attributed to a station, the acting staff (when one person is
clocked in), and a timestamp. Owner-facing, exportable, capped so localStorage never runs away.
Categories: order · money · override · void · refund · discount · idcheck · stock · clock · access · admin. */
const ACT_CAT = { order:"money", money:"money", refund:"money", discount:"money", override:"override", void:"override", idcheck:"access", clock:"access", access:"access", stock:"admin", admin:"admin" };
function actingStaff(){ try{ const on=(FLOW.staff||[]).filter(s=>openPunch(s.id)); return on.length===1?on[0].name:(on.length>1?"(multiple on shift)":""); }catch(e){ return ""; } }
function logActivity(type, detail, orderNo, amt){
try{ DB=DB||loadDB(); DB.activity=DB.activity||[];
const st=(typeof boundStation==="function")?boundStation():null;
DB.activity.push({ ts:Date.now(), at:new Date().toISOString().slice(11,16), day:todayStr(), type, detail:detail||"", order:(orderNo!=null?orderNo:null), amt:(amt!=null?+(+amt).toFixed(2):null), station:(st&&st.label)||"", staff:actingStaff() });
if(DB.activity.length>3000) DB.activity=DB.activity.slice(-3000); // keep the most recent 3000 events
saveDB(DB);
}catch(e){}
}
function activityCSV(day){ const rows=[["time","type","detail","amount","order","station","staff"]];
(loadDB().activity||[]).filter(a=>!day||a.day===day).forEach(a=>rows.push([a.at, a.type, a.detail, a.amt==null?"":a.amt, a.order==null?"":("#"+a.order), a.station, a.staff]));
return csvRows(rows); }
// data ownership: your data is yours to take out. Everything below builds plain files from the local DB.
/* ===================================== DATA & BACKUP ===================================== */
function downloadFile(name, text, type){ const blob=new Blob([text],{type:type||"text/plain"}); const url=URL.createObjectURL(blob); const a=document.createElement("a"); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(()=>URL.revokeObjectURL(url),1000); }
function csvCell(v){ v=(v==null?"":String(v)); return /[",\n]/.test(v) ? '"'+v.replace(/"/g,'""')+'"' : v; }
function csvRows(rows){ return rows.map(r=>r.map(csvCell).join(",")).join("\n"); }
function backupJSON(){ return JSON.stringify({ app:"customPOS", flowId:flowId(), exportedAt:new Date().toISOString(), data:loadDB() }, null, 2); }
function customersCSV(){ const cs=(loadDB().customers||[]); return csvRows([["name","phone","points","gift","balance"], ...cs.map(c=>[c.name||"",c.phone||"",c.points||0,c.gift||0,c.balance||0])]); }
function salesCSV(day){ const d=loadDB(); const done=d.records.filter(r=>(r.status==="PAID"||r.status==="CLOSED"||r.status==="REFUNDED") && dayOf(r.ts)===day);
return csvRows([["order","time","status","items","subtotal","discount","tax","tip","total","tenders"],
...done.map(r=>[r.number, r.createdAt||"", r.status, r.lines.map(l=>l.qty+"x "+l.name).join("; "), lineSubtotal(r).toFixed(2), recordDiscount(r).toFixed(2), recordTax(r).toFixed(2), (r.tip||0).toFixed(2), recordTotal(r).toFixed(2), (r.tenders||[]).map(t=>t.type+":"+t.amount).join("; ")])]); }
function catalogCSV(){ return csvRows([["name","price","category","barcode","taxable","on_hand","reorder_at"],
...FLOW.catalog.map(i=>[i.name, i.price, i.category||"", i.barcode||"", i.taxable!==false, tracksStock(i)?stockOnHand(i):"", i.reorderAt!=null?i.reorderAt:""])]); }
function importCustomersCSV(text){ const rows=(text||"").split(/\r?\n/).map(r=>r.trim()).filter(Boolean); const d=loadDB(); const byPhone=new Map((d.customers||[]).map(c=>[c.phone,c])); let n=0;
rows.forEach((row,i)=>{ const c=row.split(",").map(s=>s.trim()); if(i===0 && /name/i.test(c[0]) && /phone/i.test(c[1]||"")) return; const phone=c[1]; if(!phone) return;
const cust=byPhone.get(phone)||{phone}; cust.name=c[0]||cust.name; if(c[2]!==undefined&&c[2]!=="") cust.points=Number(c[2])||0; if(c[3]!==undefined&&c[3]!=="") cust.gift=Number(c[3])||0; if(c[4]!==undefined&&c[4]!=="") cust.balance=Number(c[4])||0; byPhone.set(phone,cust); n++; });
d.customers=[...byPhone.values()]; saveDB(d); return n; }
function slug(){ return (FLOW.branding.name||"custompos").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""); }
function restoreBackup(text){ const obj=JSON.parse(text); const db=obj&&obj.data?obj.data:obj; if(!db||!Array.isArray(db.records)) throw new Error("not a customPOS backup"); persistDB(db); }
// install-as-app: brand the manifest + theme with the business so "Add to Home Screen" shows the shop's name/color
let __installReady=false;
function setupInstall(){
if(__installReady) return; __installReady=true;
const name=FLOW.branding.name||"customPOS", color=FLOW.branding.brandColor||"#1f6feb";
const tc=document.getElementById("themeColor"); if(tc) tc.content=color;
const at=document.createElement("meta"); at.name="apple-mobile-web-app-title"; at.content=name; document.head.appendChild(at);
const letter=(name.trim()[0]||"C").toUpperCase();
const svg="<svg xmlns='http://www.w3.org/2000/svg' width='512' height='512'><rect width='512' height='512' rx='96' fill='"+color+"'/><text x='256' y='352' font-family='sans-serif' font-size='300' font-weight='bold' fill='#fff' text-anchor='middle'>"+letter+"</text></svg>";
const icon="data:image/svg+xml,"+encodeURIComponent(svg);
const manifest={ name, short_name:name.slice(0,12), display:"standalone", start_url:".", background_color:"#0f1115", theme_color:color, icons:[{src:icon, sizes:"any", type:"image/svg+xml"}] };
const link=document.createElement("link"); link.rel="manifest"; link.href=URL.createObjectURL(new Blob([JSON.stringify(manifest)],{type:"application/manifest+json"})); document.head.appendChild(link);
const ai=document.createElement("link"); ai.rel="apple-touch-icon"; ai.href=icon; document.head.appendChild(ai);
}
// brand color → the whole accent; a light brand gets dark ink for contrast (WCAG-ish luminance test)
function hexToRgb(h){ h=(h||"").replace('#',''); if(h.length===3) h=h.split('').map(c=>c+c).join(''); const n=parseInt(h,16); return isNaN(n)?null:[(n>>16)&255,(n>>8)&255,n&255]; }
function readableInk(hex){ const c=hexToRgb(hex); if(!c) return "#ffffff"; const L=(0.299*c[0]+0.587*c[1]+0.114*c[2])/255; return L>0.62?"#111418":"#ffffff"; }
function applyBranding(){
const color=FLOW.branding.brandColor||"#1f6feb"; const rs=document.documentElement.style;
rs.setProperty('--brand', color); rs.setProperty('--brand-ink', readableInk(color));
const c=hexToRgb(color); if(c) rs.setProperty('--brand-tint','rgba('+c[0]+','+c[1]+','+c[2]+',.13)');
const logo=FLOW.branding.logo, li=document.getElementById('brandLogo'), dot=document.getElementById('brandDot');
if(logo){ li.src=logo; li.style.display='block'; dot.style.display='none'; }
else { li.style.display='none'; dot.style.display='inline-flex'; dot.style.background=color; dot.textContent=((FLOW.branding.name||'C').trim()[0]||'C').toUpperCase(); }
document.getElementById("bizName").textContent = FLOW.branding.name;
}
function render(){
DB = loadDB();
setupInstall();
applyBranding();
const station = boundStation();
document.getElementById("stationLabel").textContent = station ? "· "+station.label : "";
const chg = document.getElementById("changeStation"); chg.style.display = station ? "" : "none"; chg.onclick = unbind;
const app = document.getElementById("app"); app.innerHTML = "";
if(!station){ renderPicker(app); return; }
if(station.type==="intake") renderIntake(app, station);
else if(station.type==="production" || station.type==="staging") renderPipeline(app, station);
else if(station.type==="fulfillment") renderCheckout(app, station);
else if(station.type==="central"){ renderIntake(app, station); renderCheckout(app, station); }
else if(station.type==="board") renderBoard(app, station);
else if(station.type==="tracker") renderTracker(app, station);
else if(station.type==="report") renderReport(app, station);
else if(station.type==="detail") renderDetail(app, station);
else if(station.type==="route") renderRoute(app, station);
else if(station.type==="timeclock") renderTimeclock(app, station);
else if(station.type==="booking") renderBooking(app, station);
else if(station.type==="kds") renderKDS(app, station);
else if(station.type==="floor") renderFloor(app, station);
else if(station.type==="schedule") renderSchedule(app, station);
else if(station.type==="worker") renderWorker(app, station);
}
/* TIP POOLING — pooled tips shared fairly by hours worked (opt-in). Helps tipped hourly staff split evenly.
On when FLOW.endpoints.payment.tipPool (or .tip.pool). Distribution is by each worker's recorded hours. */
function tipPoolOn(){ const pay=FLOW.endpoints&&FLOW.endpoints.payment; return !!(pay && (pay.tipPool || (pay.tip&&pay.tip.pool))); }
function poolHours(){ const by={}; let tot=0; (DB.punches||[]).forEach(pn=>{ const h=workedMs(pn)/3600000; by[pn.name]=(by[pn.name]||0)+h; tot+=h; }); return {by, tot}; }
function tipsForDay(day){ return DB.records.filter(r=>(r.status==="PAID"||r.status==="CLOSED") && dayOf(r.ts)===day).reduce((s,r)=>s+(r.tip||0),0); }
function tipShareFor(name, day){ const t=tipsForDay(day); const {by,tot}=poolHours(); return (!tot||!t)?0:t*(by[name]||0)/tot; }
/* WIN-BACK — regulars we haven't seen in a while. Bringing a lapsed customer back is cheaper than finding a new
one; this surfaces them so the owner can invite them in one tap (over the notify seam). */
function winbackDays(){ return (FLOW.endpoints && FLOW.endpoints.winback && +FLOW.endpoints.winback.days) || 30; }
function customerLastVisit(phone){ let mx=0; DB.records.forEach(r=>{ if(r.customer && r.customer.phone===phone && (r.ts||0)>mx) mx=r.ts; }); return mx; }
function lapsedCustomers(){ const cut=Date.now()-winbackDays()*86400000; return (DB.customers||[]).map(c=>({c, last:customerLastVisit(c.phone)})).filter(x=>x.last>0 && x.last<cut).sort((a,b)=>a.last-b.last); }
/* COMMISSION & TIPS report — money-math primitive: per-performer service sales, commission %, tips */
/* ===================================== ROLES + MONEY-GATE (optional) =====================================
Money-reversing / discretionary actions (refund, return) can require a manager/owner approval. Opt-in via
FLOW.endpoints.approvals = { refund:true } together with FLOW.staff roles (role "owner"|"manager" may
approve). Inert when unconfigured — a shop with no approver roles keeps the plain actions. The approver
enters their PIN at the moment of the action; every approval is written to an audit log (DB.approvals).
Generalizes "staff requests, owner approves" — the anti-theft gate — with no per-trade code. */
function approvers(){ return (FLOW.staff||[]).filter(s=> s.role==="owner" || s.role==="manager"); }
function needsApproval(action){ return !!(FLOW.endpoints && FLOW.endpoints.approvals && FLOW.endpoints.approvals[action]) && approvers().length>0; }
async function withApproval(action, label, fn){
if(!needsApproval(action)){ fn(null); render(); return; }
const waiting = stationWaiting(); if(waiting){ flash(waiting); return; }
const pin = prompt(label + "\nEnter a manager/owner PIN to approve this " + action + ":");
if(pin==null) return; // cancelled — no change
const who = await pinOwner(pin, s=> s.role==="owner" || s.role==="manager"); // the setup's PINs on one computer; the hub's PIN hashes on several (the download carries no PINs)
if(!who){ flash("Not authorized — a manager or owner PIN is required"); return; }
fn(who);
DB=loadDB(); DB.approvals=DB.approvals||[]; DB.approvals.push({ action, label, by:who.name, at:new Date().toISOString().slice(11,16), ts:Date.now() }); saveDB(DB);
logActivity("admin", action+" approved — "+(label||"")+" (by "+who.name+")");
render();
}
/* EXPENSES — the other half of the money story. Sales, cost-of-goods and labor were already captured; this
adds the overhead an owner actually pays (supplies, rent, utilities…) so the report goes all the way to NET
profit instead of stopping at gross margin. Append-only + void (never a hard delete, per the house rule),
and every entry lands on the activity log like any other money edit. NOTE: entered on the office/report
station; syncing the expense ledger across stations is a follow-up (the hub syncs orders + customers today). */
const EXPENSE_CATS=["supplies","rent","utilities","equipment","fees","other"];
function expenseCats(){ return (FLOW.expenses&&FLOW.expenses.categories)||EXPENSE_CATS; }
function dayExpenses(day){ return (DB.expenses||[]).filter(e=>!e.void && e.day===day); }
function dayExpenseTotal(day){ return dayExpenses(day).reduce((s,e)=>s+(+e.amount||0),0); }
function addExpense(amount, category, vendor, note){
amount=+amount; if(!(amount>0)) return false;
DB=loadDB(); DB.expenses=DB.expenses||[];
DB.expenses.push({ id:"E"+Date.now(), ts:Date.now(), day:todayStr(), category:category||"other", vendor:(vendor||"").trim(), note:(note||"").trim(), amount:+amount.toFixed(2), emp:(typeof actingStaff==="function"?actingStaff():"") });
logActivity("money", "expense · "+(category||"other")+((vendor||"").trim()?" · "+vendor.trim():""), null, amount);
saveDB(DB); return true;
}
function voidExpense(id){ DB=loadDB(); const e=(DB.expenses||[]).find(x=>x.id===id); if(e && !e.void){ e.void=true; logActivity("money", "voided expense · "+(e.category||"other"), null, e.amount); saveDB(DB); } }
// labor cost for a day, from the punch clock × each person's wage (the same basis the day verdict uses)
function dayLaborCost(){ let c=0; (DB.punches||[]).forEach(pn=>{ c += (workedMs(pn)/3600000)*((pn.wage!=null?pn.wage:staffWage(pn.staffId))||0); }); return c; }
function renderReport(app, station){
const day = reportDay || todayStr(); const isToday = day===todayStr();
app.innerHTML="<h2>"+station.label+" — "+(isToday?"today":day)+"</h2>";
// day navigation — the report defaults to today but you can page back through history
const nav=document.createElement("div"); nav.className="row"; nav.style.margin="0 0 10px";
const prev=document.createElement("button"); prev.textContent="← "+shiftDay(day,-1); prev.onclick=()=>{ reportDay=shiftDay(day,-1); render(); }; nav.appendChild(prev);
const dp=document.createElement("input"); dp.type="date"; dp.value=day; dp.style.margin="0 8px"; dp.max=todayStr(); dp.onchange=e=>{ reportDay = e.target.value||todayStr(); render(); }; nav.appendChild(dp);
if(!isToday){ const next=document.createElement("button"); next.textContent=shiftDay(day,1)+" →"; next.onclick=()=>{ reportDay=shiftDay(day,1); if(reportDay===todayStr()) reportDay=null; render(); }; nav.appendChild(next);
const tb=document.createElement("button"); tb.textContent="Today"; tb.style.marginLeft="8px"; tb.onclick=()=>{ reportDay=null; render(); }; nav.appendChild(tb); }
app.appendChild(nav);
// ---- ⚙️ Business settings — tax, tips, name, labor target, editable live (collapsed by default) ----
if(isToday && station.view && station.view.money){
const t=FLOW.endpoints.tax||{}; const tip=(FLOW.endpoints.payment&&FLOW.endpoints.payment.tip)||{};
const det=document.createElement("details"); det.className="card"; det.style.padding="0 14px";
const sm=document.createElement("summary"); sm.style.cssText="cursor:pointer;padding:12px 0;font-weight:600"; sm.textContent="⚙️ Business settings — logo, brand color, tax, tips"; det.appendChild(sm);
const grid=document.createElement("div"); grid.style.cssText="padding:0 0 12px";
const field=(label,el)=>{ const w=document.createElement("div"); w.className="fld"; w.style.margin="6px 0"; const l=document.createElement("span"); l.className="flab"; l.textContent=label; l.style.cssText="display:inline-block;min-width:190px;color:var(--dim)"; w.appendChild(l); w.appendChild(el); grid.appendChild(w); return el; };
// ---- MAKE IT YOURS (first) — a shop's logo + brand color, so the whole app looks like THEIR brand ----
const hd=document.createElement("div"); hd.style.cssText="font-weight:700;margin:2px 0 4px"; hd.textContent="Make it yours"; grid.appendChild(hd);
const hint=document.createElement("div"); hint.className="muted"; hint.style.cssText="font-size:13px;margin:0 0 8px"; hint.textContent="Add your logo and pick your color — the counter, buttons and receipts pick it up instantly."; grid.appendChild(hint);
let logoData = FLOW.branding.logo||null;
const logoRow=document.createElement("div"); logoRow.className="fld"; logoRow.style.margin="6px 0";
const logoLab=document.createElement("span"); logoLab.className="flab"; logoLab.textContent="Logo"; logoLab.style.cssText="display:inline-block;min-width:190px;color:var(--dim)"; logoRow.appendChild(logoLab);
const prev=document.createElement("img"); prev.style.cssText="height:34px;max-width:120px;border-radius:6px;object-fit:contain;border:1px solid var(--line)"+(logoData?"":";display:none"); if(logoData) prev.src=logoData; logoRow.appendChild(prev);
const file=document.createElement("input"); file.type="file"; file.accept="image/*"; file.style.margin="0 0 0 8px";
file.onchange=()=>{ const f=file.files&&file.files[0]; if(!f) return; if(f.size>600000){ flash("Logo too big — use one under ~500KB"); file.value=""; return; } const rd=new FileReader(); rd.onload=()=>{ logoData=rd.result; prev.src=logoData; prev.style.display=""; }; rd.readAsDataURL(f); };
logoRow.appendChild(file);
const rm=document.createElement("button"); rm.textContent="Remove"; rm.style.margin="0 0 0 8px"; rm.onclick=()=>{ logoData=null; prev.style.display="none"; file.value=""; }; logoRow.appendChild(rm);
grid.appendChild(logoRow);
const color=document.createElement("input"); color.type="color"; color.value=FLOW.branding.brandColor||"#1f6feb"; field("Brand color", color);
const biz=document.createElement("input"); biz.type="text"; biz.value=FLOW.branding.name||""; biz.style.width="200px"; field("Business name", biz);
const rate=document.createElement("input"); rate.type="number"; rate.step="0.01"; rate.value=((+t.rate||0)*100).toFixed(2); rate.style.width="90px"; field("Sales tax rate (%)", rate);
const incl=document.createElement("input"); incl.type="checkbox"; incl.checked=!!t.included; field("Tax included in prices", incl);
const tips=document.createElement("input"); tips.type="text"; tips.value=(tip.presets||[]).join(", "); tips.placeholder="15, 18, 20"; tips.style.width="120px"; field("Tip presets (%)", tips);
const lab=document.createElement("input"); lab.type="number"; lab.value=(FLOW.labor&&FLOW.labor.targetLaborPct)||""; lab.placeholder="28"; lab.style.width="90px"; field("Target labor (% of sales)", lab);
const save=document.createElement("button"); save.className="primary"; save.textContent="Save settings"; save.style.marginTop="8px";
save.onclick=()=>{ const presets=tips.value.split(",").map(x=>+x.trim()).filter(x=>x>0);
saveSettings({ bizName:(biz.value||"").trim()||FLOW.branding.name,
brandColor:color.value, logo:logoData,
tax:{ rate:Math.max(0,(+rate.value||0)/100), included:!!incl.checked },
tipPresets:presets.length?presets:undefined,
targetLaborPct: lab.value!==""?+lab.value:undefined });
flash("Settings saved"); render(); };
grid.appendChild(save); det.appendChild(grid); app.appendChild(det);
}
const dayAll=DB.records.filter(r=>(r.status==="PAID"||r.status==="CLOSED"||r.status==="REFUNDED") && dayOf(r.ts)===day);
// multi-store: scope the whole report to one store, with an all-stores roll-up when viewing "All"
if(storesOn()){
const chips=document.createElement("div"); chips.className="opts"; chips.style.margin="0 0 10px";
const mk=(id,label)=>{ const b=document.createElement("button"); if((reportStore||"")===(id||"")) b.className="sel"; b.textContent=label; b.onclick=()=>{ reportStore=id; render(); }; chips.appendChild(b); };
mk(null,"All stores"); storeList().forEach(s=>mk(s.id, s.name)); app.appendChild(chips);
if(!reportStore){ // roll-up: net sales + orders per store (only when more than one store rang today)
const per={}; dayAll.filter(r=>r.status!=="REFUNDED").forEach(r=>{ const sid=r.storeId||"—"; const allSub=lineSubtotal(r), frac=allSub>0?(allSub-returnedSubtotal(r))/allSub:1; per[sid]=per[sid]||{net:0,orders:0}; per[sid].net+=recordNet(r)*frac; per[sid].orders++; });
const ids=Object.keys(per);
if(ids.length>1){ const rc=document.createElement("div"); rc.className="card"; rc.innerHTML="<div class='row'><b>By store</b> <span class='muted'>net sales "+(isToday?"today":day)+"</span></div>";
let tot=0, to=0; ids.sort((a,b)=>per[b].net-per[a].net).forEach(sid=>{ tot+=per[sid].net; to+=per[sid].orders; const row=document.createElement("div"); row.className="line"; row.innerHTML="<span>🏬 "+(storeName(sid)||sid)+" <span class='muted'>· "+per[sid].orders+" order(s)</span></span><span class='spacer'></span><span>"+money(per[sid].net)+"</span>"; rc.appendChild(row); });
const t=document.createElement("div"); t.className="line"; t.innerHTML="<b>All stores</b> <span class='muted'>· "+to+" order(s)</span><span class='spacer'></span><b>"+money(tot)+"</b>"; rc.appendChild(t); app.appendChild(rc); }
}
}
const done = (storesOn() && reportStore) ? dayAll.filter(r=>r.storeId===reportStore) : dayAll;
const L=(lab,val,bold)=>"<div class='line'>"+(bold?"<b>":"<span>")+lab+(bold?"</b>":"</span>")+"<span class='spacer'></span>"+(bold?"<b>":"<span>")+val+(bold?"</b>":"</span>")+"</div>";
// ---- daily sales summary (refund-aware: a refunded order's sale nets out, its reversed tender nets its tenders) ----
let net=0, tax=0, tips=0, disc=0, items=0, refunds=0, orders=0, cogs=0, roundUp=0; const byTender={}, byCat={}, byItem={}, byHour={};
const itemCost=(l)=>{ const it=FLOW.catalog.find(i=>i.id===l.catId); return (it&&+it.cost)||0; };
done.forEach(r=>{ const rf=r.status==="REFUNDED";
if(rf){ refunds += recordTotal(r); }
else { orders++;
const allSub=lineSubtotal(r), frac = allSub>0 ? (allSub-returnedSubtotal(r))/allSub : 1; // proportion still sold (line-level returns)
net += recordNet(r)*frac; tax += recordTax(r)*frac; tips += r.tip||0; disc += recordDiscount(r)*frac; roundUp += r.roundUp||0;
if(r.ts){ const hr=new Date(r.ts).getHours(); byHour[hr]=(byHour[hr]||0)+recordNet(r)*frac; }
r.lines.filter(l=>!l.returned).forEach(l=>{ items += l.qty; cogs += itemCost(l)*l.qty; byCat[l.category||"other"]=(byCat[l.category||"other"]||0)+l.price*l.qty;
const bi=byItem[l.name]=byItem[l.name]||{qty:0,rev:0,cost:0}; bi.qty+=l.qty; bi.rev+=l.price*l.qty; bi.cost+=itemCost(l)*l.qty; });
const ret = -((r.tenders||[]).filter(t=>t.refund).reduce((s,t)=>s+t.amount,0)); if(ret>0.0001) refunds += ret; // partial line returns
}
(r.tenders||[]).forEach(t=>{ byTender[t.type]=(byTender[t.type]||0)+t.amount; }); // refund pushes offsetting negative tenders, so this nets
});
const onAccount=byTender.account||0; // charged to house accounts today — money owed, not money collected
const collected=Object.keys(byTender).filter(k=>k!=="account").reduce((s,k)=>s+byTender[k],0);
// ---- "how today went": one plain-language verdict fusing sales, margin, and labor — the first thing an owner sees ----
if(isToday && (orders||refunds)){
const laborCost=dayLaborCost();
const haveCost=FLOW.catalog.some(i=>+i.cost>0); const marginPct = (haveCost&&net>0)? (net-cogs)/net*100 : null;
const laborPct = (laborCost>0&&net>0)? laborCost/net*100 : null;
const opEx=dayExpenseTotal(day); const netProfit = net - (haveCost?cogs:0) - laborCost - opEx; // full picture: down to net
const target=(FLOW.labor&&FLOW.labor.targetLaborPct)||30;
const concerns=[]; if(laborPct!=null && laborPct>target+10) concerns.push("labor is running high"); if(marginPct!=null && marginPct<20) concerns.push("margins are thin"); if(refunds>collected*0.15 && refunds>0) concerns.push("lots of refunds"); if(netProfit<0 && (opEx>0||laborCost>0)) concerns.push("spending outran sales");
const good = !concerns.length && net>0;
const verdict = net<=0 ? "Quiet so far today." : good ? "Solid day." : "Worth a look — "+concerns.join(", ")+".";
const bits=[money(collected)+" in"]; if(marginPct!=null) bits.push(marginPct.toFixed(0)+"% margin"); if(laborPct!=null) bits.push("labor "+laborPct.toFixed(0)+"% of sales"); if(opEx>0||laborCost>0) bits.push((netProfit>=0?"+":"−")+money(Math.abs(netProfit))+" net");
const hd=document.createElement("div"); hd.className="card"; hd.style.cssText="border-left:4px solid "+(net<=0?"var(--line)":good?"var(--good,#2ea043)":"var(--warn,#c99a12)")+";padding-left:14px";
hd.innerHTML="<div style='font-size:18px;font-weight:700'>"+verdict+"</div><div class='muted' style='margin-top:2px'>"+bits.join(" · ")+"</div>";
app.appendChild(hd);
}
const sum=document.createElement("div"); sum.className="card";
sum.innerHTML="<div class='row'><b>Sales summary</b></div>"
+ L("Orders", String(orders)) + L("Items sold", String(items))
+ L("Net sales", money(net)) + (disc?L("Discounts","−"+money(disc)):"") + L("Tax collected", money(tax)) + (tips?L("Tips", money(tips)):"") + (refunds?L("Refunds","−"+money(refunds)):"")
+ L("Total collected", money(collected), true) + (onAccount?L("On account (A/R)", money(onAccount)):"");
app.appendChild(sum);
// ---- community: charity round-ups collected today (only when the round-up option is on) ----
if(FLOW.endpoints.payment.roundUp && roundUp>0){ const cause=(FLOW.endpoints.payment.roundUp.cause)||"a local cause";
const cc=document.createElement("div"); cc.className="card"; cc.innerHTML="<div class='row'><b>Community ♥</b></div>"+L("Rounded up for "+cause, money(roundUp), true)+"<div class='muted' style='margin-top:2px'>Collected from customers who chose to round up — set it aside to donate.</div>";
app.appendChild(cc);
}
// ---- gross margin: what's left after the cost of what you sold (only when items carry a cost) ----
if(FLOW.catalog.some(i=>+i.cost>0) && net>0){ const gross=net-cogs; const margin=gross/net*100;
const pc=document.createElement("div"); pc.className="card";
pc.innerHTML="<div class='row'><b>Gross margin</b></div>"+L("Net sales", money(net))+L("Cost of goods","−"+money(cogs))+L("Gross profit", money(gross), true)
+"<div class='line'><span>Margin</span><span class='spacer'></span><span"+(margin<0?" style='color:var(--bad);font-weight:600'":"")+">"+margin.toFixed(0)+"%</span></div>"
+"<div class='muted' style='margin-top:2px'>"+(margin<0?"You're selling below cost today — check pricing or waste.":"What's left to cover rent, labor, and everything else.")+"</div>";
app.appendChild(pc);
}
// ---- expenses: the overhead behind the counter (supplies, rent, utilities…), so the picture reaches NET profit ----
const exList=dayExpenses(day), exTotal=dayExpenseTotal(day); const byExCat={}; exList.forEach(e=>{ byExCat[e.category||"other"]=(byExCat[e.category||"other"]||0)+(+e.amount||0); });
const ex=document.createElement("div"); ex.className="card";
const exHead=document.createElement("div"); exHead.innerHTML="<div class='row'><b>Expenses</b><span class='spacer'></span><span class='muted'>"+(isToday?"today":day)+"</span></div>"; ex.appendChild(exHead);
if(isToday){ // entry form (built as DOM so its Add handler survives — never rebuild the card via innerHTML+= after this)
const form=document.createElement("div"); form.className="row"; form.style.cssText="gap:6px;flex-wrap:wrap;margin:4px 0 8px";
const amt=document.createElement("input"); amt.type="number"; amt.placeholder="$ amount"; amt.style.width="120px";
const cat=document.createElement("select"); expenseCats().forEach(c=>{ const o=document.createElement("option"); o.value=c; o.textContent=c[0].toUpperCase()+c.slice(1); cat.appendChild(o); });
const ven=document.createElement("input"); ven.type="text"; ven.placeholder="vendor / note"; ven.style.minWidth="140px";
const add=document.createElement("button"); add.className="primary"; add.textContent="Add"; add.onclick=()=>{ if(addExpense(amt.value, cat.value, ven.value, "")) render(); else flash("Enter an amount"); };
[amt,cat,ven,add].forEach(el=>form.appendChild(el)); ex.appendChild(form);
}
if(exList.length){
const sumBox=document.createElement("div"); let sh="";
Object.keys(byExCat).sort((a,b)=>byExCat[b]-byExCat[a]).forEach(k=>{ sh+=L(k[0].toUpperCase()+k.slice(1),"−"+money(byExCat[k])); });
sh+=L("Total expenses","−"+money(exTotal), true); sumBox.innerHTML=sh; ex.appendChild(sumBox);
const det=document.createElement("div"); det.style.marginTop="6px";
exList.slice().sort((a,b)=>b.ts-a.ts).forEach(e=>{ const row=document.createElement("div"); row.className="line"; row.style.fontSize="13px";
row.innerHTML="<span class='muted'>"+(e.category||"other")+(e.vendor?" · "+e.vendor:"")+"</span><span class='spacer'></span><span>"+money(e.amount)+"</span>";
if(isToday){ const v=document.createElement("button"); v.textContent="void"; v.className="link"; v.style.marginLeft="8px"; v.onclick=()=>{ voidExpense(e.id); render(); }; row.appendChild(v); }
det.appendChild(row); });
ex.appendChild(det);
} else { const none=document.createElement("div"); none.className="muted"; none.textContent="No expenses recorded"+(isToday?" yet — add supplies, rent, utilities as you pay them.":" that day."); ex.appendChild(none); }
app.appendChild(ex);
// ---- bottom line: the whole money story in one card — revenue all the way down to net profit (an estimate) ----
if(net>0 || exTotal>0){
const laborCost=dayLaborCost(); const haveCost=FLOW.catalog.some(i=>+i.cost>0);
const gross=net-(haveCost?cogs:0); const netProfit=gross-laborCost-exTotal;
const col=netProfit>=0?"var(--good,#2ea043)":"var(--bad,#e5484d)";
const bl=document.createElement("div"); bl.className="card"; bl.style.cssText="border-left:4px solid "+col+";padding-left:14px";
bl.innerHTML="<div class='row'><b>Bottom line</b><span class='spacer'></span><span class='muted'>"+(isToday?"today":day)+" · estimate</span></div>"
+L("Net sales", money(net))
+(haveCost?L("Cost of goods","−"+money(cogs)):"")
+L("Gross profit", money(gross))
+(laborCost>0?L("Labor","−"+money(laborCost)):"")
+(exTotal>0?L("Operating expenses","−"+money(exTotal)):"")
+"<div class='line' style='border-top:1px solid var(--line);margin-top:4px;padding-top:6px'><b>Net profit</b><span class='spacer'></span><b style='color:"+col+"'>"+(netProfit<0?"−"+money(-netProfit):money(netProfit))+"</b></div>"
+"<div class='muted' style='margin-top:2px'>"+(netProfit>=0?"What the business kept after goods, labor and overhead.":"Spent more than it made "+(isToday?"today":"that day")+" — check labor and expenses.")+(laborCost>0?"":" Clock staff in with wages set to include labor.")+"</div>";
app.appendChild(bl);
}
if(Object.keys(byTender).length){ const tc=document.createElement("div"); tc.className="card"; tc.innerHTML="<div class='row'><b>By tender</b></div>"+Object.keys(byTender).map(k=>L(k[0].toUpperCase()+k.slice(1), money(byTender[k]))).join(""); app.appendChild(tc); }
if(Object.keys(byCat).length){ const cc=document.createElement("div"); cc.className="card"; cc.innerHTML="<div class='row'><b>By category</b></div>"+Object.keys(byCat).sort((a,b)=>byCat[b]-byCat[a]).map(k=>L(k, money(byCat[k]))).join(""); app.appendChild(cc); }
// ---- top items: your best sellers by revenue, with per-item margin when costs are known (push winners, cut losers) ----
const itemNames=Object.keys(byItem);
if(itemNames.length){ const haveCost=FLOW.catalog.some(i=>+i.cost>0);
const top=itemNames.sort((a,b)=>byItem[b].rev-byItem[a].rev).slice(0,8);
const ti=document.createElement("div"); ti.className="card"; ti.innerHTML="<div class='row'><b>Top items</b><span class='spacer'></span><span class='muted'>by sales"+(haveCost?" · margin":"")+"</span></div>";
top.forEach(n=>{ const bi=byItem[n]; const m=(haveCost && bi.rev>0)?Math.round((bi.rev-bi.cost)/bi.rev*100):null;
ti.innerHTML+="<div class='line'><span>"+n+" <small class='muted'>×"+bi.qty+"</small></span><span class='spacer'></span><span>"+money(bi.rev)+(m!=null?" <small class='muted'>· "+m+"%</small>":"")+"</span></div>"; });
app.appendChild(ti);
}
// ---- busy hours: when the money actually comes in, so staffing can match demand ----
const hrs=Object.keys(byHour).map(Number).sort((a,b)=>a-b);
if(hrs.length){ const mx=Math.max(...hrs.map(h=>byHour[h]));
const fmtHr=h=>{ const ap=h<12?"a":"p"; const h12=(h%12)||12; return h12+ap; };
const bh=document.createElement("div"); bh.className="card"; bh.innerHTML="<div class='row'><b>Busy hours</b><span class='spacer'></span><span class='muted'>net sales by hour</span></div>";
hrs.forEach(h=>{ const v=byHour[h]; const blocks=mx>0?Math.max(1,Math.round(v/mx*16)):0;
bh.innerHTML+="<div class='line'><span style='width:42px;display:inline-block'>"+fmtHr(h)+"</span><span style='font-family:monospace;letter-spacing:-1px;color:var(--brand,#2f7bd6)'>"+"▇".repeat(blocks)+"</span><span class='spacer'></span><span class='muted'>"+money(v)+"</span></div>"; });
const busiest=hrs.reduce((a,h)=>byHour[h]>byHour[a]?h:a, hrs[0]);