Subversion Repositories SmartDukaan

Rev

Rev 37020 | Rev 37032 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
36877 vikas 1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="utf-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1">
6
<title>Beat Journey</title>
7
<style>
8
  :root{
9
    --bg:#eef1f7; --card:#ffffff; --ink:#1d2433; --muted:#69748c; --soft:#97a1b5;
10
    --line:#e6e9f1; --line2:#eef1f6;
11
    --brand:#3b5bdb; --brand2:#5c7cfa; --teal:#0ca678; --cyan:#1098ad;
12
    --amber:#f59f00; --orange:#e8590c; --red:#e03131; --violet:#7048e8; --pink:#d6336c;
13
    --good:#2f9e44; --warn:#f08c00; --bad:#e03131;
14
  }
15
  *{box-sizing:border-box}
16
  html,body{margin:0;background:var(--bg);color:var(--ink);
17
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;font-size:14px}
18
  .wrap{max-width:1320px;margin:0 auto;padding:20px 24px 90px}
19
  a{color:var(--brand)}
20
  header.top{display:flex;align-items:center;justify-content:space-between;gap:18px;flex-wrap:wrap;margin-bottom:16px}
21
  .brand .crumb{font-size:12px;color:var(--soft);font-weight:600}
22
  .brand h1{margin:3px 0 0;font-size:23px;font-weight:740;letter-spacing:-.01em}
23
  .brand h1 .live{font-size:11px;font-weight:700;color:var(--teal);background:#e6fcf5;border:1px solid #c3fae8;border-radius:999px;padding:3px 9px;vertical-align:middle;margin-left:10px}
24
  .brand h1 .live i{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--teal);margin-right:5px;animation:pulse 1.6s infinite}
25
  @keyframes pulse{0%,100%{opacity:1}50%{opacity:.25}}
26
  .hd-right{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
27
  .ctl{background:var(--card);border:1px solid var(--line);border-radius:9px;padding:8px 12px;font-size:13px;color:var(--ink);font-weight:600}
28
  .ctl .lbl{color:var(--soft);font-weight:500;margin-right:5px}
29
  select.ctl,input.ctl{appearance:none;cursor:pointer;height:36px}
30
  input.ctl{cursor:auto}
31
  .btn-r{background:var(--brand);border:0;color:#fff;font-weight:650;padding:9px 15px;border-radius:9px;cursor:pointer;font-size:13px;height:36px}
32
  .lenses{display:flex;gap:4px;border-bottom:1px solid var(--line);margin-bottom:20px}
33
  .lens{padding:11px 4px;margin-right:22px;font-size:14px;font-weight:650;color:var(--muted);cursor:pointer;border:0;background:transparent;border-bottom:2.5px solid transparent;margin-bottom:-1px}
34
  .lens.active{color:var(--brand);border-bottom-color:var(--brand)}
35
  .lens .b{display:inline-block;background:#eef1fb;color:var(--brand);font-size:11px;font-weight:700;border-radius:999px;padding:1px 7px;margin-left:6px}
36917 vikas 36
  .kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px}
36929 vikas 37
  .kpi{background:var(--card);border:1px solid var(--line);border-radius:13px;padding:14px 15px;box-shadow:0 1px 2px rgba(20,30,60,.04);display:flex;flex-direction:column}
36905 vikas 38
  .kpi.clickable{cursor:pointer;transition:border-color .12s,box-shadow .12s,transform .12s}
39
  .kpi.clickable:hover{border-color:#c7d0e8;box-shadow:0 3px 10px rgba(20,30,60,.09);transform:translateY(-1px)}
36877 vikas 40
  .kpi .top{display:flex;align-items:center;gap:8px}
41
  .kpi .ic{width:28px;height:28px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:14px;flex:none}
42
  .kpi .label{font-size:11.5px;color:var(--muted);font-weight:600;line-height:1.2}
36929 vikas 43
  .kpi .val{font-size:26px;font-weight:760;margin-top:auto;padding-top:9px;letter-spacing:-.02em;line-height:1}
36877 vikas 44
  .kpi .val small{font-size:13px;color:var(--soft);font-weight:600}
45
  .kpi .foot{font-size:11.5px;color:var(--soft);margin-top:7px}
36929 vikas 46
  .kpi .brow{display:flex;align-items:flex-start;text-align:center}
47
  .kpi .brow.blabs{margin-top:11px}
48
  .kpi .brow.bvals{margin-top:auto;padding-top:4px}
49
  .kpi .blab{flex:1;font-size:11px;color:var(--soft);font-weight:600;line-height:1.25}
50
  .kpi .bval{flex:1;font-size:24px;font-weight:760;letter-spacing:-.02em;line-height:1}
51
  .kpi .bval small{font-size:12px;color:var(--soft);font-weight:600}
52
  .kpi .bsep{color:var(--line);font-weight:600;align-self:center}
36877 vikas 53
  .grid{display:grid;gap:16px}
54
  .g2{grid-template-columns:1fr 1fr}
55
  .g3{grid-template-columns:1.55fr 1fr}
56
  .card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:17px 19px;margin-bottom:16px;box-shadow:0 1px 2px rgba(20,30,60,.04)}
57
  .card h2{margin:0 0 3px;font-size:15px;font-weight:720;letter-spacing:-.01em}
58
  .card .desc{color:var(--muted);font-size:12.5px;margin:0 0 14px}
59
  .sectionlabel{font-size:11.5px;letter-spacing:.12em;text-transform:uppercase;color:var(--soft);font-weight:700;margin:24px 2px 12px}
60
  .funnel{display:flex;gap:9px;align-items:stretch}
61
  .fstep{flex:1;border:1px solid var(--line);border-radius:11px;padding:13px 12px;position:relative;text-align:center;background:#fbfcfe}
36905 vikas 62
  .fstep.clickable{cursor:pointer;transition:border-color .12s,box-shadow .12s,transform .12s}
63
  .fstep.clickable:hover{border-color:#c7d0e8;box-shadow:0 3px 10px rgba(20,30,60,.09);transform:translateY(-1px)}
36916 vikas 64
  .fstep.active{border-color:var(--brand);background:#eef1fb;box-shadow:0 0 0 1px var(--brand) inset}
65
  .boardfilter{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);margin:0 0 10px;padding:7px 11px;background:#eef1fb;border:1px solid #d7deef;border-radius:8px}
66
  .boardfilter b{color:#28304a}
67
  .boardfilter .clearf{margin-left:auto;border:1px solid #c7d0e8;background:#fff;color:#3b5bdb;border-radius:7px;padding:3px 10px;font-size:12px;font-weight:600;cursor:pointer}
68
  .boardfilter .clearf:hover{background:#f1f4ff}
36877 vikas 69
  .fstep .fn{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted);font-weight:600}
70
  .fstep .fv{font-size:26px;font-weight:770;margin-top:6px}
71
  .fstep .fbar{height:5px;border-radius:3px;margin-top:10px;background:linear-gradient(90deg,var(--brand),var(--brand2))}
72
  .fstep .drop{font-size:11px;color:var(--red);margin-top:7px;font-weight:600}
73
  .fstep .keep{font-size:11px;color:var(--good);margin-top:7px;font-weight:600}
74
  .fstep .arrow{position:absolute;right:-12px;top:50%;transform:translateY(-50%);z-index:2;color:#c5cce0;font-size:15px}
36929 vikas 75
  .fstep .ssplit{display:flex;align-items:flex-start;margin-top:11px}
76
  .fstep .scol{flex:1}
77
  .fstep .scol .sl{font-size:11px;color:var(--soft);font-weight:600;line-height:1.25}
78
  .fstep .scol .sv{font-size:23px;font-weight:760;letter-spacing:-.02em;line-height:1;margin-top:7px;color:#1b2436}
79
  .fstep .scol .sv .u{font-size:11px;color:var(--soft);font-weight:600;margin-left:2px}
80
  .fstep .scol .sv.good{color:#2f9e44}
81
  .fstep .scol .sv.bad{color:#e8590c}
36877 vikas 82
  .leak{display:flex;gap:10px;margin-top:12px}
83
  .leakbox{flex:1;border:1px solid var(--line2);border-radius:10px;padding:10px 12px;background:#f8f9fc}
84
  .leakbox .lt{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:600}
85
  .leakbox .lv{font-size:20px;font-weight:760;margin-top:4px}
86
  table{width:100%;border-collapse:collapse;font-size:13px}
87
  th,td{text-align:left;padding:9px 9px;border-bottom:1px solid var(--line2)}
88
  th{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:700;white-space:nowrap;cursor:pointer}
89
  th.num,td.num{text-align:right}
90
  tbody tr:hover{background:#f7f9fd}
91
  tr.clickable{cursor:pointer}
92
  .lvl{display:inline-block;font-size:10.5px;font-weight:700;padding:2px 6px;border-radius:5px;background:#eef1fb;color:var(--brand)}
93
  .pill-state{display:inline-flex;align-items:center;gap:6px;font-weight:600;font-size:12.5px;padding:3px 9px;border-radius:999px}
94
  .ps-store{background:#e7f5ff;color:#1971c2}
95
  .ps-travel{background:#e6fcf5;color:#0ca678}
96
  .ps-done{background:#ebfbee;color:#2f9e44}
97
  .ps-idle{background:#fff4e6;color:#e8590c}
98
  .ps-no{background:#fff0f0;color:#e03131}
99
  .meter{display:inline-block;width:54px;height:7px;border-radius:4px;background:#eef1f6;vertical-align:middle;margin-left:7px;overflow:hidden}
100
  .meter > i{display:block;height:100%;border-radius:4px}
101
  .warnflag{color:var(--orange);font-weight:700}
102
  .badflag{color:var(--red);font-weight:700}
103
  .rowwarn{background:#fff9f0}
104
  .rowbad{background:#fff5f5}
36897 vikas 105
  .bstat{display:inline-block;font-size:10.5px;font-weight:700;padding:3px 9px;border-radius:999px;white-space:nowrap}
106
  .bstat.ok{background:#ebfbee;color:#2f9e44}
107
  .bstat.warn{background:#fff4e6;color:#e8590c}
108
  .bstat.no{background:#fff0f0;color:#e03131}
109
  .bdot{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:6px;vertical-align:middle}
110
  .ptime{display:inline-block;background:#ebfbee;color:#2f9e44;font-weight:700;font-size:11px;padding:2px 7px;border-radius:6px;font-variant-numeric:tabular-nums}
36913 vikas 111
  .potime{display:inline-block;background:#ebfbee;color: #D60303A8;font-weight:700;font-size:11px;padding:2px 7px;border-radius:6px;font-variant-numeric:tabular-nums}
36897 vikas 112
  td.cnt{font-weight:700;font-variant-numeric:tabular-nums}
113
  .cgreen{color:#2f9e44}.camber{color:#f08c00}.cred{color:#e03131}.cmuted{color:#69748c}
36917 vikas 114
  tr.boardtot td{background:#f4f6fb;border-bottom:2px solid #cdd3df;font-weight:700}
36897 vikas 115
  .actbtn{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:7px;border:0;cursor:pointer;color:#fff;font-size:12px;margin-left:3px}
116
  .actbtn.map{background:#12b886}.actbtn.view{background:#3b5bdb}
117
  .actbtn.edit{background:#f08c00}.actbtn.add{background:#2f9e44;font-size:15px}
118
  .actbtn:active{transform:translateY(1px)}
36877 vikas 119
  .att{display:flex;align-items:center;gap:12px;padding:11px 12px;border:1px solid var(--line);border-radius:11px;margin-bottom:9px}
120
  .att .ic{width:30px;height:30px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px;flex:none}
121
  .att .ab{flex:1}
122
  .att .atitle{font-size:13px;font-weight:650}
123
  .att .adet{font-size:12px;color:var(--muted);margin-top:2px}
124
  .att .acount{font-size:18px;font-weight:780}
36882 vikas 125
  .att.clickable{cursor:pointer;transition:border-color .12s,box-shadow .12s}
126
  .att.clickable:hover{border-color:#c7d0e8;box-shadow:0 2px 8px rgba(20,30,60,.08)}
127
  .att .chev{color:#c2cadb;font-size:13px;margin-left:8px}
36941 vikas 128
  .attrow{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}
129
  .attrow .att{margin-bottom:0}
130
  @media (max-width:1000px){.attrow{grid-template-columns:repeat(2,1fr)}}
36877 vikas 131
  .barrow{display:grid;grid-template-columns:60px 1fr 90px;align-items:center;gap:11px;margin:8px 0}
132
  .barrow .name{font-size:13px;font-weight:600}
133
  .track{background:#f1f3f9;border-radius:7px;height:20px;position:relative;overflow:hidden}
134
  .fill{height:100%;border-radius:7px;display:flex;align-items:center;justify-content:flex-end;padding-right:6px;font-size:10.5px;color:#fff;font-weight:650;min-width:2px}
135
  .barrow .meta{font-size:11.5px;color:var(--muted);text-align:right}
136
  .donutwrap{display:flex;align-items:center;gap:20px}
137
  .donut{width:138px;height:138px;border-radius:50%;flex:none;position:relative;
138
    -webkit-mask:radial-gradient(circle 42px at center,transparent 98%,#000 100%);mask:radial-gradient(circle 42px at center,transparent 98%,#000 100%)}
139
  .donut .center{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;-webkit-mask:none;mask:none}
140
  .legend{display:flex;flex-direction:column;gap:9px;font-size:12.5px}
141
  .legend .it{display:flex;align-items:flex-start;gap:9px}
36913 vikas 142
  .legend .it.clickable{cursor:pointer;border-radius:8px;padding:4px 6px;margin:-4px -6px;transition:background .12s}
143
  .legend .it.clickable:hover{background:#f1f3f9}
144
  .barrow.clickable{cursor:pointer}
145
  .barrow.clickable:hover .track{outline:2px solid #c7d0e8;outline-offset:1px;border-radius:7px}
146
  .donut.clickable{cursor:pointer}
36877 vikas 147
  .dot{width:11px;height:11px;border-radius:3px;flex:none;margin-top:3px}
148
  .tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:11px}
149
  .tile{background:#f8f9fc;border:1px solid var(--line2);border-radius:11px;padding:12px}
150
  .tile .t{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:600}
151
  .tile .v{font-size:21px;font-weight:760;margin-top:5px}
152
  .tile .v small{font-size:12px;color:var(--soft);font-weight:600}
153
  .util{display:flex;height:30px;border-radius:8px;overflow:hidden}
154
  .util div{display:flex;align-items:center;justify-content:center;font-size:11.5px;font-weight:650;color:#fff}
155
  .utlegend{display:flex;gap:18px;margin-top:12px;font-size:12px;color:var(--muted);flex-wrap:wrap}
156
  .utlegend span{display:inline-flex;align-items:center;gap:7px}
157
  .callout{background:linear-gradient(180deg,#fbfcff,#f4f7ff);border:1px solid #dfe6fb;border-radius:14px;padding:18px 20px;margin-top:6px}
158
  .callout h2{margin:0 0 3px;font-size:16px}
159
  .callout .desc{color:var(--muted);font-size:12.5px;margin-bottom:14px}
160
  .fix{display:flex;gap:13px;padding:13px 0;border-bottom:1px solid #e6ebf8}
161
  .fix:last-child{border-bottom:0}
162
  .fix .sev{width:6px;border-radius:4px;flex:none}
163
  .fix .fb{flex:1}
164
  .fix .ft{font-size:14px;font-weight:700}
165
  .fix .fd{font-size:13px;color:#3a4459;margin-top:4px;line-height:1.5}
166
  .fix .fd b{color:var(--ink)}
167
  .fix .act{font-size:12.5px;color:var(--good);margin-top:6px;font-weight:650}
168
  .hide{display:none}
169
  .loading{padding:70px;text-align:center;color:var(--muted)}
170
  .spinner{width:30px;height:30px;border:3px solid #e3e8f5;border-top-color:var(--brand);border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 12px}
171
  @keyframes spin{to{transform:rotate(360deg)}}
172
  .modal-back{position:fixed;inset:0;background:rgba(15,22,40,.45);display:none;align-items:flex-start;justify-content:center;z-index:50;padding:40px 16px;overflow:auto}
36903 vikas 173
  /* image lightbox — stacks above the journey modal */
174
  .img-back{position:fixed;inset:0;background:rgba(8,12,24,.82);display:none;align-items:center;justify-content:center;z-index:60;padding:30px}
175
  .img-back.show{display:flex}
176
  .img-back img{max-width:95%;max-height:92vh;border-radius:10px;box-shadow:0 16px 60px rgba(0,0,0,.5);background:#fff}
177
  .img-x{position:absolute;top:18px;right:22px;width:40px;height:40px;border-radius:50%;border:0;background:rgba(255,255,255,.18);color:#fff;font-size:26px;line-height:1;cursor:pointer}
178
  .img-x:hover{background:rgba(255,255,255,.3)}
36877 vikas 179
  .modal-back.show{display:flex}
36882 vikas 180
  .modal{background:#fff;border-radius:14px;max-width:780px;width:100%;padding:20px 22px;box-shadow:0 20px 60px rgba(10,20,50,.3);position:relative}
181
  .modal h3{margin:0 0 2px;font-size:17px;text-align:center}
182
  .modal > .desc{text-align:center}
183
  .modal .x{position:absolute;top:14px;right:16px;cursor:pointer;color:var(--soft);font-size:22px;line-height:1;border:0;background:none}
184
  /* journey totals bar */
185
  .jstats{display:flex;gap:9px;margin:12px 0 2px;flex-wrap:wrap}
186
  .js{flex:1;min-width:104px;background:#f8f9fc;border:1px solid var(--line2);border-radius:10px;padding:9px 10px;text-align:center}
187
  .js .jv{font-size:15.5px;font-weight:760;color:var(--ink);font-variant-numeric:tabular-nums}
188
  .js .jl{font-size:10px;color:var(--soft);text-transform:uppercase;letter-spacing:.04em;margin-top:3px;font-weight:600}
36877 vikas 189
  .btn-ok{background:var(--good);border:0;color:#fff;font-weight:650;padding:6px 12px;border-radius:7px;cursor:pointer;font-size:12px}
36882 vikas 190
  /* journey timeline (exec drilldown) */
191
  .tl{position:relative;margin:14px 2px 4px;padding:4px 0}
192
  .tl::before{content:"";position:absolute;left:50%;top:6px;bottom:6px;width:2px;background:#e9edf5;transform:translateX(-50%)}
193
  .tlgap{position:relative;display:flex;justify-content:center;margin:-3px 0}
194
  .tlgap .gappill{background:#fff;border:1px solid var(--line);border-radius:999px;padding:3px 11px;font-size:11px;font-weight:600;color:var(--muted);z-index:2;box-shadow:0 1px 2px rgba(20,30,60,.05);font-variant-numeric:tabular-nums}
36955 vikas 195
  .tlgap .gappill.overrun{border-color:var(--red);color:var(--red)}
36903 vikas 196
  .tlrow{position:relative;display:flex;justify-content:space-between;align-items:flex-start;margin:14px 0}
36882 vikas 197
  .tlrow .node{position:absolute;left:50%;top:8px;transform:translateX(-50%);width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:13px;z-index:2;box-shadow:0 0 0 4px #fff}
198
  .tlcard{width:calc(50% - 26px);background:#fff;border:1px solid var(--line);border-radius:11px;box-shadow:0 2px 10px rgba(20,30,60,.07);display:flex;overflow:hidden}
199
  .tlrow.left .tlcard{flex-direction:row-reverse;text-align:right}
200
  .tlrow.right .tlcard{flex-direction:row;text-align:left}
36903 vikas 201
  /* remark on the opposite half, hugging the centre line */
202
  .tlremark{width:calc(50% - 26px);display:flex;align-items:flex-start;padding-top:6px}
203
  .tlrow.right .tlremark{justify-content:flex-end}
204
  .tlrow.left .tlremark{justify-content:flex-start}
205
  .tlremark .rk{max-width:100%;background:#fbfcfe;border:1px solid var(--line2);border-left:3px solid #c7d0e8;border-radius:8px;padding:7px 10px;font-size:11.5px;color:#4a5468;line-height:1.45;word-break:break-word}
206
  .tlrow.right .tlremark .rk{text-align:right}
207
  .tlrow.left .tlremark .rk{text-align:left}
208
  .tlremark .rkl{font-size:9px;text-transform:uppercase;letter-spacing:.05em;color:var(--soft);font-weight:700;margin-bottom:3px}
36882 vikas 209
  .tlcard .tm{flex:none;width:62px;display:flex;flex-direction:column;align-items:center;justify-content:center;color:#fff;font-weight:750;font-size:13px;padding:6px 4px;line-height:1.05}
210
  .tlcard .tm small{font-weight:600;font-size:8.5px;opacity:.9;text-transform:uppercase;letter-spacing:.04em;margin-top:3px}
211
  .tlcard .bd{padding:8px 11px;flex:1;min-width:0}
212
  .tlcard .bd .ti{font-size:12.5px;font-weight:700;color:var(--ink);line-height:1.25;word-break:break-word}
213
  .tlcard .bd .stt{display:inline-block;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.03em;padding:1px 6px;border-radius:5px;margin-top:5px;color:#fff}
36941 vikas 214
  .tlcard .bd .stt.unplanned{background:#fff4e6;color:#e8590c;border:1px solid #ffd8a8;margin-left:5px}
36882 vikas 215
  .tlcard .bd .mt{font-size:11px;color:var(--muted);margin-top:6px}
216
  .tlextra{display:flex;align-items:center;gap:7px;margin-top:8px;flex-wrap:wrap}
217
  .tlrow.left .tlextra{justify-content:flex-end}
218
  .tlrow.right .tlextra{justify-content:flex-start}
219
  .tlthumb{width:46px;height:46px;border-radius:8px;object-fit:cover;border:1px solid var(--line);cursor:pointer;background:#f1f3f9}
220
  .tlph{width:46px;height:46px;border-radius:8px;border:1px dashed #cfd6e6;background:#f4f6fb;display:flex;align-items:center;justify-content:center;color:#b3bcce;font-size:18px}
221
  .tlchip{font-size:10.5px;font-weight:600;color:var(--muted);background:#f1f3f9;border-radius:6px;padding:2px 7px;white-space:nowrap}
36897 vikas 222
  .exectabs{display:flex;gap:6px;justify-content:center;margin:12px 0 4px}
223
  .exectab{padding:6px 14px;border-radius:8px;font-size:12.5px;font-weight:650;color:var(--muted);cursor:pointer;border:1px solid var(--line);background:#fff}
224
  .exectab.active{background:var(--brand);color:#fff;border-color:var(--brand)}
225
  #bjMap{width:100%;height:460px;border-radius:12px;border:1px solid var(--line);margin-top:10px;background:#eef1f7;overflow:hidden}
36903 vikas 226
  .bjlegend{display:flex;gap:16px;align-items:center;flex-wrap:wrap;margin-top:12px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;background:#f8f9fc;font-size:12.5px;min-height:20px}
227
  .bjlegend .lg{font-weight:700}
228
  .bjlegend .sw{display:inline-block;width:24px;vertical-align:middle;margin-right:7px}
229
  .bjlegend .ln{border-top:4px solid #e03131}
230
  .bjlegend .dt{border-top:4px dotted #2f9e44}
36897 vikas 231
  .valwrap{display:flex;justify-content:center;margin:14px 0 6px}
232
  .valimg{max-width:100%;max-height:440px;border-radius:12px;border:1px solid var(--line);cursor:zoom-in}
233
  .valph{width:100%;padding:48px;text-align:center;color:var(--soft);border:1px dashed #cfd6e6;border-radius:12px;background:#f4f6fb;font-size:14px}
234
  .valactions{display:flex;justify-content:center;gap:10px;margin-top:8px}
36877 vikas 235
  @media (max-width:1000px){.kpis{grid-template-columns:repeat(3,1fr)}.g2,.g3{grid-template-columns:1fr}.funnel{flex-wrap:wrap}.fstep{min-width:46%}.fstep .arrow{display:none}}
36903 vikas 236
  @media (max-width:560px){.tl::before{left:20px}.tlrow.left,.tlrow.right{justify-content:flex-end}.tlrow .node{left:20px}.tlcard{width:calc(100% - 44px)}.tlrow.left .tlcard{flex-direction:row;text-align:left}.tlremark{display:none}}
36877 vikas 237
</style>
238
</head>
239
<body>
240
<div class="wrap">
241
  <header class="top">
242
    <div class="brand">
243
      <div class="crumb"><a href="${rc.contextPath}/dashboard">&larr; Dashboard</a> &middot; Field Sales &middot; Beat / Monthly PJP</div>
244
      <h1>Beat Journey <span class="live"><i></i>Live</span></h1>
245
    </div>
246
    <div class="hd-right">
247
      <select class="ctl" id="bj-level">
248
        <option value="">All levels below me</option>
249
        #foreach($lvl in $escalationTypes)
250
          <option value="$lvl">$lvl</option>
251
        #end
252
      </select>
36897 vikas 253
      #if($topLevel)
254
      <select class="ctl hide" id="bj-user">
255
        <option value="">All users at level</option>
256
      </select>
257
      #end
36877 vikas 258
      <input class="ctl" type="date" id="bj-date" value="$today">
259
      <span id="bj-period-range" class="hide">
260
        <input class="ctl" type="date" id="bj-start" value="$monthStart">
261
        <input class="ctl" type="date" id="bj-end" value="$today">
262
      </span>
263
      <button class="btn-r" id="bj-apply">Apply</button>
36903 vikas 264
      <button class="btn-r" id="bj-export" style="background:#2f9e44" title="Download an Excel report for the selected date / range">&#11015; Export Excel</button>
36877 vikas 265
    </div>
266
  </header>
267
 
268
  <div class="lenses">
269
    <button class="lens active" data-lens="today" id="lens-today">Today (Live)</button>
270
    <button class="lens" data-lens="period" id="lens-period">Period (Analytics)</button>
271
  </div>
272
 
273
  <div id="bj-content"><div class="loading"><div class="spinner"></div>Loading&hellip;</div></div>
274
</div>
275
 
276
<div class="modal-back" id="bj-modal-back">
277
  <div class="modal" id="bj-modal"></div>
278
</div>
279
 
36903 vikas 280
<div class="img-back" id="bj-img-back">
281
  <button class="img-x" id="bj-img-x" title="Close">&times;</button>
282
  <img id="bj-img" alt="Attachment">
283
</div>
284
 
36877 vikas 285
<script>
286
var CTX = '${rc.contextPath}';
287
var BASE = CTX + '/beat-journey';
288
var LENS = 'today';
36897 vikas 289
var TODAY = '$today';
36962 vikas 290
var CAN_EDIT_BEAT = $canEditBeat;
36877 vikas 291
 
292
function el(id){ return document.getElementById(id); }
36897 vikas 293
// The first lens reads "Today (Live)" for today's date, otherwise it shows the
294
// selected date (the tab is still the live/single-day view, just for that day).
295
function fmtDateLabel(d){
296
  var p=(d||'').split('-'); if(p.length!==3) return d;
297
  var mo=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
298
  return parseInt(p[2],10)+' '+(mo[parseInt(p[1],10)-1]||p[1])+' '+p[0];
299
}
300
function updateTodayLabel(){
301
  var b=el('bj-date'), lbl=el('lens-today'); if(!lbl) return;
302
  var d=b?b.value:'';
303
  lbl.innerHTML = (!d || d===TODAY) ? 'Today (Live)' : esc(fmtDateLabel(d));
304
}
36877 vikas 305
function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
306
function num(n){ return (n==null?0:n).toLocaleString(); }
307
function adhColor(p){ if(p>=80)return '#2f9e44'; if(p>=60)return '#f08c00'; if(p>=40)return '#e8590c'; return '#e03131'; }
308
function pct(a,b){ return b? Math.round(100*a/b):0; }
309
function qs(){
310
  var lvl = el('bj-level').value;
311
  var s = '';
312
  if(lvl) s += '&escalationType=' + encodeURIComponent(lvl);
36897 vikas 313
  var usr = el('bj-user');           // only present for L5/Final
314
  if(usr && usr.value) s += '&teamOfAuthUserId=' + encodeURIComponent(usr.value);
36877 vikas 315
  return s;
316
}
36897 vikas 317
// L5/Final: when a level is picked, list its users so a specific manager's team
318
// can be selected. Selecting a user scopes the whole view to that user's team.
319
function onLevelChange(){
320
  var usr = el('bj-user');
321
  if(!usr){ load(); return; }       // not top-level: just reload on level change
322
  var lvl = el('bj-level').value;
323
  usr.innerHTML = '<option value="">All users at level</option>';
324
  if(!lvl){ usr.classList.add('hide'); load(); return; }
325
  fetch(BASE + '/users?escalationType=' + encodeURIComponent(lvl), {headers:{'Accept':'application/json'}})
326
    .then(function(r){ return r.json(); })
327
    .then(function(d){
328
      var us = d.users || [];
329
      var h = '<option value="">All ' + esc(lvl) + ' users</option>';
330
      us.forEach(function(u){ h += '<option value="' + u.id + '">' + esc(u.name) + '</option>'; });
331
      usr.innerHTML = h;
332
      usr.classList.toggle('hide', us.length === 0);
333
      load();
334
    })
335
    .catch(function(){ usr.classList.add('hide'); load(); });
336
}
36877 vikas 337
function spinner(){ el('bj-content').innerHTML = '<div class="loading"><div class="spinner"></div>Loading&hellip;</div>'; }
338
function fail(e){ el('bj-content').innerHTML = '<div class="loading">Could not load data ('+esc(e&&e.message||e)+'). Are you signed in?</div>'; }
339
 
340
function setLens(name){
341
  LENS = name;
342
  var tabs = document.querySelectorAll('.lens');
343
  for(var i=0;i<tabs.length;i++){ tabs[i].classList.toggle('active', tabs[i].getAttribute('data-lens')===name); }
344
  el('bj-date').classList.toggle('hide', name!=='today');
345
  el('bj-period-range').classList.toggle('hide', name==='today');
346
  load();
347
}
348
function load(){
349
  if(LENS==='today') return loadToday();
350
  if(LENS==='period') return loadPeriod();
351
  return loadApproval();
352
}
353
 
354
/* ============================ TODAY ============================ */
355
function loadToday(){
36897 vikas 356
  updateTodayLabel();
36877 vikas 357
  spinner();
358
  fetch(BASE + '/today?date=' + encodeURIComponent(el('bj-date').value) + qs(), {headers:{'Accept':'application/json'}})
359
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
360
    .then(renderToday).catch(fail);
361
}
36905 vikas 362
function kpi(ic, bg, fg, label, val, foot, valColor, click){
363
  return '<div class="kpi'+(click?' clickable':'')+'"'+(click?' onclick="'+click+'" title="Click for details"':'')+'><div class="top"><div class="ic" style="background:'+bg+';color:'+fg+'">'+ic+'</div>'+
36929 vikas 364
    '<div class="label">'+label+'</div></div>'+
365
    '<div class="foot">'+foot+'</div>'+
366
    '<div class="val"'+(valColor?' style="color:'+valColor+'"':'')+'>'+val+'</div></div>';
36877 vikas 367
}
36929 vikas 368
// Multi-column breakdown card: centered title, a row of sub-labels, the number under each.
369
// cols = [[label, value], ...]; unit (optional) is appended after each number, e.g. 'min'.
370
function kpiCols(ic, bg, fg, title, cols, fg2, click, unit){
371
  var lab='', val='', u=unit?' <small>'+unit+'</small>':'';
372
  for(var i=0;i<cols.length;i++){
373
    var sep=i?'<span class="bsep">&middot;</span>':'';
374
    lab+=sep+'<div class="blab">'+cols[i][0]+'</div>';
375
    val+=(i?'<span class="bsep">&nbsp;</span>':'')+'<div class="bval"'+(fg2?' style="color:'+fg2+'"':'')+'>'+num(cols[i][1])+u+'</div>';
376
  }
377
  return '<div class="kpi kpicols'+(click?' clickable':'')+'"'+(click?' onclick="'+click+'" title="Click for details"':'')+'>'+
378
    '<div class="top"><div class="ic" style="background:'+bg+';color:'+fg+'">'+ic+'</div><div class="label">'+title+'</div></div>'+
379
    '<div class="brow blabs">'+lab+'</div>'+
380
    '<div class="brow bvals">'+val+'</div></div>';
381
}
382
// Period journey summary as a row of cards (old funnel layout). Each card is a
36941 vikas 383
// group (Total Visits / Avg Time Spent / Idle-Break / Deferred / Completed),
384
// planned and self-assigned merged into one value. col=[[label,value,colorClass],...].
36929 vikas 385
function summaryCard(title, cols, last){
386
  var body='';
387
  for(var i=0;i<cols.length;i++){
388
    body+='<div class="scol"><div class="sl">'+cols[i][0]+'</div>'+
389
          '<div class="sv'+(cols[i][2]?' '+cols[i][2]:'')+'">'+cols[i][1]+'</div></div>';
390
  }
391
  return '<div class="fstep"><div class="fn">'+title+'</div><div class="ssplit">'+body+'</div>'+
392
    (last?'':'<span class="arrow">&#10148;</span>')+'</div>';
393
}
394
function summaryCards(s){
395
  if(!s) return '';
396
  var mn=function(v){return num(v)+'<span class="u">min</span>';};
36941 vikas 397
  // planned + self-assigned merged into single totals
398
  var totalVisits=(s.plannedVisits||0)+(s.selfVisits||0);
399
  var completed=(s.completedPlanned||0)+(s.completedSelf||0);
400
  var deferred=(s.deferredPlanned||0)+(s.deferredSelf||0);
401
  return summaryCard('Total Visits',[['Visits',num(totalVisits),'']])+
402
    summaryCard('Average Time Spent',[['Per visit',mn(s.avgTimeAllMin),'']])+
36929 vikas 403
    summaryCard('Idle / Break',[['Total Average',mn(s.idleAvgMin),'']])+
36941 vikas 404
    summaryCard('Completed Visits',[['Completed',num(completed),'good']])+
405
    summaryCard('Deferred',[['Deferred',num(deferred),deferred>0?'bad':'']],true);
36929 vikas 406
}
36905 vikas 407
function fstep(name, val, w, sub, drop, last, key){
36916 vikas 408
  return '<div class="fstep'+(key?' clickable" data-fkey="'+key+'" onclick="funnelClick(\''+key+'\')" title="Click to filter the board to these executives':'')+'"><div class="fn">'+name+'</div><div class="fv">'+num(val)+'</div>'+
36913 vikas 409
    '<div class="fbar" style="width:'+Math.min(w,100)+'%"></div><div class="'+(drop?'drop':'keep')+'">'+sub+'</div>'+
36877 vikas 410
    (last?'':'<span class="arrow">&#10148;</span>')+'</div>';
411
}
36913 vikas 412
// Funnel drop sub-text: positive = fell out (red); negative = above planned
413
// (leads push visits past planned stops) shown green; zero = on plan.
414
function fdrop(p, badLabel){
415
  if(p>0) return '&minus;'+p+'% '+badLabel;
416
  if(p<0) return '+'+(-p)+'% above planned';
417
  return 'on plan';
418
}
36877 vikas 419
function leakbox(t, v, color){ return '<div class="leakbox"><div class="lt">'+t+'</div><div class="lv"'+(color?' style="color:'+color+'"':'')+'>'+num(v)+'</div></div>'; }
420
 
421
function renderToday(d){
422
  var k=d.kpis, f=d.funnel, s=d.stops, a=d.attention;
36897 vikas 423
  window._canApprove = !!d.canApprove;
424
  window._mediaUrl = d.mediaUrl || window._mediaUrl || '';
36905 vikas 425
  window._board = d.board || [];          // funnel drill-down filters this
426
  window._boardDate = d.date || '';
427
  window._leadsList = d.leadsList || [];  // leads drill-down
36917 vikas 428
  window._execList = d.execList || [];    // main-card drill-downs
36877 vikas 429
  var h='';
430
  h+='<div class="kpis">';
36917 vikas 431
  h+=kpi('&#128101;','#eef1fb','#3b5bdb','Total Executives',num(k.totalExecs),'in your team',null,"openCards('total')");
432
  h+=kpi('&#128197;','#ebfbee','#2f9e44','Scheduled PJP',num(k.scheduledPjp)+' <small>/'+k.totalExecs+'</small>',k.unscheduled+' unscheduled',null,"openCards('scheduled')");
433
  h+=kpi('&#9998;','#fff4e6','#e8590c','Agenda Filled',num(k.agendaFilled)+' <small>/'+k.scheduledPjp+'</small>',(k.scheduledPjp-k.agendaFilled)+' pending',null,"openCards('agenda')");
434
  h+=kpi('&#10060;','#fff0f6','#d6336c','Unscheduled',num(k.unscheduled),'no PJP today',null,"openCards('unscheduled')");
36877 vikas 435
  h+='</div>';
436
 
36941 vikas 437
  h+='<div class="card"><h2>Needs attention now</h2><p class="desc">Things a manager should clear today.</p>'+attentionList(a)+'</div>';
438
 
36877 vikas 439
  h+='<div class="sectionlabel">Today\'s Journey Funnel</div><div class="card"><div class="funnel">';
36917 vikas 440
  var sp=f.scheduledPjp||1, pin=f.punchedIn||1;
441
  h+=fstep('Punched In',f.punchedIn,pct(f.punchedIn,sp),f.punchedIn+' of '+f.scheduledPjp+' scheduled',false,false,'punchedIn');
442
  h+=fstep('Traveling',f.travelling,pct(f.travelling,pin),'on the road',false,false,'travelling');
443
  h+=fstep('In Store',f.inStore,pct(f.inStore,pin),'at a stop',false,false,'inStore');
37020 vikas 444
  h+=fstep('Idle / Break',f.idle,pct(f.idle,pin),'&lt; 1 km in 15 min',true,false,'idle');
36917 vikas 445
  h+=fstep('Punched Out',f.punchedOut,pct(f.punchedOut,pin),'journey ended',false,true,'punchedOut');
36877 vikas 446
  h+='</div></div>';
447
 
36916 vikas 448
  window._boardFilter = null;             // funnel-card filter (null = all rows)
449
  h+='<div class="card"><h2>Live executive board</h2><p class="desc">Each executive\'s journey right now. Click a row for the day\'s visit detail.</p><div id="bj-board">'+boardCard()+'</div></div>';
36877 vikas 450
  el('bj-content').innerHTML=h;
451
}
452
function stateClass(st){ return st==='IN_STORE'?'ps-store':st==='TRAVELLING'?'ps-travel':st==='DONE'?'ps-done':st==='NOT_STARTED'?'ps-no':'ps-idle'; }
36897 vikas 453
function js(s){ return String(s==null?'':s).replace(/\\/g,'\\\\').replace(/'/g,"\\'"); }
454
// Open the Beat Planner (map-first planner window) for this executive/beat/day,
455
// in a new tab. Edit pre-selects the beat; add opens it to assign/add a visit.
456
function openPlanner(authUserId, beatId, date, mode){
457
  var u = CTX + '/beatPlanWindow?autoUserId=' + encodeURIComponent(authUserId) + '&editDate=' + encodeURIComponent(date);
458
  if(beatId && beatId>0) u += '&editBeatId=' + encodeURIComponent(beatId);
459
  if(mode==='add') u += '&assign=1';
460
  window.open(u, '_blank');
461
}
36916 vikas 462
// Funnel-card click: period cards (p_*) open their drill-down popup; today's
463
// funnel cards filter the Live executive board in place. Clicking the active
464
// card again clears the filter.
465
function funnelClick(key){
466
  if(key && key.indexOf('p_')===0) return openFunnel(key);
467
  setBoardFilter(window._boardFilter===key ? null : key);
468
}
469
// Apply / clear the funnel filter and re-render just the board card. Also marks
470
// the active funnel card so it's clear which cohort the board is showing.
471
function setBoardFilter(key){
472
  window._boardFilter = key || null;
473
  var c=el('bj-board'); if(c) c.innerHTML=boardCard();
474
  document.querySelectorAll('.fstep[data-fkey]').forEach(function(s){
475
    s.classList.toggle('active', !!key && s.getAttribute('data-fkey')===key);
476
  });
477
}
478
// Board card content: an optional "filtered by …" bar plus the table, showing
479
// only the rows that reached the selected funnel stage (Scheduled = all rows).
480
function boardCard(){
481
  var rows=window._board||[], date=window._boardDate||'', key=window._boardFilter;
482
  var view=rows, m=key?FUNNEL_META[key]:null;
483
  if(m) view=rows.filter(m.f);
484
  var bar='';
485
  if(m){
486
    bar='<div class="boardfilter">Showing <b>'+esc(m.title)+'</b> &middot; '+view.length+
487
        ' of '+rows.length+'<button class="clearf" onclick="setBoardFilter(null)">&times; Clear filter</button></div>';
488
  }
489
  return bar+boardTable(view, date);
490
}
36941 vikas 491
// Merge planned partner visits and self-assigned leads into one set of tallies.
492
// Total reconciles with the parts: Total = Completed + Pending + Deferred, where
493
// Total is the plan (or activity total if it ran past the plan).
494
function boardCounts(r){
495
  var completed=r.completedVisits||0, deferred=r.deferred||0;
496
  var total=Math.max(r.planned||0, completed+deferred);
497
  return {total:total, completed:completed, deferred:deferred, pending:total-completed-deferred};
498
}
37020 vikas 499
// seconds -> compact "1h 20m" / "45m" for the board's time columns.
500
function bhm(sec){ sec=Math.max(0,Math.round(sec||0)); var h=Math.floor(sec/3600), m=Math.round((sec%3600)/60); return h?(h+'h '+m+'m'):(m+'m'); }
36877 vikas 501
function boardTable(rows, date){
502
  if(!rows||!rows.length) return '<p class="desc">No executives scheduled or active for this date.</p>';
36897 vikas 503
  var h='<div style="overflow-x:auto"><table><thead><tr>'+
36916 vikas 504
    '<th>Agenda</th><th>Executive</th><th>Punch In/Out</th>'+
36941 vikas 505
    '<th class="num" title="Planned partner visits + self-assigned leads">Total</th>'+
506
    '<th class="num">Completed</th><th class="num">Pending</th><th class="num">Deferred</th>'+
37020 vikas 507
    '<th class="num" title="Transit time between stops so far today">Transit</th>'+
508
    '<th class="num" title="Time spent inside stores so far today">In-store</th>'+
36941 vikas 509
    '<th>State</th><th>Action</th>'+
36897 vikas 510
    '</tr></thead><tbody>';
36917 vikas 511
  // column totals, computed up front so the Total row can lead the table
37020 vikas 512
  var t={total:0,completed:0,pending:0,deferred:0,transit:0,inStore:0};
36877 vikas 513
  rows.forEach(function(r){
36941 vikas 514
    var c=boardCounts(r);
515
    t.total+=c.total; t.completed+=c.completed; t.pending+=c.pending; t.deferred+=c.deferred;
37020 vikas 516
    t.transit+=(r.transitSecs||0); t.inStore+=(r.inStoreSecs||0);
36917 vikas 517
  });
518
  h+='<tr class="boardtot">'+
519
     '<td></td><td><b>Total</b><br><span style="color:#97a1b5;font-size:11px">'+rows.length+' executives</span></td><td></td>'+
36941 vikas 520
     '<td class="num cnt cmuted">'+t.total+'</td>'+
521
     '<td class="num cnt cgreen">'+t.completed+'</td>'+
522
     '<td class="num cnt">'+t.pending+'</td>'+
37020 vikas 523
     '<td class="num cnt camber">'+t.deferred+'</td>'+
524
     '<td class="num cnt cmuted">'+bhm(t.transit)+'</td>'+
525
     '<td class="num cnt cmuted">'+bhm(t.inStore)+'</td><td></td><td></td>'+
36917 vikas 526
     '</tr>';
527
  rows.forEach(function(r){
36897 vikas 528
    var rowcls = r.state==='NOT_STARTED' ? 'rowbad' : (r.idleAway?'rowwarn':'');
529
    var A = r.userId+",'"+js(r.name)+"','"+date+"'";   // openExec args
530
    var go = 'onclick="openExec('+A+')"';
36941 vikas 531
    var c=boardCounts(r);
36897 vikas 532
    h+='<tr class="clickable '+rowcls+'" '+go+'>'+
533
       '<td style="text-align:center">'+(r.agendaFilled?'<span style="color:#2f9e44;font-size:15px">&#10003;</span>':'<span class="badflag" style="font-size:15px">&#10007;</span>')+'</td>'+
534
       '<td><b>'+esc(r.name)+'</b><br>'+esc(r.beatName||'-')+'</td>'+
535
       '<td style="white-space:nowrap">'+(r.punchInTime?'<span class="ptime">'+esc(r.punchInTime)+'</span>':'<span class="badflag">-</span>')+
536
         ' <span style="color:#97a1b5;font-size:11px">/ '+(r.punchOutTime?esc(r.punchOutTime):'--')+'</span></td>'+
36941 vikas 537
       '<td class="num cnt cmuted">'+c.total+'</td>'+
538
       '<td class="num cnt cgreen">'+c.completed+'</td>'+
539
       '<td class="num cnt">'+c.pending+'</td>'+
540
       '<td class="num cnt camber">'+c.deferred+'</td>'+
37020 vikas 541
       '<td class="num cnt cmuted">'+(r.transitSecs?bhm(r.transitSecs):'<span style="color:#c5cce0">&mdash;</span>')+'</td>'+
542
       '<td class="num cnt cmuted">'+(r.inStoreSecs?bhm(r.inStoreSecs):'<span style="color:#c5cce0">&mdash;</span>')+'</td>'+
36905 vikas 543
       '<td><span class="pill-state '+stateClass(r.state)+'">'+esc(r.stateLabel)+'</span></td>'+
36897 vikas 544
       '<td style="white-space:nowrap" onclick="event.stopPropagation()">'+
545
         '<button class="actbtn map" title="Live location" onclick="openExec('+A+',\'map\')">&#128205;</button>'+
546
         '<button class="actbtn view" title="Journey detail" onclick="openExec('+A+')">&#128065;</button>'+
36962 vikas 547
         (CAN_EDIT_BEAT
548
           ? '<button class="actbtn edit" title="Edit beat in Beat Planner" onclick="openPlanner('+r.authUserId+','+(r.beatId||0)+',\''+date+'\',\'edit\')">&#9998;</button>'+
549
             '<button class="actbtn add" title="Assign / add visit in Beat Planner" onclick="openPlanner('+r.authUserId+','+(r.beatId||0)+',\''+date+'\',\'add\')">&#43;</button>'
550
           : '')+
36897 vikas 551
       '</td></tr>';
36877 vikas 552
  });
36917 vikas 553
  return h+'</tbody></table></div>';
36877 vikas 554
}
36905 vikas 555
// Funnel drill-down: each stage shows the executives who reached it AND the
556
// drop-off cohort that fell out at this step (the "−N …" sub-line). Filters
557
// mirror the backend funnel conditions exactly (rows carry the per-stage flags).
558
var FUNNEL_META = {
36917 vikas 559
  punchedIn:  {title:'Punched In',   desc:'Started the day (punch-in recorded)', f:function(r){ return r.punchedIn; }},
37020 vikas 560
  travelling: {title:'Traveling',    desc:'On the road between stops',           f:function(r){ return r.state==='TRAVELLING'; }},
36917 vikas 561
  inStore:    {title:'In Store',     desc:'Currently checked in at a stop',      f:function(r){ return r.state==='IN_STORE'; }},
37020 vikas 562
  idle:       {title:'Idle / Break', desc:'Punched in but < 1 km covered in the last 15 min', f:function(r){ return r.state==='IDLE'; }},
36917 vikas 563
  punchedOut: {title:'Punched Out',  desc:'Ended the day (punch-out recorded)',  f:function(r){ return r.punchedOut; }}
36905 vikas 564
};
565
function funnelRows(list, date){
566
  if(!list.length) return '<p class="desc">None.</p>';
567
  var h='<table><thead><tr><th>Executive / Beat</th><th>Punch In/Out</th><th class="num">Completed</th><th class="num">Planned</th><th>State</th></tr></thead><tbody>';
568
  list.slice().sort(function(a,b){ return (''+a.name).localeCompare(b.name); }).forEach(function(r){
569
    var A=r.userId+",'"+js(r.name)+"','"+date+"'";
570
    h+='<tr class="clickable" onclick="openExec('+A+')">'+
571
       '<td><b>'+esc(r.name)+'</b><br><span style="color:#97a1b5;font-size:11px">'+esc(r.beatName||'-')+'</span></td>'+
572
       '<td style="white-space:nowrap">'+(r.punchInTime?'<span class="ptime">'+esc(r.punchInTime)+'</span>':'<span class="badflag">-</span>')+
573
         ' <span style="color:#97a1b5;font-size:11px">/ '+(r.punchOutTime?esc(r.punchOutTime):'--')+'</span></td>'+
574
       '<td class="num cnt cgreen">'+r.completedVisits+'</td>'+
575
       '<td class="num">'+r.planned+'</td>'+
576
       '<td><span class="pill-state '+stateClass(r.state)+'">'+esc(r.stateLabel)+'</span></td></tr>';
577
  });
578
  return h+'</tbody></table>';
579
}
580
function openFunnel(key){
36913 vikas 581
  if(key && key.indexOf('p_')===0) return openPFunnel(key);   // period funnel
36905 vikas 582
  var m=FUNNEL_META[key]; if(!m) return;
583
  var board=window._board||[], date=window._boardDate||'';
584
  var reached=board.filter(m.f);
585
  var dropped=m.drop ? board.filter(m.drop) : [];
586
  var mb=el('bj-modal-back'), md=el('bj-modal');
587
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(m.title)+'</h3>'+
588
        '<p class="desc">'+reached.length+' '+(reached.length===1?'executive':'executives')+' &middot; '+esc(m.desc)+'</p>'+
589
        funnelRows(reached, date);
590
  if(m.drop){
591
    h+='<div class="sectionlabel" style="margin-top:18px;color:#e8590c">'+esc(m.dropLabel)+' &middot; '+dropped.length+'</div>'+
592
       funnelRows(dropped, date);
593
  }
594
  h+='<p class="desc" style="margin-top:10px">Click a row to open that executive\'s journey detail.</p>';
595
  md.innerHTML=h; mb.classList.add('show');
596
}
36917 vikas 597
// Main-card drill-downs: roster of executives behind each top KPI card.
598
// 'drop' (optional) adds a second, highlighted section for the complementary
599
// cohort — e.g. who's scheduled but hasn't filled the agenda.
600
var CARD_META = {
601
  total:       {title:'Total Executives', desc:'Everyone in your team',        f:function(r){ return true; }},
602
  scheduled:   {title:'Scheduled PJP',     desc:'Executives with a beat today', f:function(r){ return r.hasBeat; }},
603
  agenda:      {title:'Agenda Filled',     desc:'Beats with the agenda filled', f:function(r){ return r.agendaFilled; },
604
                dropLabel:'Agenda not filled (scheduled)', drop:function(r){ return r.hasBeat && !r.agendaFilled; }},
605
  unscheduled: {title:'Unscheduled',       desc:'No PJP scheduled today',       f:function(r){ return !r.hasBeat; }}
606
};
607
// Renders an executive roster table (used by the card drill-downs).
608
function execRows(list, date){
609
  if(!list.length) return '<p class="desc">None.</p>';
610
  var h='<table><thead><tr><th>Executive</th><th>Beat</th><th>Agenda</th><th>Status</th></tr></thead><tbody>';
611
  list.forEach(function(r){
612
    var A=r.userId+",'"+js(r.name)+"','"+date+"'";
613
    var go = r.userId ? ' class="clickable" onclick="openExec('+A+')"' : '';
614
    var agenda = !r.hasBeat ? '<span style="color:#97a1b5">&mdash;</span>'
615
      : (r.agendaFilled ? '<span style="color:#2f9e44">&#10003;</span>' : '<span class="badflag">&#10007;</span>');
616
    h+='<tr'+go+'>'+
617
       '<td><b>'+esc(r.name)+'</b></td>'+
618
       '<td>'+esc(r.beatName||'-')+'</td>'+
619
       '<td style="text-align:center">'+agenda+'</td>'+
620
       '<td>'+esc(r.statusLabel||'')+'</td></tr>';
621
  });
622
  return h+'</tbody></table>';
623
}
624
function openCards(key){
625
  var m=CARD_META[key]; if(!m) return;
626
  var all=(window._execList||[]), date=window._boardDate||'';
627
  var list=all.filter(m.f);
628
  var dropped=m.drop ? all.filter(m.drop) : [];
629
  var mb=el('bj-modal-back'), md=el('bj-modal');
630
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(m.title)+'</h3>'+
631
        '<p class="desc">'+list.length+' '+(list.length===1?'executive':'executives')+' &middot; '+esc(m.desc)+'</p>'+
632
        execRows(list, date);
633
  if(m.drop){
634
    h+='<div class="sectionlabel" style="margin-top:18px;color:#e8590c">'+esc(m.dropLabel)+' &middot; '+dropped.length+'</div>'+
635
       execRows(dropped, date);
636
  }
637
  h+='<p class="desc" style="margin-top:10px">Click a row to open that executive\'s journey detail.</p>';
638
  md.innerHTML=h; mb.classList.add('show');
639
}
36905 vikas 640
// Leads drill-down: lists every lead visit logged today (matches the KPI count).
641
function openLeads(){
642
  var list=window._leadsList||[], date=window._boardDate||'';
643
  var mb=el('bj-modal-back'), md=el('bj-modal');
644
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>Leads on route</h3>'+
645
        '<p class="desc">'+list.length+' lead '+(list.length===1?'visit':'visits')+' logged'+(date?' on '+esc(date):'')+'</p>';
646
  if(!list.length){ h+='<p class="desc">No leads logged for this date.</p>'; }
647
  else {
648
    h+='<table><thead><tr><th>Executive</th><th>Lead</th><th>Check-in</th><th>Status</th></tr></thead><tbody>';
649
    list.slice().sort(function(a,b){ return (''+a.exec).localeCompare(b.exec); }).forEach(function(r){
650
      var A=r.userId+",'"+js(r.exec)+"','"+date+"'";
651
      var go = r.userId ? ' class="clickable" onclick="openExec('+A+')"' : '';
652
      h+='<tr'+go+'>'+
653
         '<td><b>'+esc(r.exec)+'</b></td>'+
654
         '<td>'+esc(r.lead||'-')+'</td>'+
655
         '<td style="white-space:nowrap">'+(r.checkInTime?'<span class="ptime">'+esc(hhmm(r.checkInTime))+'</span>':'<span class="badflag">-</span>')+'</td>'+
656
         '<td>'+esc(r.status||'')+'</td></tr>';
657
    });
658
    h+='</tbody></table><p class="desc" style="margin-top:10px">Click a row to open that executive\'s journey detail.</p>';
659
  }
660
  md.innerHTML=h; mb.classList.add('show');
661
}
36913 vikas 662
/* ===================== PERIOD (ANALYTICS) DRILL-DOWNS ===================== */
663
function pModal(html){ el('bj-modal').innerHTML=html; el('bj-modal-back').classList.add('show'); }
664
function pRange(){ return (el('bj-start')?el('bj-start').value:'')+' to '+(el('bj-end')?el('bj-end').value:''); }
665
 
666
// Scorecard list popup (used by KPI cards + funnel stages). Rows drill to the
667
// executive's day-by-day. sortKey sorts descending.
668
function openPScore(sortKey, title, desc){
669
  var rows=(((window._period||{}).scorecard)||[]).slice();
670
  if(sortKey) rows.sort(function(a,b){ return (b[sortKey]||0)-(a[sortKey]||0); });
671
  pModal('<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(title)+'</h3>'+
672
    '<p class="desc">'+esc(desc)+' &middot; '+esc(pRange())+' &middot; click a row for the day-by-day</p>'+pScoreTable(rows));
673
}
674
function pScoreTable(rows){
675
  if(!rows.length) return '<p class="desc">No executives in scope.</p>';
37020 vikas 676
  var h='<table><thead><tr><th>Executive</th><th class="num">Plan</th><th class="num">Done</th><th class="num">Adher.</th>'+
677
    '<th class="num" title="Avg lead visits per active (punched-in) day">Lead/day</th>'+
678
    '<th class="num" title="Avg franchisee visits per active (punched-in) day">Fr/day</th>'+
37028 vikas 679
    '<th class="num">Disc.</th><th class="num">Hrs</th><th class="num">Leads</th></tr></thead><tbody>';
36913 vikas 680
  rows.forEach(function(r){
681
    var c=adhColor(r.adherencePct);
682
    h+='<tr class="clickable" onclick="openExecPeriod('+r.authUserId+',\''+js(r.name)+'\')">'+
37020 vikas 683
       '<td><span class="lvl">'+esc(r.level)+'</span> <b>'+esc(r.name)+'</b></td>'+
36913 vikas 684
       '<td class="num">'+r.planned+'</td><td class="num">'+r.done+'</td>'+
685
       '<td class="num"><b style="color:'+c+'">'+r.adherencePct+'%</b></td>'+
37020 vikas 686
       '<td class="num">'+(r.avgLeadVisitsPerDay||'-')+'</td>'+
687
       '<td class="num">'+(r.avgFranchiseeVisitsPerDay||'-')+'</td>'+
36913 vikas 688
       '<td class="num'+(r.discussionMin>0&&r.discussionMin<10?' warnflag':'')+'">'+(r.discussionMin||'-')+(r.discussionMin?'m':'')+'</td>'+
37028 vikas 689
       '<td class="num">'+r.workingHrs+'</td><td class="num">'+r.leads+'</td></tr>';
36913 vikas 690
  });
691
  return h+'</tbody></table>';
692
}
693
// Funnel stage → the executives behind it (the scorecard, focused).
694
function openPFunnel(key){
695
  var map={ p_planned:['planned','Planned stops','Planned partner + lead stops per executive'],
696
            p_punchedin:['done','Planned on punch-in days','Executives, planned vs done'],
697
            p_checkedin:['done','Checked in','Visits checked in per executive'],
698
            p_checkedout:['done','Checked out (done)','Visits completed per executive'] };
699
  var m=map[key]; if(m) openPScore(m[0],m[1],m[2]);
700
}
701
// Executive day-by-day (scorecard row drill). Fetches /exec-period; each day
702
// opens the journey detail / map modal.
703
function openExecPeriod(authUserId, name){
704
  pModal('<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(name)+'</h3>'+
705
    '<p class="desc">Day-by-day &middot; '+esc(pRange())+'</p><div class="loading"><div class="spinner"></div>Loading&hellip;</div>');
706
  fetch(BASE+'/exec-period?authUserId='+authUserId+'&startDate='+encodeURIComponent(el('bj-start').value)+'&endDate='+encodeURIComponent(el('bj-end').value),{headers:{'Accept':'application/json'}})
707
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
708
    .then(function(d){
709
      var rows=d.rows||[], uid=d.userId, nm=d.name||name;
710
      var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(nm)+'</h3>'+
711
        '<p class="desc">'+rows.length+' day'+(rows.length===1?'':'s')+' &middot; '+esc(pRange())+(uid?' &middot; click a day for the journey detail':'')+'</p>';
712
      if(!rows.length){ h+='<p class="desc">No scheduled or active days in this range.</p>'; }
713
      else {
714
        h+='<table><thead><tr><th>Date</th><th>Punch In/Out</th><th class="num">Planned</th><th class="num">Completed</th><th class="num">Deferred</th><th class="num">Total</th></tr></thead><tbody>';
715
        rows.forEach(function(r){
716
          var go = uid ? ' class="clickable" onclick="openExec('+uid+',\''+js(nm)+'\',\''+r.date+'\')"' : '';
717
          h+='<tr'+go+'><td>'+esc(r.date)+'</td>'+
718
             '<td style="white-space:nowrap">'+(r.punchIn?'<span class="ptime">'+esc(hhmm(r.punchIn))+'</span>':'<span class="badflag">-</span>')+
719
               ' <span style="color:#97a1b5;font-size:11px">/ '+(r.punchOut?esc(hhmm(r.punchOut)):'--')+'</span></td>'+
720
             '<td class="num">'+r.planned+'</td><td class="num cnt cgreen">'+r.done+'</td>'+
721
             '<td class="num cnt cred">'+r.deferred+'</td><td class="num cnt cmuted">'+r.total+'</td></tr>';
722
        });
723
        h+='</tbody></table>';
724
      }
725
      el('bj-modal').innerHTML=h;
726
    })
727
    .catch(function(){ el('bj-modal').innerHTML='<button class="x" onclick="closeModal()">&times;</button><p class="desc">Could not load day-by-day.</p>'; });
728
}
729
// PJP coverage drill — execs with / without a plan (optionally one level).
730
function openCoverage(level){
731
  var all=((window._period||{}).coverageDetail)||[];
732
  var list=level ? all.filter(function(r){ return r.level===level; }) : all;
733
  var without=list.filter(function(r){ return !r.hasPlan; }), withP=list.filter(function(r){ return r.hasPlan; });
734
  function tbl(rs){
735
    if(!rs.length) return '<p class="desc">None.</p>';
736
    var h='<table><tbody>';
737
    rs.forEach(function(r){ h+='<tr class="clickable" onclick="openExecPeriod('+r.authUserId+',\''+js(r.name)+'\')"><td style="font-weight:600">'+esc(r.name)+'</td><td><span class="lvl">'+esc(r.level)+'</span></td></tr>'; });
738
    return h+'</tbody></table>';
739
  }
740
  pModal('<button class="x" onclick="closeModal()">&times;</button><h3>PJP coverage'+(level?' &middot; '+esc(level):'')+'</h3>'+
741
    '<p class="desc">'+withP.length+' of '+list.length+' have a monthly plan &middot; '+esc(pRange())+'</p>'+
742
    '<div class="sectionlabel" style="color:#e03131">No plan &middot; '+without.length+'</div>'+tbl(without)+
743
    '<div class="sectionlabel" style="color:#2f9e44;margin-top:16px">Has a plan &middot; '+withP.length+'</div>'+tbl(withP));
744
}
745
// Deferrals drill — all, or just system / genuine (from the donut segments).
746
function openDeferrals(filter){
747
  var all=((window._period||{}).deferralsList)||[];
748
  var list = filter==='system' ? all.filter(function(r){ return r.system; })
749
           : filter==='genuine' ? all.filter(function(r){ return !r.system; }) : all;
750
  var title = filter==='system' ? 'Deferrals — system-flagged' : filter==='genuine' ? 'Deferrals — genuine reason' : 'Deferrals';
751
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(title)+'</h3>'+
752
        '<p class="desc">'+list.length+' deferral'+(list.length===1?'':'s')+' &middot; '+esc(pRange())+'</p>';
753
  if(!list.length){ h+='<p class="desc">None in this range.</p>'; }
754
  else {
755
    h+='<table><thead><tr><th>Executive</th><th>Partner</th><th>Reason</th><th>Date</th><th>Status</th></tr></thead><tbody>';
756
    list.forEach(function(r){
757
      h+='<tr><td style="font-weight:600;white-space:nowrap">'+esc(r.exec)+'</td>'+
758
         '<td>'+esc(r.partner||'-')+'</td>'+
759
         '<td style="color:'+(r.system?'#f08c00':'#2f9e44')+'">'+esc(r.reason||'-')+'</td>'+
760
         '<td style="white-space:nowrap">'+esc(r.date||'')+'</td>'+
761
         '<td>'+esc(r.status||'')+'</td></tr>';
762
    });
763
    h+='</tbody></table>';
764
  }
765
  pModal(h);
766
}
36929 vikas 767
// Auto "missed" drill — the three execution-gap causes behind the card, plus
768
// the underlying deferral records (system-flagged "beat missed" / "no punch-in").
769
function openMissed(){
770
  var k=(window._period||{}).kpis||{};
771
  var rows=[
772
    ['Unscheduled', k.autoMissedUnscheduled||0, 'Executives (sales roles) with no PJP scheduled in this range'],
773
    ['Unfilled agenda', k.autoMissedUnfilledAgenda||0, 'Scheduled beat-days where the agenda was never filled'],
774
    ['Missed punch', k.autoMissedMissedPunchin||0, 'Scheduled beat-days the owner never punched in on']
775
  ];
776
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>Auto &ldquo;missed&rdquo;</h3>'+
777
        '<p class="desc">Why planned execution broke down &middot; '+esc(pRange())+'</p>'+
778
        '<table><thead><tr><th>Cause</th><th class="num">Count</th><th>What it means</th></tr></thead><tbody>';
779
  rows.forEach(function(r){
780
    h+='<tr><td style="font-weight:600;white-space:nowrap">'+esc(r[0])+'</td>'+
781
       '<td class="num cnt cred">'+num(r[1])+'</td>'+
782
       '<td style="color:#69748c">'+esc(r[2])+'</td></tr>';
783
  });
784
  h+='<tr class="boardtot"><td><b>Total</b></td><td class="num cnt"><b>'+num(k.autoMissed||0)+'</b></td><td></td></tr>';
785
  h+='</tbody></table>'+
786
     '<p class="desc" style="margin-top:12px">See also the <a href="javascript:void(0)" onclick="openDeferrals()" style="color:#3b5bdb">deferral records</a> for the partner-level &ldquo;beat missed&rdquo; / &ldquo;no punch-in&rdquo; entries.</p>';
787
  pModal(h);
788
}
36913 vikas 789
// Leads drill (period) — every lead created in the range.
790
function openPLeads(){
791
  var list=((window._period||{}).leadsList)||[];
792
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>Leads on route</h3>'+
793
        '<p class="desc">'+list.length+' lead'+(list.length===1?'':'s')+' created &middot; '+esc(pRange())+'</p>';
794
  if(!list.length){ h+='<p class="desc">No leads created in this range.</p>'; }
795
  else {
796
    h+='<table><thead><tr><th>Executive</th><th>Lead</th><th>City</th><th>Date</th><th>Status</th></tr></thead><tbody>';
797
    list.forEach(function(r){
798
      h+='<tr><td style="font-weight:600;white-space:nowrap">'+esc(r.exec)+'</td>'+
799
         '<td>'+esc(r.lead||'-')+'</td><td>'+esc(r.city||'')+'</td>'+
800
         '<td style="white-space:nowrap">'+esc(r.date||'')+'</td><td>'+esc(r.status||'')+'</td></tr>';
801
    });
802
    h+='</tbody></table>';
803
  }
804
  pModal(h);
805
}
36877 vikas 806
function names(list,n){ if(!list||!list.length) return 'None'; var s=list.slice(0,n).join(', '); if(list.length>n) s+=' +'+(list.length-n); return s; }
36882 vikas 807
var ATT_META = {
808
  notPunchedIn:    {bg:'#fff0f0', fg:'#e03131', ic:'&#9888;',   title:'Not punched in',                  sub:'executives with a beat, not started', cls:'badflag'},
36941 vikas 809
  idleStale:       {bg:'#fff4e6', fg:'#e8590c', ic:'&#9201;',   title:'Idle &mdash; off-store &gt; 59 min', sub:'stationary &gt;20 m from any store',  cls:'warnflag'},
36882 vikas 810
  geofence:        {bg:'#fff0f0', fg:'#e03131', ic:'&#128205;', title:'Check-in outside store geofence',  sub:'&gt;50 m from partner\'s saved location', cls:'badflag'},
811
  locationOff:     {bg:'#fff4e6', fg:'#e8590c', ic:'&#128244;', title:'Location turned off mid-journey',  sub:'GPS toggled off',                     cls:'warnflag'},
812
  deferredAwaiting:{bg:'#eef1f6', fg:'#69748c', ic:'&#8635;',   title:'Deferred, awaiting re-action',     sub:'shops deferred today',                cls:''}
813
};
36877 vikas 814
function attentionList(a){
36882 vikas 815
  window._att = a;
816
  var order=['notPunchedIn','idleStale','geofence','locationOff','deferredAwaiting'];
36941 vikas 817
  var h='<div class="attrow">';
36882 vikas 818
  order.forEach(function(k){
819
    var m=ATT_META[k], list=a[k]||[], n=list.length;
820
    var detail = n ? names(list.map(function(x){return x.name;}),3) : m.sub;
821
    var cls = n ? ' att clickable' : ' att';
822
    var click = n ? ' onclick="openAttention(\''+k+'\')"' : '';
823
    h+='<div class="'+cls.trim()+'"'+click+'><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.ic+'</div>'+
824
       '<div class="ab"><div class="atitle">'+m.title+'</div><div class="adet">'+detail+'</div></div>'+
825
       '<div class="acount '+(n?m.cls:'')+'">'+n+'</div>'+(n?'<span class="chev">&#9656;</span>':'')+'</div>';
826
  });
36941 vikas 827
  return h+'</div>';
36877 vikas 828
}
36882 vikas 829
function openAttention(key){
830
  var a=window._att||{}, list=a[key]||[], m=ATT_META[key]||{title:'Detail'};
831
  var mb=el('bj-modal-back'), md=el('bj-modal');
36897 vikas 832
  // Off-site check-ins can be approved here, but only by L5/Final (canApprove).
833
  var showApprove = (key==='geofence' && window._canApprove);
36882 vikas 834
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+m.title+'</h3>'+
36897 vikas 835
        '<p class="desc">'+list.length+' '+(list.length===1?'item':'items')+
836
        (showApprove?' &middot; approving updates the partner\'s saved coordinates':'')+'</p>';
36882 vikas 837
  if(!list.length){ h+='<p class="desc">Nothing here.</p>'; }
838
  else{
36941 vikas 839
    var date=window._boardDate||'';
840
    h+='<p class="desc">Click a row to open that executive\'s journey detail.</p><table><tbody>';
36882 vikas 841
    list.forEach(function(x){
36897 vikas 842
      var act='';
36941 vikas 843
      // approve button gets its own cell that swallows the click so it doesn't drill down
844
      if(showApprove) act='<td class="num" style="white-space:nowrap" onclick="event.stopPropagation()">'+(x.trackingId?'<button class="btn-ok" onclick="openValidate('+x.trackingId+')">Validate &amp; Approve</button>':'')+'</td>';
845
      var canOpen = x.userId>0;
846
      var go = canOpen ? ' class="clickable" onclick="openExec('+x.userId+",'"+js(x.name)+"','"+date+"')\"" : '';
847
      h+='<tr'+go+'><td style="font-weight:600;white-space:nowrap">'+esc(x.name)+'</td>'+
36897 vikas 848
         '<td style="color:#69748c">'+esc(x.detail||'')+'</td>'+act+'</tr>';
36882 vikas 849
    });
850
    h+='</tbody></table>';
851
  }
852
  md.innerHTML=h; mb.classList.add('show');
853
}
36897 vikas 854
// Step 2: review the check-in photo/document before approving.
855
function openValidate(trackingId){
856
  var list=(window._att&&window._att.geofence)||[], item=null;
857
  for(var i=0;i<list.length;i++){ if(list[i].trackingId===trackingId){ item=list[i]; break; } }
858
  if(!item){ return; }
859
  var img = (item.attachment && window._mediaUrl)
36903 vikas 860
    ? '<img class="valimg" src="'+esc(window._mediaUrl+item.attachment)+'" onclick="bjOpenImage(this.src)" onerror="this.outerHTML=\'<div class=&quot;valph&quot;>&#128247; Photo unavailable</div>\'">'
36897 vikas 861
    : '<div class="valph">&#128247; No photo on this check-in</div>';
862
  el('bj-modal').innerHTML='<button class="x" onclick="closeModal()">&times;</button><h3>Validate check-in</h3>'+
863
    '<p class="desc">'+esc(item.name)+' &middot; '+esc(item.detail||'')+'</p>'+
864
    '<div class="valwrap">'+img+'</div>'+
865
    '<div class="valactions">'+
866
      '<button class="exectab" onclick="openAttention(\'geofence\')">&larr; Back</button>'+
867
      '<button class="btn-ok" onclick="approveValidated('+trackingId+',this)">Approve</button>'+
868
    '</div>';
869
}
870
function approveValidated(trackingId, btn){
871
  btn.disabled=true; btn.textContent='Approving…';
872
  fetch(CTX+'/beat-journey/approve-checkin',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'trackingId='+trackingId})
873
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
874
    .then(function(){
875
      if(window._att && window._att.geofence){ window._att.geofence = window._att.geofence.filter(function(x){ return x.trackingId!==trackingId; }); }
876
      if(window._att && window._att.geofence && window._att.geofence.length) openAttention('geofence');
877
      else closeModal();
878
    })
879
    .catch(function(){ btn.disabled=false; btn.textContent='Approve'; alert('Approve failed (not authorised, or server error).'); });
880
}
36877 vikas 881
 
882
/* ============================ PERIOD ============================ */
883
function loadPeriod(){
884
  spinner();
885
  var u = BASE + '/data?startDate=' + encodeURIComponent(el('bj-start').value) + '&endDate=' + encodeURIComponent(el('bj-end').value) + qs();
886
  fetch(u, {headers:{'Accept':'application/json'}})
887
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
888
    .then(renderPeriod).catch(fail);
889
}
890
function tile(t,v){ return '<div class="tile"><div class="t">'+t+'</div><div class="v">'+v+'</div></div>'; }
891
function renderPeriod(d){
36913 vikas 892
  window._period = d;          // drill-downs read scorecard / lists from here
36877 vikas 893
  var k=d.kpis, f=d.funnel, df=d.deferral, u=d.utilization, t=d.travel, o=d.outcomes;
894
  var neverTouched = Math.max((f.plannedStops||0)-(f.checkedIn||0)-(df.total||0),0);
895
  var h='';
896
  h+='<div class="kpis">';
36929 vikas 897
  h+=kpi('&#9878;','#fff4e6','#f08c00','Adherence',k.adherencePct+'<small>%</small>',num(k.doneStops)+' of '+num(k.plannedStops)+' planned visits done',adhColor(k.adherencePct),"openPScore('adherencePct','Adherence','Planned visits done vs planned, per executive')");
36913 vikas 898
  h+=kpi('&#128506;','#e7f5ff','#1098ad','PJP coverage L1',k.coverageL1Pct+'<small>%</small>',k.coverageL1With+'/'+k.coverageL1Total+' have a plan','#1098ad',"openCoverage('L1')");
36929 vikas 899
  h+=kpiCols('&#128694;','#ebfbee','#2f9e44','Average Visit (per day)',
36941 vikas 900
    [['Franchisee',k.avgPartnersPerActiveDay],['Lead',k.avgLeadsPerActiveDay]],
36929 vikas 901
    null,"openPScore('done','Visits / active day','Visits completed per executive')");
902
  h+=kpiCols('&#128172;','#eef1fb','#3b5bdb','Average discussion (per executive)',
903
    [['Partner',k.avgDiscussionPartnerMin],['Lead',k.avgDiscussionLeadMin]],
904
    k.avgDiscussionMin>0&&k.avgDiscussionMin<30?'#e8590c':null,"openPScore('discussionMin','Average discussion minutes','Avg in-store discussion per executive')",'min');
905
  h+=kpiCols('&#8635;','#fff0f0','#e03131','Auto "missed"',
906
    [['Unscheduled',k.autoMissedUnscheduled],['Unfilled agenda',k.autoMissedUnfilledAgenda],['Missed punch',k.autoMissedMissedPunchin]],
907
    '#e03131',"openMissed()");
36913 vikas 908
  h+=kpi('&#9733;','#fff0f6','#d6336c','Leads on route',num(k.leadsCreated),'this period',null,"openPLeads()");
36877 vikas 909
  h+='</div>';
910
 
36941 vikas 911
  h+='<div class="sectionlabel">Journey Summary</div><div class="card"><p class="desc">Planned (PJP) and self-assigned visits combined.</p><div class="funnel">'+summaryCards(d.summary)+'</div></div>';
36877 vikas 912
 
913
  h+='<div class="sectionlabel">Adherence &amp; Coverage</div><div class="grid g3">';
914
  h+='<div class="card"><h2>Per-executive scorecard <span style="color:#97a1b5;font-weight:500;font-size:12px">&middot; '+d.scorecard.length+' executives</span></h2><p class="desc">The coaching list &mdash; click a header to sort. Reds are where to intervene.</p>'+scorecardTable(d.scorecard)+'</div>';
915
  h+='<div class="card"><h2>Coverage by sales level</h2><p class="desc">Filled = executives with a plan; light = total at that level.</p>'+coverageBars(d.coverageByLevel)+utilBlock(u)+'</div>';
916
  h+='</div>';
917
 
918
  h+='<div class="sectionlabel">Deferrals, Travel &amp; Outcomes</div><div class="grid g2">';
919
  h+='<div class="card"><h2>Deferral nature</h2><p class="desc">Deliberate, or just auto-flagged missed beats?</p>'+deferDonut(df)+'</div>';
920
  h+='<div class="card"><h2>Travel &amp; route quality</h2><p class="desc">Straight-line distance per leg between consecutive stops.</p>'+travelBlock(t)+'</div>';
921
  h+='</div>';
922
 
923
  h+='<div class="sectionlabel">Outcomes &amp; Visit Quality</div><div class="card"><p class="desc">Captured on the check-out form &mdash; the substance of each store conversation.</p>'+
924
     '<div class="tiles" style="grid-template-columns:repeat(4,1fr)">'+
925
     tile('Partner remark filled', o.remarkFilledPct+'<small>%</small>')+
926
     tile('Avg partner rating', (o.avgRating||0)+'<small>/5</small>')+
927
     tile('Audit checklist done', o.auditDonePct+'<small>%</small>')+
928
     tile('Next-visit follow-up set', o.nextVisitPct+'<small>%</small>')+
929
     '</div></div>';
930
 
931
  h+='<div class="sectionlabel">What to fix</div>'+findingsBlock(d.findings);
932
  h+=sourcesCard();
933
  el('bj-content').innerHTML=h;
934
  window._scorecard = d.scorecard;
935
}
936
var sortKey=null, sortAsc=false;
937
function sortCard(key){
938
  if(sortKey===key) sortAsc=!sortAsc; else { sortKey=key; sortAsc=false; }
939
  window._scorecard.sort(function(a,b){ var x=a[key],y=b[key];
940
    if(typeof x==='string') return sortAsc? (''+x).localeCompare(y):(''+y).localeCompare(x);
941
    return sortAsc? x-y : y-x; });
942
  document.getElementById('scTbl').outerHTML = scorecardTable(window._scorecard);
943
}
944
function scorecardTable(rows){
945
  if(!rows||!rows.length) return '<p class="desc">No beat owners in scope for this period.</p>';
946
  var h='<table id="scTbl"><thead><tr>'+
947
    '<th onclick="sortCard(\'name\')">Executive</th>'+
948
    '<th class="num" onclick="sortCard(\'planned\')">Plan</th>'+
949
    '<th class="num" onclick="sortCard(\'done\')">Done</th>'+
950
    '<th class="num" onclick="sortCard(\'adherencePct\')">Adher.</th>'+
37028 vikas 951
    '<th class="num" onclick="sortCard(\'avgLeadVisitsPerDay\')" title="Avg lead visits per active (punched-in) day">Lead/day</th>'+
952
    '<th class="num" onclick="sortCard(\'avgFranchiseeVisitsPerDay\')" title="Avg franchisee visits per active (punched-in) day">Fr/day</th>'+
36877 vikas 953
    '<th class="num" onclick="sortCard(\'discussionMin\')">Disc.</th>'+
954
    '<th class="num" onclick="sortCard(\'workingHrs\')">Hrs</th>'+
37028 vikas 955
    '<th class="num" onclick="sortCard(\'leads\')">Leads</th></tr></thead><tbody>';
36877 vikas 956
  rows.forEach(function(r){
957
    var c=adhColor(r.adherencePct);
37028 vikas 958
    h+='<tr class="clickable" onclick="openExecPeriod('+r.authUserId+',\''+js(r.name)+'\')"><td><span class="lvl">'+esc(r.level)+'</span>'+esc(r.name)+'</td>'+
36877 vikas 959
       '<td class="num">'+r.planned+'</td><td class="num">'+r.done+'</td>'+
960
       '<td class="num"><b style="color:'+c+'">'+r.adherencePct+'%</b><span class="meter"><i style="width:'+Math.min(100,r.adherencePct)+'%;background:'+c+'"></i></span></td>'+
37028 vikas 961
       '<td class="num">'+(r.avgLeadVisitsPerDay||'-')+'</td>'+
962
       '<td class="num">'+(r.avgFranchiseeVisitsPerDay||'-')+'</td>'+
36882 vikas 963
       '<td class="num'+(r.discussionMin>0&&r.discussionMin<10?' warnflag':'')+'">'+(r.discussionMin||'-')+(r.discussionMin?'m':'')+'</td>'+
37028 vikas 964
       '<td class="num">'+r.workingHrs+'</td><td class="num">'+r.leads+'</td></tr>';
36877 vikas 965
  });
966
  return h+'</tbody></table>';
967
}
968
function coverageBars(rows){
969
  if(!rows||!rows.length) return '<p class="desc">No coverage data.</p>';
970
  var max=0; rows.forEach(function(r){ if(r.totalUsers>max)max=r.totalUsers; }); if(!max)max=1;
971
  var h=''; rows.forEach(function(r){
972
    var w=pct(r.withPjp,max), wt=pct(r.totalUsers,max);
36913 vikas 973
    h+='<div class="barrow clickable" onclick="openCoverage(\''+js(r.level)+'\')" title="Click to see these executives"><div class="name">'+esc(r.level)+'</div><div class="track">'+
36877 vikas 974
       '<div style="position:absolute;inset:0;width:'+wt+'%;background:#e3e8f5;border-radius:7px"></div>'+
975
       '<div class="fill" style="width:'+w+'%;position:relative;background:linear-gradient(90deg,#1098ad,#22b8cf)">'+(r.withPjp||'')+'</div></div>'+
976
       '<div class="meta">'+r.withPjp+'/'+r.totalUsers+' &middot; '+r.coveragePct+'%</div></div>';
977
  });
978
  return h;
979
}
980
function utilBlock(u){
981
  return '<h2 style="margin-top:18px">Working-hour utilization</h2><p class="desc">Where the average working day goes.</p>'+
982
    '<div class="util">'+
983
    '<div style="width:'+u.inStorePct+'%;background:#2f9e44">In-store '+u.inStorePct+'%</div>'+
984
    '<div style="width:'+u.travelPct+'%;background:#3b5bdb">Travel '+u.travelPct+'%</div>'+
985
    '<div style="width:'+u.idlePct+'%;background:#e03131">Idle '+u.idlePct+'%</div></div>'+
986
    '<div class="utlegend"><span><span class="dot" style="background:#2f9e44;margin:0"></span>Selling '+u.inStoreHrs+' h</span>'+
987
    '<span><span class="dot" style="background:#3b5bdb;margin:0"></span>Travel '+u.travelHrs+' h</span>'+
988
    '<span><span class="dot" style="background:#e03131;margin:0"></span>Idle '+u.idleHrs+' h</span></div>';
989
}
990
function deferDonut(df){
991
  var sysPct=df.systemPct||0;
992
  var g='conic-gradient(#f59f00 0 '+sysPct+'%, #2f9e44 '+sysPct+'% 100%)';
36913 vikas 993
  return '<div class="donutwrap"><div class="donut clickable" onclick="openDeferrals()" title="Click to see all deferrals" style="background:'+g+'"><div class="center">'+
36877 vikas 994
    '<div style="font-size:24px;font-weight:780">'+num(df.total)+'</div><div style="font-size:11px;color:#97a1b5">deferrals</div></div></div>'+
995
    '<div class="legend">'+
36913 vikas 996
    '<div class="it clickable" onclick="openDeferrals(\'system\')"><span class="dot" style="background:#f59f00"></span><div><b>'+df.systemGenerated+'</b> system auto-flagged ('+sysPct+'%)<br><span style="color:#97a1b5;font-size:11.5px">"beat missed", "no punch-in"</span></div></div>'+
997
    '<div class="it clickable" onclick="openDeferrals(\'genuine\')"><span class="dot" style="background:#2f9e44"></span><div><b>'+df.human+'</b> genuine reason ('+df.humanPct+'%)</div></div>'+
36877 vikas 998
    '<div class="it"><span class="dot" style="background:#3b5bdb"></span><div><b>'+df.actioned+'</b> acted on by a head'+(df.avgDaysToAction?'<br><span style="color:#97a1b5;font-size:11.5px">avg '+df.avgDaysToAction+' days to action</span>':'')+'</div></div>'+
36913 vikas 999
    '</div></div><p class="desc" style="margin-top:13px">Click the chart for all deferrals, or a legend row for system / genuine. "System" vs "genuine" is read from the deferral reason.</p>';
36877 vikas 1000
}
1001
function travelBlock(t){
1002
  var rows=t.legBuckets||[], max=0; rows.forEach(function(r){ if(r.count>max)max=r.count; }); if(!max)max=1;
1003
  var colors={'0-2 km':'#2f9e44','2-5 km':'#2f9e44','5-15 km':'#82c91e','15-50 km':'#f59f00','50 km+':'#e03131'};
1004
  var h=''; rows.forEach(function(r){
1005
    h+='<div class="barrow"><div class="name">'+esc(r.bucket)+'</div><div class="track"><div class="fill" style="width:'+pct(r.count,max)+'%;background:'+(colors[r.bucket]||'#3b5bdb')+'">'+r.count+'</div></div><div class="meta"></div></div>';
1006
  });
1007
  h+='<div class="tiles" style="margin-top:14px">'+
1008
     tile('Avg leg', t.avgLegKm+'<small> km</small>')+
1009
     tile('Legs &gt; 15 km', t.pctOver15+'<small>%</small>')+
1010
     tile('Actual / estimate', (t.actualVsEstimateRatio||0)+'<small>&times;</small>')+'</div>';
1011
  return h;
1012
}
1013
function findingsBlock(items){
1014
  if(!items||!items.length) return '<div class="callout"><h2>Nothing flagged</h2><p class="desc">No issues crossed the alert thresholds for this period.</p></div>';
1015
  var sev={high:'#e03131',med:'#f59f00',low:'#2f9e44'};
1016
  var h='<div class="callout"><h2>Recommended management actions</h2><p class="desc">Generated from this period\'s data.</p>';
1017
  items.forEach(function(x){
1018
    h+='<div class="fix"><div class="sev" style="background:'+(sev[x.severity]||'#3b5bdb')+'"></div><div class="fb">'+
1019
       '<div class="ft">'+esc(x.title)+'</div><div class="fd">'+esc(x.detail)+'</div>'+
1020
       '<div class="act">&rarr; '+esc(x.action)+'</div></div></div>';
1021
  });
1022
  return h+'</div>';
1023
}
1024
function sourcesCard(){
1025
  return '<div class="sectionlabel">Where the numbers come from</div><div class="card">'+
1026
    '<p class="desc">Nothing new needs to be captured &mdash; everything here is built from what the field app already records on each journey.</p>'+
1027
    '<ul style="margin:0;padding-left:18px;line-height:1.95;font-size:13px;color:#3a4459">'+
1028
    '<li>The <b>journey timeline</b> (punch-in, check-ins/outs, deferrals, punch-out) comes from what the executive taps in the app.</li>'+
1029
    '<li><b>Adherence</b> compares the partners planned on each beat against the stores actually visited.</li>'+
1030
    '<li><b>Time, travel and distance</b> use the in-store and travel durations logged per visit.</li>'+
1031
    '<li><b>Geofence / fake-visit checks</b> compare the check-in GPS against the partner\'s saved shop location (flagged beyond ~50 m).</li>'+
1032
    '<li><b>Visit outcomes</b> (remarks, rating, audit, next visit) come from the check-out form.</li>'+
1033
    '<li><b>Coverage and the manager view</b> follow the existing L1&ndash;L5 sales hierarchy, so each manager sees only their team.</li>'+
1034
    '</ul></div>';
1035
}
1036
 
1037
/* ============================ EXEC DRILLDOWN ============================ */
36897 vikas 1038
function openExec(userId, name, date, tab){
36877 vikas 1039
  if(!userId){ return; }
36897 vikas 1040
  window._exec = {userId:userId, name:name, date:date, detail:null, tab:(tab||'timeline')};
36877 vikas 1041
  var mb=el('bj-modal-back'), m=el('bj-modal');
1042
  m.innerHTML='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(name)+'</h3><p class="desc">Journey detail &middot; '+esc(date)+'</p><div class="loading"><div class="spinner"></div>Loading&hellip;</div>';
1043
  mb.classList.add('show');
36882 vikas 1044
  fetch(CTX+'/beat-journey/journey-detail?userId='+userId+'&date='+encodeURIComponent(date),{headers:{'Accept':'application/json'}})
36877 vikas 1045
    .then(function(r){ return r.json(); }).then(function(d){
36882 vikas 1046
      window._mediaUrl = d.mediaUrl || '';
36897 vikas 1047
      window._exec.detail = d;
1048
      renderExec(window._exec.tab);
1049
    }).catch(function(){ el('bj-modal').innerHTML='<button class="x" onclick="closeModal()">&times;</button><p class="desc">Could not load detail.</p>'; });
1050
}
1051
function renderExec(tab){
1052
  var ex=window._exec; if(!ex) return;
1053
  var d=ex.detail||{};
1054
  var head='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(ex.name)+'</h3>'+
1055
    '<p class="desc">Journey detail &middot; '+esc(ex.date)+' &middot; battery '+(d.batteryLevel==null?'-':d.batteryLevel+'%')+' &middot; loc-off '+(d.locationToggleCount||0)+'</p>'+
1056
    '<div class="exectabs">'+
1057
      '<button class="exectab'+(tab==='timeline'?' active':'')+'" onclick="renderExec(\'timeline\')">&#128221; Timeline</button>'+
1058
      '<button class="exectab'+(tab==='map'?' active':'')+'" onclick="renderExec(\'map\')">&#128205; Live Location</button>'+
1059
    '</div>';
1060
  if(tab==='map'){
36903 vikas 1061
    el('bj-modal').innerHTML=head+'<div id="bjRouteLegend" class="bjlegend"></div>'+
1062
      '<div id="bjMap"><div class="loading"><div class="spinner"></div>Loading map&hellip;</div></div>';
36897 vikas 1063
    bjShowMap(ex.userId, ex.date);
1064
  } else {
1065
    el('bj-modal').innerHTML=head+buildTimelineHtml(d, ex.date);
1066
  }
1067
}
1068
function buildTimelineHtml(d, date){
1069
  var all=(d.visits||[]).slice();
1070
  // Sequence like the field report: Punch in -> visited stops (by check-in time)
1071
  // -> PENDING/not-visited -> Punch out. The attendance row carries both punch-in
1072
  // & punch-out times; split it into the two bookends.
1073
  var att=null, visited=[], pending=[];
1074
  all.forEach(function(x){
1075
    var tt=(x.taskType||'').toLowerCase(), mt=(x.markType||'').toUpperCase();
1076
    if(tt==='attendance' || mt.indexOf('PUNCH')>=0){ if(!att) att=x; }
1077
    else if(x.checkInTime){ visited.push(x); }
1078
    else { pending.push(x); }
1079
  });
1080
  visited.sort(function(a,b){ return tlSecs(a.checkInTime)-tlSecs(b.checkInTime); });
36882 vikas 1081
 
36903 vikas 1082
  var distKm=0, inStoreSec=0, leadsN=0;
36897 vikas 1083
  all.forEach(function(x){
1084
    var tt=(x.taskType||'').toLowerCase();
1085
    if(tt==='attendance') return;
1086
    if(x.totalDistance) distKm += (parseFloat(x.totalDistance)||0);
1087
    inStoreSec += toSec(x.timeSpent);
1088
    if(tt==='lead') leadsN++;
1089
  });
1090
  var workSec = (att && att.checkInTime && att.checkOutTime) ? (toSec(att.checkOutTime)-toSec(att.checkInTime)) : (att?toSec(att.timeSpent):0);
1091
  if(workSec<0) workSec=0;
36903 vikas 1092
  // Travel = working − in-store, so In-store + Travel = Working hours exactly
1093
  // (summing per-leg transit under-counts the idle/waiting between stops).
1094
  var transitSec = Math.max(0, workSec - inStoreSec);
36882 vikas 1095
 
36897 vikas 1096
  var seq=[];
1097
  if(att && att.checkInTime) seq.push(punchEntry('in', att.checkInTime));
1098
  visited.forEach(function(x){ seq.push(x); });
1099
  pending.forEach(function(x){ seq.push(x); });
1100
  if(att && att.checkOutTime) seq.push(punchEntry('out', att.checkOutTime));
36882 vikas 1101
 
36897 vikas 1102
  var h='<div class="jstats">'+
1103
    jstat(fmtSec(workSec),'Working hours')+
1104
    jstat(fmtSec(inStoreSec),'In-store time')+
1105
    jstat(fmtSec(transitSec),'Travel time')+
1106
    jstat(distKm.toFixed(2)+' km','Distance Covered')+
36905 vikas 1107
    jstat(visited.length+(leadsN?' / '+leadsN+'L':''),'Visits / Leads')+
36897 vikas 1108
    '</div>';
1109
  if(!seq.length){ return h+'<p class="desc">No tracking events for this day.</p>'; }
1110
  h+='<div class="tl">';
1111
  var ri=0;
1112
  seq.forEach(function(x){
1113
    if(!x._punch && x.checkInTime){
1114
      var tr=(x.transitTime && x.transitTime!=='00:00:00') ? x.transitTime : null;
1115
      var km=(x.totalDistance && parseFloat(x.totalDistance)>0) ? (parseFloat(x.totalDistance).toFixed(2)+' km') : null;
36955 vikas 1116
      var eta=(x.estimatedTime && x.estimatedTime!=='00:00:00') ? x.estimatedTime : null;
1117
      if(tr || km || eta){
1118
        var parts=[]; if(tr) parts.push('&#128663; '+esc(tr)); if(km) parts.push(esc(km)); if(eta) parts.push('ETA '+esc(eta));
1119
        // flag the leg red when actual transit exceeds 1.5x the ETA (same rule as the export)
1120
        var overrun = eta && toSec(tr) > 1.5*toSec(eta);
1121
        h+='<div class="tlgap"><span class="gappill'+(overrun?' overrun':'')+'"'+(overrun?' title="Travel overran 1.5x the ETA"':'')+'>'+parts.join(' &middot; ')+'</span></div>';
36877 vikas 1122
      }
36897 vikas 1123
    }
1124
    h+=tlRow(x, ri%2===0?'left':'right'); ri++;
1125
  });
1126
  h+='</div>';
1127
  return h;
36877 vikas 1128
}
36897 vikas 1129
 
1130
/* ---- live location map (reuses /beat-report/live-tracking pathPoints) ---- */
1131
function bjLoadMaps(cb){
1132
  if(window.google && window.google.maps){ cb(); return; }
1133
  window._mapsCbs = window._mapsCbs || [];
1134
  window._mapsCbs.push(cb);
1135
  if(window._mapsLoading) return;
1136
  window._mapsLoading=true;
1137
  window.__bjMapsReady=function(){ (window._mapsCbs||[]).forEach(function(f){ try{f();}catch(e){} }); window._mapsCbs=[]; };
1138
  var s=document.createElement('script');
1139
  s.src='https://maps.googleapis.com/maps/api/js?key=AIzaSyAckO0y4Z6WhBOuMjNjioWLSYZDhGEvGBc&libraries=geometry&v=weekly&callback=__bjMapsReady';
1140
  s.async=true; document.head.appendChild(s);
1141
}
1142
function bjShowMap(userId, date){
1143
  bjLoadMaps(function(){
1144
    fetch(CTX+'/beat-journey/track-map?userId='+userId+'&date='+encodeURIComponent(date),{headers:{'Accept':'application/json'}})
1145
      .then(function(r){ return r.json(); }).then(function(data){ bjDrawMap(data); })
1146
      .catch(function(){ var e=document.getElementById('bjMap'); if(e) e.innerHTML='<div class="loading">Could not load location.</div>'; });
1147
  });
1148
}
1149
function bjMarkColor(mt){
1150
  mt=(mt||'').toUpperCase();
1151
  if(mt.indexOf('CHECKOUT')>=0) return '#2f9e44';
1152
  if(mt==='CHECKIN') return '#f59f00';
1153
  if(mt==='DEFERRED') return '#e8590c';
1154
  if(mt==='PENDING') return '#97a1b5';
1155
  return '#3b5bdb';
1156
}
1157
function bjMarkInfo(v,color){
1158
  return '<div style="font-size:12px;max-width:240px"><b>'+esc(v.name||'')+'</b><br>'+
1159
    '<span style="background:'+color+';color:#fff;border-radius:4px;padding:1px 6px;font-size:10px">'+esc(v.markType||'')+'</span>'+
1160
    (v.checkInTime?'<br>In: <b>'+esc(v.checkInTime)+'</b>':'')+
1161
    (v.checkOutTime?'<br>Out: <b>'+esc(v.checkOutTime)+'</b>':'')+
1162
    (v.timeSpent?'<br>Time spent: <b>'+esc(v.timeSpent)+'</b>':'')+
1163
    (v.address?'<br>'+esc(v.address):'')+'</div>';
1164
}
1165
// Teardrop pin (same shape as Beat Report) with a white disc + label.
1166
function bjPin(color, label){
1167
  var svg='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="40" viewBox="0 0 28 40">'+
1168
    '<path d="M14 0C6.268 0 0 6.268 0 14c0 10.5 14 26 14 26s14-15.5 14-26C28 6.268 21.732 0 14 0z" fill="'+color+'"/>'+
1169
    '<circle cx="14" cy="14" r="7" fill="#ffffff"/>'+
1170
    '<text x="14" y="18" text-anchor="middle" font-size="10" font-weight="bold" fill="'+color+'">'+label+'</text></svg>';
1171
  return {url:'data:image/svg+xml;charset=UTF-8,'+encodeURIComponent(svg), scaledSize:new google.maps.Size(28,40), anchor:new google.maps.Point(14,40)};
1172
}
1173
// Larger pin sized to fit a duration label (idle stops).
1174
function bjStopPin(label){
1175
  var s=String(label), d=Math.max(40, 14+s.length*7), H=d+10, r=d/2;
1176
  var svg='<svg xmlns="http://www.w3.org/2000/svg" width="'+d+'" height="'+H+'" viewBox="0 0 '+d+' '+H+'">'+
1177
    '<polygon points="'+(r-7)+','+(d-7)+' '+(r+7)+','+(d-7)+' '+r+','+H+'" fill="#e8590c"/>'+
1178
    '<circle cx="'+r+'" cy="'+r+'" r="'+(r-2)+'" fill="#e8590c" stroke="#ffffff" stroke-width="2"/>'+
1179
    '<text x="'+r+'" y="'+(r+4)+'" text-anchor="middle" font-size="12" font-weight="bold" fill="#ffffff">'+s+'</text></svg>';
1180
  return {url:'data:image/svg+xml;charset=UTF-8,'+encodeURIComponent(svg), scaledSize:new google.maps.Size(d,H), anchor:new google.maps.Point(r,H)};
1181
}
1182
function fmtDur2(sec){ sec=sec||0; var m=Math.floor(sec/60), s=sec%60; return m+'m'+(s>0?' '+s+'s':''); }
1183
function bjDrawMap(data){
1184
  var box=document.getElementById('bjMap'); if(!box) return;
1185
  box.innerHTML='';
1186
  var map=new google.maps.Map(box,{zoom:12,center:{lat:20.5937,lng:78.9629},mapTypeControl:true,streetViewControl:false});
1187
  var bounds=new google.maps.LatLngBounds(), has=false;
1188
  function pin(pos,icon,zi,title,info){
1189
    has=true; bounds.extend(pos);
1190
    var m=new google.maps.Marker({position:pos,map:map,zIndex:zi||100,icon:icon,title:title||''});
1191
    if(info){ var iw=new google.maps.InfoWindow({content:info}); m.addListener('click',function(){ iw.open(map,m); }); }
1192
    return m;
1193
  }
1194
 
36903 vikas 1195
  // 1) last-known location marker (the GPS trail itself is drawn as the "taken"
1196
  // route in bjDrawRoutes, straight from location_tracking_path).
36897 vikas 1197
  var pts=(data.path||[]).map(function(p){ return {lat:p.lat,lng:p.lng}; });
1198
  if(pts.length){
1199
    pts.forEach(function(p){ bounds.extend(p); has=true; });
1200
    var lastPt=pts[pts.length-1];
1201
    var lk=new google.maps.Marker({position:lastPt,map:map,zIndex:999,title:'Last Known Location',
1202
      icon:{url:CTX+'/resources/images/salesman.png',scaledSize:new google.maps.Size(40,40),anchor:new google.maps.Point(20,20)}});
1203
    var lkIw=new google.maps.InfoWindow({content:'<div style="font-size:12px"><b>&#128205; Last known location</b></div>'});
1204
    lk.addListener('click',function(){ lkIw.open(map,lk); });
1205
  }
1206
 
1207
  // 2) idle stops (>=10 min within 50 m)
1208
  (data.idleStops||[]).forEach(function(s){
1209
    var lbl=fmtDur2(s.seconds);
1210
    pin({lat:s.lat,lng:s.lng}, bjStopPin(lbl), 80, 'Idle '+lbl,
1211
      '<div style="font-size:12px"><b>&#9201; Idle stop</b><br>Stayed ~'+esc(lbl)+' within 50 m</div>');
1212
  });
1213
 
36954 vikas 1214
  // 3) every visit — visited stops are numbered in array order; pending / deferred
1215
  // stops (plotted at their planned store location) get a neutral dot and sit
1216
  // below the visited pins.
36897 vikas 1217
  var idx=0;
1218
  (data.visits||[]).forEach(function(v){
1219
    var color=bjMarkColor(v.markType);
36954 vikas 1220
    var visited = !!v.checkInTime;
1221
    pin({lat:v.lat,lng:v.lng}, bjPin(color, visited?String(++idx):'•'), visited?100:60,
36897 vikas 1222
      (v.name||'')+' ('+v.markType+')', bjMarkInfo(v,color));
1223
  });
1224
 
1225
  // 4) punch in / punch out
1226
  if(data.punchIn){
1227
    pin({lat:data.punchIn.lat,lng:data.punchIn.lng}, bjPin('#2f9e44','P'), 300,
1228
      'Punch in'+(data.punchIn.time?' · '+data.punchIn.time:''),
1229
      '<div style="font-size:12px"><b>&#9873; Punch in</b>'+(data.punchIn.time?'<br>'+esc(data.punchIn.time):'')+'</div>');
1230
  }
1231
  if(data.punchOut){
1232
    pin({lat:data.punchOut.lat,lng:data.punchOut.lng}, bjPin('#7048e8','X'), 300,
1233
      'Punch out'+(data.punchOut.time?' · '+data.punchOut.time:''),
1234
      '<div style="font-size:12px"><b>&#9873; Punch out</b>'+(data.punchOut.time?'<br>'+esc(data.punchOut.time):'')+'</div>');
1235
  }
1236
 
36903 vikas 1237
  // 5) routes — actual road taken vs Google-suggested optimal, for comparison.
37028 vikas 1238
  // Suggested-route checkpoints = the whole day's stops (planned + visited), not
1239
  // just the ones already visited, so the suggestion shows from punch-in onward
1240
  // (and even before the first check-in). optimizeWaypoints reorders them, so the
1241
  // input order only needs to keep punch-in first / punch-out last; visited stops
1242
  // are listed by check-in time and still-pending stops after them.
36903 vikas 1243
  var cps=[];
1244
  if(data.punchIn) cps.push({lat:data.punchIn.lat,lng:data.punchIn.lng});
1245
  (data.visits||[]).slice()
37028 vikas 1246
    .filter(function(v){ return v.lat && v.lng; })                   // every stop with coords
36903 vikas 1247
    .sort(function(a,b){ return tlSecs(a.checkInTime)-tlSecs(b.checkInTime); })
1248
    .forEach(function(v){ cps.push({lat:v.lat,lng:v.lng}); });
1249
  if(data.punchOut) cps.push({lat:data.punchOut.lat,lng:data.punchOut.lng});
36929 vikas 1250
  // Actual time window of the GPS trail (first → last breadcrumb timestamp),
1251
  // shown on the taken-route click detail alongside the driving estimate.
1252
  var takenTime='';
1253
  var dp=data.path||[];
1254
  if(dp.length>=2 && dp[0].ts && dp[dp.length-1].ts && dp[dp.length-1].ts>dp[0].ts){
1255
    var t0=dp[0].ts, t1=dp[dp.length-1].ts;
1256
    takenTime=bjClock(t0)+' &rarr; '+bjClock(t1)+' ('+bjElapsed(t1-t0)+')';
1257
  }
1258
  bjDrawRoutes(map, cps, pts, takenTime, dp);
36903 vikas 1259
 
36897 vikas 1260
  if(has){
1261
    map.fitBounds(bounds);
1262
    google.maps.event.addListenerOnce(map,'idle',function(){ if(map.getZoom()>16) map.setZoom(16); });
1263
  } else {
1264
    box.innerHTML='<div class="loading">No GPS / location recorded for this day.</div>';
1265
  }
1266
}
36903 vikas 1267
// TAKEN route = the recorded GPS trail (location_tracking_path) routed along the
1268
// road network so it follows actual roads rather than straight hops between sparse
1269
// pings. SUGGESTED route = the Google-optimal road route through the journey's
1270
// checkpoints (green dotted). Both are drawn and compared by distance.
36929 vikas 1271
function bjDrawRoutes(map, cps, pathPts, takenTime, timedPts){
36903 vikas 1272
  var legend=bjRouteLegend();
1273
 
1274
  // taken — road route traced through the recorded breadcrumb (in order)
1275
  if(pathPts && pathPts.length>=2){
1276
    var ds1=new google.maps.DirectionsService();
1277
    var sample=bjSample(pathPts, 25);                          // Directions cap: 25 incl. ends
1278
    var o=sample[0], d=sample[sample.length-1];
1279
    var vias=sample.slice(1,-1).map(function(p){ return {location:new google.maps.LatLng(p.lat,p.lng), stopover:false}; });
1280
    bjRouteRequest(ds1, o, d, vias, false, function(res){
36929 vikas 1281
      bjRenderRoute(map, res, {color:'#e03131', dashed:false, z:55, label:'Route taken (actual GPS)', time:takenTime, timed:timedPts});
36903 vikas 1282
      legend.set('taken', bjRouteKm(res));
1283
    }, function(status){
1284
      console.warn('Directions (taken) failed:', status);
36929 vikas 1285
      // fallback: plot the raw breadcrumb (straight hops), with arrows, and measure along it
1286
      var poly=new google.maps.Polyline({path:pathPts,geodesic:false,strokeColor:'#e03131',strokeOpacity:.9,strokeWeight:4,zIndex:55,map:map,
1287
        icons:[{icon:{path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW,strokeColor:'#e03131',fillColor:'#e03131',fillOpacity:1,scale:3},offset:'3%',repeat:'120px'}]});
1288
      var km=google.maps.geometry.spherical.computeLength(pathPts.map(function(p){ return new google.maps.LatLng(p.lat,p.lng); }))/1000;
1289
      bjRouteClick(map, poly, '#e03131', 'Route taken (actual GPS)', km, '', takenTime, timedPts);
1290
      legend.set('taken', km);
36903 vikas 1291
    });
1292
  } else {
1293
    legend.set('taken', false);
1294
  }
1295
 
1296
  // suggested — Google-optimal route through punch-in → visits → punch-out
1297
  if(cps.length>=2){
1298
    var ds=new google.maps.DirectionsService();
1299
    var origin=cps[0], dest=cps[cps.length-1], mids=cps.slice(1,-1), capped=false;
1300
    if(mids.length>23){ mids=mids.slice(0,23); capped=true; }  // Directions allows 23 waypoints
1301
    var wpts=mids.map(function(p){ return {location:new google.maps.LatLng(p.lat,p.lng), stopover:true}; });
1302
    bjRouteRequest(ds, origin, dest, wpts, true, function(res){
36929 vikas 1303
      bjRenderRoute(map, res, {color:'#2f9e44', dashed:true, z:50, label:'Suggested route (optimal)'});
36903 vikas 1304
      legend.set('suggested', bjRouteKm(res));
1305
    }, function(status){ console.warn('Directions (suggested) failed:', status); legend.set('suggested', false); });
1306
    if(capped) legend.note('Suggested route limited to first 23 stops');
1307
  } else {
1308
    legend.set('suggested', false);
1309
  }
1310
}
1311
// Evenly downsample a list to at most `max` items, always keeping first and last.
1312
function bjSample(arr, max){
1313
  if(arr.length<=max) return arr.slice();
1314
  var out=[], step=(arr.length-1)/(max-1);
1315
  for(var i=0;i<max;i++) out.push(arr[Math.round(i*step)]);
1316
  return out;
1317
}
1318
function bjRouteRequest(ds, origin, dest, wpts, optimize, ok, err){
1319
  ds.route({
1320
    origin:new google.maps.LatLng(origin.lat,origin.lng),
1321
    destination:new google.maps.LatLng(dest.lat,dest.lng),
1322
    waypoints:wpts, optimizeWaypoints:optimize,
1323
    travelMode:google.maps.TravelMode.DRIVING
1324
  }, function(res, status){
1325
    if(status===google.maps.DirectionsStatus.OK && res && res.routes && res.routes.length) ok(res);
1326
    else err(status);
1327
  });
1328
}
36929 vikas 1329
// Draw a route as a custom polyline (so we can add direction arrows + a click
1330
// info window). Forward arrows are repeated along the line; dashed routes also
1331
// get the dash pattern. Clicking the line opens its distance / duration detail.
36903 vikas 1332
function bjRenderRoute(map, res, opt){
36929 vikas 1333
  var path=res.routes[0].overview_path;
1334
  var arrow={icon:{path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW, strokeColor:opt.color,
1335
                   strokeOpacity:1, strokeWeight:1, fillColor:opt.color, fillOpacity:1, scale:opt.dashed?2.6:3.2},
1336
             offset:'3%', repeat:opt.dashed?'95px':'120px'};
1337
  var icons=[arrow];
36903 vikas 1338
  if(opt.dashed){
36929 vikas 1339
    icons.unshift({icon:{path:'M 0,-1 0,1', strokeColor:opt.color, strokeOpacity:1, strokeWeight:4, scale:3}, offset:'0', repeat:'14px'});
36903 vikas 1340
  }
36929 vikas 1341
  var poly=new google.maps.Polyline({path:path, map:map, zIndex:opt.z,
1342
    strokeColor:opt.color, strokeOpacity:opt.dashed?0:0.85, strokeWeight:opt.dashed?0:5, icons:icons});
1343
  bjRouteClick(map, poly, opt.color, opt.label||(opt.dashed?'Suggested route':'Route taken'),
1344
    bjRouteKm(res), bjRouteDur(res), opt.time, opt.timed);
36903 vikas 1345
}
36929 vikas 1346
// Attach a click handler that opens an info window with the route's details at
1347
// the clicked point. Reused by both the routed line and the breadcrumb fallback.
1348
// `time` (optional) is the actual GPS time window, e.g. "09:28 → 16:03 (6h 35m)".
1349
// `timed` (optional) are the raw breadcrumbs with timestamps; when present, the
1350
// captured time at the nearest breadcrumb to the click is shown.
1351
function bjRouteClick(map, poly, color, label, km, dur, time, timed){
1352
  var iw=new google.maps.InfoWindow();
1353
  poly.addListener('click', function(e){
1354
    var here='';
1355
    if(timed && timed.length){
1356
      var np=bjNearestPt(timed, e.latLng);
1357
      if(np && np.ts) here='&#128205; At this point: <b>'+bjClockS(np.ts)+'</b><br>';
1358
    }
1359
    iw.setContent('<div style="font-size:12px;line-height:1.5"><b style="color:'+color+'">&#10148; '+esc(label)+'</b><br>'+
1360
      here+(time?'Time: <b>'+time+'</b><br>':'')+
1361
      'Distance: <b>'+km.toFixed(1)+' km</b>'+(dur?'<br>Est. drive: <b>'+esc(dur)+'</b>':'')+'</div>');
1362
    iw.setPosition(e.latLng); iw.open(map);
1363
  });
1364
}
1365
// Nearest timestamped breadcrumb to a clicked LatLng (great-circle distance).
1366
function bjNearestPt(timed, latLng){
1367
  var best=null, bd=Infinity;
1368
  for(var i=0;i<timed.length;i++){
1369
    var d=google.maps.geometry.spherical.computeDistanceBetween(latLng, new google.maps.LatLng(timed[i].lat, timed[i].lng));
1370
    if(d<bd){ bd=d; best=timed[i]; }
1371
  }
1372
  return best;
1373
}
1374
// Format an epoch-millis timestamp as a local HH:MM clock, and a millisecond
1375
// span as a compact "Nh Nm" / "Nm" elapsed string (for the GPS time window).
1376
function bjClock(ts){
1377
  var d=new Date(ts), h=d.getHours(), m=d.getMinutes();
1378
  return (h<10?'0':'')+h+':'+(m<10?'0':'')+m;
1379
}
1380
function bjClockS(ts){
1381
  var d=new Date(ts), h=d.getHours(), m=d.getMinutes(), s=d.getSeconds();
1382
  return (h<10?'0':'')+h+':'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s;
1383
}
1384
function bjElapsed(ms){
1385
  var s=Math.round(ms/1000), h=Math.floor(s/3600), m=Math.round((s%3600)/60);
1386
  return h ? (h+'h '+m+'m') : (m+'m');
1387
}
36903 vikas 1388
function bjRouteKm(res){
1389
  var m=0; (res.routes[0].legs||[]).forEach(function(l){ m+=(l.distance?l.distance.value:0); }); return m/1000;
1390
}
36929 vikas 1391
function bjRouteDur(res){
1392
  var s=0; (res.routes[0].legs||[]).forEach(function(l){ s+=(l.duration?l.duration.value:0); });
1393
  if(!s) return '';
1394
  var h=Math.floor(s/3600), m=Math.round((s%3600)/60);
1395
  return h ? (h+'h '+m+'m') : (m+'m');
1396
}
36903 vikas 1397
// Route-comparison panel rendered into the modal (#bjRouteLegend), above the map.
1398
// Each distance fills in as its route resolves. value: number = km, false =
1399
// unavailable, undefined = still loading.
1400
function bjRouteLegend(){
1401
  var div=el('bjRouteLegend');
1402
  if(!div) return { set:function(){}, note:function(){} };
1403
  var taken, sugg, noteTxt='';
1404
  function val(v){ return typeof v==='number' ? '<b>'+v.toFixed(1)+' km</b>' : (v===false ? 'n/a' : '…'); }
1405
  function render(){
1406
    var cmp='';
1407
    if(typeof taken==='number' && typeof sugg==='number'){
1408
      cmp = taken>sugg+0.05
1409
        ? '<span style="color:#e03131">+'+(taken-sugg).toFixed(1)+' km longer than suggested</span>'
1410
        : '<span style="color:#2f9e44">on / better than the suggested route</span>';
1411
    }
1412
    div.innerHTML=
1413
      '<span class="lg">Route comparison</span>'+
1414
      '<span><span class="sw ln"></span>Taken (GPS)</span>'+
1415
      '<span><span class="sw dt"></span>Suggested</span>'+
1416
      cmp+
1417
      (noteTxt?'<span style="color:#e8590c">'+noteTxt+'</span>':'');
1418
  }
1419
  render();
1420
  return { set:function(k,v){ if(k==='taken')taken=v; else sugg=v; render(); }, note:function(t){ noteTxt=t; render(); } };
1421
}
36882 vikas 1422
function tlSecs(t){ if(!t) return 1e9; var p=t.split(':'); return (+p[0])*3600+(+(p[1]||0))*60+(+(p[2]||0)); }
1423
function toSec(t){ if(!t||t==='00:00:00') return 0; var p=t.split(':'); return (+p[0])*3600+(+(p[1]||0))*60+(+(p[2]||0)); }
1424
function fmtSec(s){ s=Math.max(0,Math.round(s)); var h=Math.floor(s/3600), m=Math.floor((s%3600)/60), ss=s%60; function z(n){return (n<10?'0':'')+n;} return z(h)+':'+z(m)+':'+z(ss); }
1425
function jstat(v,l){ return '<div class="js"><div class="jv">'+v+'</div><div class="jl">'+l+'</div></div>'; }
1426
function hhmm(t){ return t? t.slice(0,5):''; }
1427
function tlThumb(att){
36903 vikas 1428
  if(att && window._mediaUrl) return '<img class="tlthumb" src="'+esc(window._mediaUrl+att)+'" onclick="bjOpenImage(this.src)" onerror="tlImgErr(this)">';
36882 vikas 1429
  return '<div class="tlph" title="No photo">&#128247;</div>';
1430
}
1431
function tlImgErr(im){ var d=document.createElement('div'); d.className='tlph'; d.title='Photo unavailable'; d.innerHTML='&#128247;'; if(im.parentNode) im.parentNode.replaceChild(d, im); }
1432
function punchEntry(kind, time){ return {_punch:kind, checkInTime:time, markType:(kind==='in'?'PUNCHIN':'PUNCHOUT'), taskType:'attendance'}; }
1433
function tlStyle(x){
1434
  var mt=(x.markType||'').toUpperCase(), tt=(x.taskType||'').toLowerCase();
1435
  if(x._punch || tt==='attendance' || mt.indexOf('PUNCH')>=0) return {c:'#7048e8', l:(x._punch==='out'?'Punch out':'Punch in'), ic:'&#9873;'};
1436
  if(mt.indexOf('CHECKOUT')>=0) return {c:'#2f9e44', l:'Visited', ic:'&#10003;'};
1437
  if(mt==='CHECKIN') return {c:'#1098ad', l:'In store', ic:'&#128205;'};
1438
  if(mt==='DEFERRED') return {c:'#e8590c', l:'Deferred', ic:'&#8635;'};
1439
  if(mt==='PENDING' || !x.checkInTime) return {c:'#97a1b5', l:'Pending', ic:'&#9675;'};
1440
  return {c:'#3b5bdb', l:(mt||'-'), ic:'&#9679;'};
1441
}
1442
function tlTitle(x){
1443
  if(x._punch) return x._punch==='in' ? 'Journey start (Punch in)' : 'Journey end (Punch out)';
1444
  var n=x.taskName||'';
36903 vikas 1445
  var taskType=(x.taskType||'').toLowerCase();
1446
  if(taskType==='franchisee-visit') {
1447
    var pipe = n.lastIndexOf('|');
1448
    if (pipe >= 0) n = n.slice(pipe + 1);      // drop leading agenda tags
1449
    n = n.replace(/\s*VISIT\b.*$/i, '').replace(/\s*visit\s*$/i, '').replace(/\bnull\b/gi, '').replace(/\s{2,}/g, ' ').trim();
1450
  }
36882 vikas 1451
  return n || '(stop)';
1452
}
1453
function tlRow(x, side){
1454
  var s=tlStyle(x);
1455
  var tt=(x.taskType||'').toLowerCase();
1456
  var timeTop = x.checkInTime ? hhmm(x.checkInTime) : '-';
1457
  var tlabel = x._punch ? (x._punch==='in'?'punch in':'punch out') : (x.checkInTime?'check-in':'pending');
1458
  var meta;
1459
  if(x._punch){
1460
    meta = (x._punch==='in'?'Punch in':'Punch out') + ' &middot; ' + hhmm(x.checkInTime);
1461
  } else {
1462
    var io = (x.checkInTime?hhmm(x.checkInTime):'-') + ' &rarr; ' + (x.checkOutTime?hhmm(x.checkOutTime):'-');
1463
    var dur = (x.timeSpent && x.timeSpent!=='00:00:00') ? ' &middot; '+esc(x.timeSpent) : '';
1464
    var typeLabel = tt==='lead' ? 'Lead' : (tt==='office-visit'?'Office':'Partner');
1465
    meta = x.checkInTime ? (typeLabel+' &middot; '+io+dur) : (typeLabel+' &middot; not visited');
1466
  }
1467
  // image (or placeholder) + battery + location-toggle on real stops
1468
  var extra='';
1469
  if(!x._punch){
1470
    var chips='';
1471
    if(x.battery!=null) chips += '<span class="tlchip">&#128267; '+x.battery+'%</span>';
1472
    if(x.locOff!=null) chips += '<span class="tlchip">&#128244; '+x.locOff+'</span>';
1473
    extra = '<div class="tlextra">'+tlThumb(x.attachment)+chips+'</div>';
1474
  }
36903 vikas 1475
  var card='<div class="tlcard">'+
36882 vikas 1476
        '<div class="tm" style="background:'+s.c+'">'+timeTop+'<small>'+tlabel+'</small></div>'+
1477
        '<div class="bd"><div class="ti">'+esc(tlTitle(x))+'</div>'+
1478
          '<span class="stt" style="background:'+s.c+'">'+s.l+'</span>'+
36941 vikas 1479
          (tt==='lead' ? '<span class="stt unplanned">Unplanned</span>' : '')+
36882 vikas 1480
          '<div class="mt">'+meta+'</div>'+extra+'</div>'+
36903 vikas 1481
      '</div>';
1482
  // remark sits on the opposite half of the timeline (empty spacer when none)
1483
  var rk=(!x._punch && x.remarks) ? '<div class="rk"><div class="rkl">Remark</div>'+esc(x.remarks)+'</div>' : '';
1484
  var remark='<div class="tlremark">'+rk+'</div>';
1485
  var halves = side==='left' ? (card+remark) : (remark+card);
1486
  return '<div class="tlrow '+side+'">'+
1487
      '<div class="node" style="background:'+s.c+'">'+s.ic+'</div>'+
1488
      halves+'</div>';
36882 vikas 1489
}
36877 vikas 1490
function closeModal(){ el('bj-modal-back').classList.remove('show'); }
36903 vikas 1491
// Image lightbox — opens an attachment larger, stacked above the journey modal.
1492
function bjOpenImage(src){ if(!src) return; el('bj-img').src=src; el('bj-img-back').classList.add('show'); }
1493
function bjCloseImage(){ el('bj-img-back').classList.remove('show'); el('bj-img').removeAttribute('src'); }
36877 vikas 1494
 
1495
/* ============================ APPROVAL ============================ */
1496
function loadApproval(){
1497
  spinner();
1498
  var from=el('bj-start').value, to=el('bj-end').value;
1499
  var u=CTX+'/beat-report/approval/data?fromDate='+encodeURIComponent(from)+'&toDate='+encodeURIComponent(to)+qs();
1500
  fetch(u,{headers:{'Accept':'application/json'}}).then(function(r){ return r.json(); }).then(function(d){
1501
    var rows=d.rows||[];
1502
    var h='<div class="card"><h2>Location Approval <span style="color:#97a1b5;font-weight:500;font-size:12px">&middot; '+rows.length+' off-site check-ins</span></h2>'+
1503
      '<p class="desc">Check-ins recorded &gt;50 m from the partner\'s saved location, across your downline. Approving updates the partner\'s coordinates.</p>';
1504
    if(!rows.length){ h+='<p class="desc">Nothing pending in this window.</p></div>'; el('bj-content').innerHTML=h; return; }
1505
    h+='<table><thead><tr><th>Executive</th><th>Store</th><th>Date</th><th>Check-in</th><th class="num">Distance</th><th class="num">Action</th></tr></thead><tbody>';
1506
    rows.forEach(function(r){
1507
      h+='<tr id="appr-'+r.trackingId+'"><td>'+esc(r.username)+'</td><td>'+esc(r.taskName)+'</td><td>'+esc(r.taskDate)+'</td><td>'+esc(r.checkInTime)+'</td>'+
1508
         '<td class="num '+(r.distanceM>200?'badflag':'warnflag')+'">'+r.distanceM+' m</td>'+
1509
         '<td class="num"><button class="btn-ok" onclick="approve('+r.trackingId+')">Approve</button></td></tr>';
1510
    });
1511
    h+='</tbody></table></div>';
1512
    el('bj-content').innerHTML=h;
1513
  }).catch(fail);
1514
}
1515
function approve(trackingId){
1516
  fetch(CTX+'/beat-report/approve-checkin',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'trackingId='+trackingId})
1517
    .then(function(r){ return r.json(); }).then(function(){ var row=el('appr-'+trackingId); if(row) row.parentNode.removeChild(row); }).catch(function(){ alert('Approve failed'); });
1518
}
1519
 
36903 vikas 1520
/* ============================ EXPORT ============================ */
1521
// Download the Employee Task Report (.xlsx). Today lens exports the single
1522
// selected day; Period lens exports the whole start..end range. Both carry the
1523
// current level / team scope (qs()). The download is served as an attachment, so
1524
// navigating to the URL triggers the file save without leaving the page.
1525
function exportReport(){
36913 vikas 1526
  var start, end, path;
1527
  if(LENS==='period'){
1528
    // Period lens: per-employee totals + a Raw Data sheet (separate endpoint).
1529
    start=el('bj-start').value; end=el('bj-end').value; path='/export-period';
1530
  } else {
1531
    // Today lens: the day-grouped Employee Task Report (unchanged).
1532
    start=el('bj-date').value; end=start; path='/export';
1533
  }
1534
  var u = BASE + path + '?startDate=' + encodeURIComponent(start) + '&endDate=' + encodeURIComponent(end) + qs();
36903 vikas 1535
  window.location.href = u;
1536
}
1537
 
36877 vikas 1538
/* ============================ INIT ============================ */
1539
document.querySelectorAll('.lens').forEach(function(b){ b.addEventListener('click', function(){ setLens(b.getAttribute('data-lens')); }); });
1540
el('bj-apply').addEventListener('click', load);
36903 vikas 1541
el('bj-export').addEventListener('click', exportReport);
36897 vikas 1542
el('bj-level').addEventListener('change', onLevelChange);
1543
if(el('bj-user')) el('bj-user').addEventListener('change', load);
1544
el('bj-date').addEventListener('change', updateTodayLabel);
36877 vikas 1545
el('bj-modal-back').addEventListener('click', function(e){ if(e.target===el('bj-modal-back')) closeModal(); });
36903 vikas 1546
el('bj-img-back').addEventListener('click', function(e){ if(e.target===el('bj-img-back')) bjCloseImage(); });
1547
el('bj-img-x').addEventListener('click', bjCloseImage);
1548
// Esc closes the lightbox first (if open), otherwise the journey modal.
1549
document.addEventListener('keydown', function(e){
1550
  if(e.key!=='Escape') return;
1551
  if(el('bj-img-back').classList.contains('show')) bjCloseImage();
1552
  else if(el('bj-modal-back').classList.contains('show')) closeModal();
1553
});
36897 vikas 1554
updateTodayLabel();
36877 vikas 1555
load();
1556
</script>
1557
</body>
1558
</html>