Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
37125 vikas 1
## LMS Dashboard — STANDALONE full page. Faithful copy of sts-mockup.html design (app bar + tabs + hand-drawn
2
## funnel/heat-map, NO charts), wired to REAL lead data. Rendered as a complete HTML doc (layout.vm = $screen_content).
3
## Served at GET /lms/dashboard. Seeds: regions[], summaryJson, stateFunnelJson, slaHeatmapJson, ageingJson, fromDate, toDate.
4
<!DOCTYPE html>
5
<html lang="en">
6
<head>
7
<meta charset="utf-8">
8
<meta name="viewport" content="width=device-width, initial-scale=1">
9
<title>LMS — Lead Dashboard</title>
10
<style>
11
  :root{
12
    --bg:#eef1f7; --card:#ffffff; --ink:#1d2433; --muted:#69748c; --soft:#97a1b5;
13
    --line:#e6e9f1; --line2:#eef1f6;
14
    --navy:#1f2a5e; --navy2:#2f3d78;
15
    --brand:#3b5bdb; --brand2:#5c7cfa; --teal:#0ca678; --cyan:#1098ad;
16
    --amber:#f59f00; --orange:#e8590c; --red:#e03131; --coral:#f0483e; --violet:#7048e8; --pink:#d6336c;
17
    --good:#2f9e44; --warn:#f08c00; --bad:#e03131;
18
  }
19
  *{box-sizing:border-box}
20
  html,body{margin:0;background:var(--bg);color:var(--ink);
21
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;font-size:14px}
22
  .wrap{max-width:1340px;margin:0 auto;padding:0 24px 90px}
23
  a{color:var(--brand);text-decoration:none}
24
  code,.mono{font-family:ui-monospace,Menlo,Consolas,monospace}
25
 
26
  /* ===== app bar ===== */
27
  .appbar{position:sticky;top:0;z-index:40;background:var(--navy);color:#fff;margin:0;padding:0 24px}
28
  .appbar .inner{max-width:1340px;margin:0 auto;display:flex;align-items:center;gap:18px;height:58px}
29
  .logo{display:flex;align-items:center;gap:10px;font-weight:800;letter-spacing:-.01em;font-size:16px}
30
  .logo .mk{width:30px;height:30px;border-radius:8px;background:linear-gradient(135deg,var(--coral),#ff7a5c);display:flex;align-items:center;justify-content:center;font-size:15px;font-weight:800}
31
  .logo small{display:block;font-size:10px;font-weight:600;color:#aab3d6;letter-spacing:.06em}
32
  .search{flex:1;max-width:560px;position:relative}
33
  .search input{width:100%;background:#2b3768;border:1px solid #3a488a;color:#fff;border-radius:9px;padding:9px 12px 9px 34px;font-size:13px;font-weight:500}
34
  .search input::placeholder{color:#9aa4cc}
35
  .search .si{position:absolute;left:11px;top:9px;color:#9aa4cc;font-size:14px}
36
  .search .hint{position:absolute;right:10px;top:8px;font-size:10px;color:#9aa4cc;border:1px solid #3a488a;border-radius:5px;padding:2px 6px}
37
  .abtn{background:#2b3768;border:1px solid #3a488a;color:#fff;border-radius:9px;padding:8px 11px;font-size:13px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:7px}
38
  .abtn.coral{background:var(--coral);border-color:var(--coral)}
39
  .role{display:flex;align-items:center;gap:9px}
40
  .role .av{width:31px;height:31px;border-radius:50%;background:#3a488a;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:12px}
41
  .role .who{font-size:12px;line-height:1.25}
42
  .role .who b{font-weight:700}
43
  .role .who span{color:#aab3d6}
44
 
45
  /* ===== tabs ===== */
46
  .tabbar{position:sticky;top:58px;z-index:39;background:var(--card);border-bottom:1px solid var(--line);margin:0 0 20px;padding:0 24px;box-shadow:0 1px 2px rgba(20,30,60,.03)}
47
  .tabbar .inner{max-width:1340px;margin:0 auto;display:flex;gap:2px;overflow-x:auto}
48
  .tab{padding:13px 4px;margin-right:24px;font-size:13.5px;font-weight:650;color:var(--muted);cursor:pointer;border:0;background:transparent;border-bottom:2.5px solid transparent;margin-bottom:-1px;white-space:nowrap}
49
  .tab:hover{color:var(--ink)}
50
  .tab.active{color:var(--navy);border-bottom-color:var(--coral)}
51
 
52
  /* ===== generic ===== */
53
  .crumb{font-size:12px;color:var(--soft);font-weight:600}
54
  h1.page{margin:2px 0 2px;font-size:23px;font-weight:760;letter-spacing:-.01em}
55
  .pagehead{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:18px}
56
  .pagehead .sub{color:var(--muted);font-size:13px;margin-top:2px}
57
  .hd-right{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
58
  .ctl{background:var(--card);border:1px solid var(--line);border-radius:9px;padding:8px 12px;font-size:13px;color:var(--ink);font-weight:600}
59
  .ctl .lbl{color:var(--soft);font-weight:500;margin-right:5px}
60
  select.ctl{appearance:none;cursor:pointer;padding-right:26px;background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6'><path d='M1 1l4 4 4-4' stroke='%2369748c' fill='none' stroke-width='1.5'/></svg>");background-repeat:no-repeat;background-position:right 10px center}
61
  .btn{background:var(--navy);border:0;color:#fff;font-weight:650;padding:9px 15px;border-radius:9px;cursor:pointer;font-size:13px}
62
  .btn.coral{background:var(--coral)}
63
  .btn.ghost{background:#fff;color:var(--ink);border:1px solid var(--line)}
64
  .btn.sm{padding:6px 11px;font-size:12px}
65
 
66
  .sectionlabel{font-size:11.5px;letter-spacing:.12em;text-transform:uppercase;color:var(--soft);font-weight:700;margin:24px 2px 12px}
67
  .grid{display:grid;gap:16px}
68
  .g2{grid-template-columns:1fr 1fr}
69
  .g3{grid-template-columns:1.6fr 1fr}
70
  .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)}
71
  .card h2{margin:0 0 3px;font-size:15px;font-weight:720;letter-spacing:-.01em}
72
  .card .desc{color:var(--muted);font-size:12.5px;margin:0 0 14px}
73
 
74
  /* kpis */
75
  .kpis{display:grid;grid-template-columns:repeat(6,1fr);gap:12px;margin-bottom:8px}
76
  .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)}
77
  .kpi .top{display:flex;align-items:center;gap:8px}
78
  .kpi .ic{width:28px;height:28px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:14px;flex:none}
79
  .kpi .label{font-size:11.5px;color:var(--muted);font-weight:600;line-height:1.2}
80
  .kpi .val{font-size:26px;font-weight:760;margin-top:9px;letter-spacing:-.02em;line-height:1}
81
  .kpi .val small{font-size:13px;color:var(--soft);font-weight:600}
82
  .kpi .foot{font-size:11.5px;color:var(--soft);margin-top:7px}
83
 
84
  /* funnel */
85
  .funnel{display:flex;gap:8px;align-items:stretch;flex-wrap:wrap}
86
  .fstep{flex:1;min-width:118px;border:1px solid var(--line);border-radius:11px;padding:12px 11px;position:relative;text-align:center;background:#fbfcfe}
87
  .fstep .fn{font-size:10.5px;text-transform:uppercase;letter-spacing:.03em;color:var(--muted);font-weight:700}
88
  .fstep .fv{font-size:24px;font-weight:770;margin-top:6px}
89
  .fstep .fbar{height:5px;border-radius:3px;margin-top:9px;background:linear-gradient(90deg,var(--navy),var(--brand))}
90
  .fstep .drop{font-size:10.5px;color:var(--red);margin-top:6px;font-weight:600}
91
  .fstep .keep{font-size:10.5px;color:var(--good);margin-top:6px;font-weight:600}
92
  .fstep .arrow{position:absolute;right:-11px;top:50%;transform:translateY(-50%);z-index:2;color:#c5cce0;font-size:14px}
93
 
94
  /* table */
95
  table{width:100%;border-collapse:collapse;font-size:13px}
96
  th,td{text-align:left;padding:9px 9px;border-bottom:1px solid var(--line2)}
97
  th{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:700;white-space:nowrap}
98
  th.num,td.num{text-align:right}
99
  tbody tr:hover{background:#f7f9fd}
100
  .clickrow{cursor:pointer}
101
  .rowwarn{background:#fff9f0}
102
  .rowbad{background:#fff5f5}
103
  .warnflag{color:var(--orange);font-weight:700}
104
  .badflag{color:var(--red);font-weight:700}
105
 
106
  /* pills / stages */
107
  .idpill{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;font-weight:700;color:var(--navy);background:#eef1fb;border:1px solid #dfe4f7;border-radius:6px;padding:2px 7px;white-space:nowrap}
108
  .stage{display:inline-flex;align-items:center;gap:6px;font-weight:700;font-size:11px;padding:3px 9px;border-radius:999px;text-transform:uppercase;letter-spacing:.02em}
109
  .st-new{background:#eef1fb;color:#3b5bdb}
110
  .st-assigned{background:#e7f5ff;color:#1971c2}
111
  .st-contacted{background:#e3fafc;color:#0c8599}
112
  .st-qualified{background:#e6fcf5;color:#0ca678}
113
  .st-beat{background:#f3f0ff;color:#7048e8}
114
  .st-visited{background:#fff0f6;color:#c2255c}
115
  .st-onboarded{background:#ebfbee;color:#2f9e44}
116
  .st-active{background:#d3f9d8;color:#2b8a3e}
117
  .st-ni{background:#fff4e6;color:#e8590c}
118
  .st-dead{background:#f1f3f5;color:#868e96}
119
  .tag{display:inline-block;font-size:10.5px;font-weight:700;padding:2px 7px;border-radius:5px}
120
  .tag.a{background:#fff0ef;color:var(--coral)}
121
  .tag.b{background:#e6fcf5;color:var(--teal)}
122
 
123
  /* SLA pills */
124
  .sla{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:700}
125
  .sla .clk{font-family:ui-monospace,Menlo,Consolas,monospace}
126
  .sla.ok{color:var(--good)} .sla.warn{color:var(--orange)} .sla.bad{color:var(--red)}
127
  .slabar{display:inline-block;width:52px;height:6px;border-radius:4px;background:#eef1f6;overflow:hidden;vertical-align:middle}
128
  .slabar>i{display:block;height:100%}
129
 
130
  /* attention */
131
  .att{display:flex;align-items:center;gap:12px;padding:11px 12px;border:1px solid var(--line);border-radius:11px;margin-bottom:9px}
37692 vikas 132
  /* Across the top rather than down a narrow column, so the nine-column table gets the full width. */
133
  .attstrip{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px}
134
  .attstrip .att{margin-bottom:0}
135
  .attstrip .atitle{font-size:12.5px;line-height:1.25}
136
  .attstrip .adet{font-size:11.5px;margin-top:1px}
137
  /* Wide content scrolls inside its own card, never the page body. */
138
  .pipewrap{overflow-x:auto}
139
  /* table-layout:fixed + a colgroup so the columns keep sane proportions on a wide screen instead
140
     of the browser handing City and Created-by a third of the table each. Business/Retailer takes
141
     the slack because it is the column people actually read. */
142
  .pipewrap table{min-width:1040px;table-layout:fixed}
143
  .pipewrap td{vertical-align:middle;overflow:hidden;text-overflow:ellipsis}
144
  .pipewrap td.wrapok{white-space:normal}
145
  .pipewrap td.nowrap{white-space:nowrap}
37125 vikas 146
  .att .ic{width:30px;height:30px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px;flex:none}
147
  .att .ab{flex:1}
148
  .att .atitle{font-size:13px;font-weight:650}
149
  .att .adet{font-size:12px;color:var(--muted);margin-top:2px}
150
  .att .acount{font-size:18px;font-weight:780}
151
 
152
  /* tiles */
153
  .tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:11px}
154
  .tile{background:#f8f9fc;border:1px solid var(--line2);border-radius:11px;padding:12px}
155
  .tile .t{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:600}
156
  .tile .v{font-size:21px;font-weight:760;margin-top:5px}
157
  .tile .v small{font-size:12px;color:var(--soft);font-weight:600}
158
 
159
  .hide{display:none !important}
37692 vikas 160
  th.sortable{cursor:pointer;user-select:none;white-space:nowrap}
161
  th.sortable:hover{color:var(--brand2)}
162
  th.sortable.on{color:var(--brand2)}
163
  /* Triangle drawn with borders — no glyph, so it cannot fall back to a tofu box the way U+2195 did. */
164
  th.sortable .arrow{display:inline-block;width:0;height:0;margin-left:5px;vertical-align:middle;
165
    border-left:4px solid transparent;border-right:4px solid transparent}
166
  th.sortable .arrow.up{border-bottom:5px solid currentColor}
167
  th.sortable .arrow.down{border-top:5px solid currentColor}
168
  /* Field label outside the filter bar (.ctl .lbl is scoped to it) + the record-action modals. */
169
  .lbl{display:block;font-size:12px;font-weight:600;color:var(--soft);margin:10px 0 4px}
170
  .modal{position:fixed;inset:0;z-index:90;background:rgba(14,18,40,.44);display:flex;align-items:flex-start;
171
         justify-content:center;padding:6vh 16px;overflow:auto}
172
  .modal .box{background:#fff;border-radius:14px;width:min(640px,100%);box-shadow:0 26px 70px rgba(10,15,40,.3)}
173
  .modal .mh{padding:18px 22px 0}
174
  .modal .mh h2{margin:0;font-size:17px;color:var(--brand)}
175
  .modal .mb{padding:4px 22px 18px}
176
  .modal .mf{padding:14px 22px;border-top:1px solid var(--line);display:flex;justify-content:flex-end;gap:8px}
177
  .dispgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin-top:6px}
37125 vikas 178
 
179
  /* interactivity */
180
  .kpi,.fstep,.att,#dash tbody tr,.heat td{cursor:pointer}
181
  .kpi,.fstep{transition:transform .12s,box-shadow .12s}
182
  .kpi:hover,.fstep:hover{box-shadow:0 4px 14px rgba(20,30,60,.10);transform:translateY(-1px)}
183
  .att:hover{border-color:#c7d0e8}
184
 
185
  .drawer-ov{position:fixed;inset:0;background:rgba(20,26,50,.42);z-index:70;opacity:0;pointer-events:none;transition:opacity .2s}
186
  .drawer-ov.open{opacity:1;pointer-events:auto}
37692 vikas 187
  .drawer{position:fixed;top:0;right:0;height:100%;width:min(680px,96vw);background:#f7f8fc;z-index:71;box-shadow:-14px 0 46px rgba(10,15,40,.22);transform:translateX(100%);transition:transform .26s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column}
37125 vikas 188
  .drawer.open{transform:none}
189
  .drawer .dh{padding:17px 20px;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:flex-start;gap:12px;flex:none}
190
  .drawer .crumb2{font-size:10.5px;font-weight:800;text-transform:uppercase;letter-spacing:.06em;color:var(--coral)}
191
  .drawer h3{margin:2px 0 1px;font-size:18px;font-weight:770;letter-spacing:-.01em}
192
  .drawer .dsub{color:var(--muted);font-size:12.5px}
193
  .drawer .x{margin-left:auto;cursor:pointer;font-size:22px;line-height:1;color:var(--soft);background:none;border:0;padding:0 2px}
194
  .drawer .dbody{padding:16px 18px 40px;overflow:auto;flex:1}
195
  .drawer .card{margin-bottom:12px}
196
  .dstat{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;margin-bottom:12px}
197
  .dstat .box{background:#fff;border:1px solid var(--line);border-radius:11px;padding:11px 12px}
198
  .dstat .t{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:700}
199
  .dstat .v{font-size:20px;font-weight:770;margin-top:3px}
200
  .dnote{font-size:12px;color:var(--muted);line-height:1.55;margin-top:8px}
201
 
202
  .toastwrap{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:90;display:flex;flex-direction:column;gap:8px;align-items:center}
203
  .toast{background:#1f2a5e;color:#fff;padding:11px 16px;border-radius:11px;font-size:13px;font-weight:600;box-shadow:0 10px 34px rgba(10,15,40,.32);display:flex;align-items:center;gap:10px;animation:tin .18s ease-out}
204
  .toast .ok{color:#69db7c;font-weight:800}
205
  @keyframes tin{from{opacity:0;transform:translateY(10px)}}
206
 
207
  /* heatmap */
208
  .heat td{width:34px;height:30px;text-align:center;font-size:11px;font-weight:700;color:#fff;border:2px solid #fff;border-radius:6px}
209
 
210
  /* callout */
211
  .callout{background:linear-gradient(180deg,#fbfcff,#f4f7ff);border:1px solid #dfe6fb;border-radius:14px;padding:18px 20px;margin-top:6px}
212
  .callout h2{margin:0 0 3px;font-size:16px}
213
  .fix{display:flex;gap:13px;padding:13px 0;border-bottom:1px solid #e6ebf8}
214
  .fix:last-child{border-bottom:0}
215
  .fix .sev{width:6px;border-radius:4px;flex:none}
216
  .fix .fb{flex:1}
217
  .fix .ft{font-size:14px;font-weight:700}
218
  .fix .fd{font-size:13px;color:#3a4459;margin-top:4px;line-height:1.5}
219
  .fix .fd b{color:var(--ink)}
220
  .fix .act{font-size:12.5px;color:var(--good);margin-top:6px;font-weight:650}
221
 
222
  .note{font-size:11.5px;color:var(--soft);margin-top:10px;line-height:1.6}
223
  .ph{font-size:12.5px;color:var(--soft);font-style:italic;padding:16px 0;text-align:center}
224
  .rbadge{font-size:9.5px;font-weight:700;padding:1px 6px;border-radius:10px;margin-left:6px;vertical-align:middle}
225
  .rbadge.live{background:#e6f7ee;color:var(--good)}.rbadge.partial{background:#fff3dc;color:var(--warn)}.rbadge.soon{background:#eef0f5;color:var(--soft)}
226
 
227
  /* record / kv / trail */
228
  .kv{display:grid;grid-template-columns:130px 1fr;gap:7px 12px;font-size:13px}
229
  .kv .k{color:var(--soft);font-weight:600}
230
  .kv .v{font-weight:600}
231
  .divider{height:1px;background:var(--line);margin:14px 0}
232
  .recordHost{min-height:120px}
233
  .lookup{display:flex;gap:8px;align-items:center;margin-bottom:14px}
234
  .lookup input{border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13px;width:280px}
235
 
236
  /* form */
237
  .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px 16px}
238
  .fld{display:flex;flex-direction:column;gap:5px}
239
  .fld.full{grid-column:1/3}
240
  .fld label{font-size:11.5px;font-weight:700;color:var(--muted)}
241
  .fld label .m{color:var(--red)}
242
  .fld label .auto{float:right;font-size:10px;font-weight:700;color:var(--brand);background:#eef1fb;border-radius:5px;padding:1px 6px;text-transform:uppercase;letter-spacing:.03em}
243
  .inp{border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13px;font-weight:500;background:#fff;color:var(--ink);width:100%}
244
  .inp:focus{outline:none;border-color:var(--brand2);box-shadow:0 0 0 3px #eaefff}
245
  .inp[readonly],.inp.ro{background:#f5f6fa;color:var(--muted);font-weight:600}
246
  select.inp{appearance:none;cursor:pointer;background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6'><path d='M1 1l4 4 4-4' stroke='%2369748c' fill='none' stroke-width='1.5'/></svg>");background-repeat:no-repeat;background-position:right 11px center}
247
  .hinttext{font-size:11px;color:var(--soft)}
37651 vikas 248
  /* Brand-wise value capture. auto-fill keeps it compact on a laptop and collapses to one column
249
     on a phone, which is where Path B (field encounter) is actually used. */
250
  .brandgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(148px,1fr));gap:8px;margin-top:2px}
251
  .brandcell{display:flex;align-items:center;gap:6px;background:#f7f8fc;border:1px solid var(--line);
252
    border-radius:8px;padding:4px 8px}
253
  .brandcell .bname{font-size:11.5px;font-weight:700;color:var(--ink);white-space:nowrap;min-width:58px}
254
  .brandcell .bval{border:0;background:transparent;padding:3px 0;height:auto;font-size:12.5px;text-align:right}
255
  .brandcell .bval:focus{outline:0;box-shadow:none}
256
  .brandcell:focus-within{border-color:var(--brand);background:#fff}
37125 vikas 257
  .resolvebox{background:#f5f7ff;border:1px solid #dfe4f7;border-radius:11px;padding:13px 15px;display:flex;align-items:center;gap:13px}
258
  .resolvebox .ra{width:38px;height:38px;border-radius:10px;background:var(--navy);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;flex:none}
259
  .resolvebox .rt{font-size:11px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.04em}
260
  .resolvebox .rn{font-size:15px;font-weight:750;margin-top:1px}
261
  .resolvebox .rc{font-size:11.5px;color:var(--muted);margin-top:2px}
262
  .trail{position:relative;padding-left:22px}
37692 vikas 263
  /* When the trail scrolls, bleed it out to the card's edge (.card padding is 17px 19px) and put
264
     that 19px back as padding — the scrollbar then sits flush against the card border instead of
265
     floating in a gutter, and the entries stay where they were. */
266
  .trail.scrolls{margin-right:-19px;padding-right:19px}
37125 vikas 267
  .trail:before{content:"";position:absolute;left:7px;top:4px;bottom:4px;width:2px;background:var(--line)}
268
  .tevt{position:relative;padding:0 0 14px}
269
  .tevt:last-child{padding-bottom:0}
270
  .tevt .tdot{position:absolute;left:-22px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;border:2px solid var(--brand);display:flex;align-items:center;justify-content:center;font-size:8px;color:var(--brand)}
271
  .tevt.sys .tdot{border-color:var(--soft);color:var(--soft)}
272
  .tevt.win .tdot{border-color:var(--good);color:var(--good)}
273
  .tevt.call .tdot{border-color:var(--coral);color:var(--coral)}
274
  .tevt .tt{font-size:13px;font-weight:650}
275
  .tevt .tm{font-size:11.5px;color:var(--soft);margin-top:1px}
276
  .tevt .td{font-size:12.5px;color:var(--muted);margin-top:4px;background:#f8f9fc;border:1px solid var(--line2);border-radius:8px;padding:8px 10px}
37692 vikas 277
  .tevt .trec{display:flex;align-items:center;gap:8px;margin-top:6px}
278
  .tevt .trec audio{height:30px;max-width:230px}
37125 vikas 279
 
280
  /* record stepper */
281
  .rec-stepper{display:flex;align-items:center;gap:0;margin:2px 0 4px;flex-wrap:wrap}
282
  .rec-step{display:flex;align-items:center;gap:8px;flex:1;min-width:96px;position:relative}
283
  .rec-step .dot{width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;flex:none;border:2px solid var(--line);background:#fff;color:var(--soft)}
284
  .rec-step.done .dot{background:var(--good);border-color:var(--good);color:#fff}
285
  .rec-step.cur .dot{background:var(--navy);border-color:var(--navy);color:#fff;box-shadow:0 0 0 4px #e7ebfa}
286
  .rec-step .sl{font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.02em;color:var(--muted)}
287
  .rec-step.cur .sl{color:var(--navy)}
288
  .rec-step .bar{position:absolute;left:26px;right:0;top:13px;height:2px;background:var(--line);z-index:-1}
289
  .rec-step.done .bar{background:var(--good)}
290
 
291
  /* matrix */
292
  .matrix{width:100%;border-collapse:separate;border-spacing:0;font-size:12.5px}
293
  .matrix th,.matrix td{padding:9px 8px;border-bottom:1px solid var(--line2);text-align:center}
294
  .matrix th:first-child,.matrix td:first-child{text-align:left;font-weight:650}
295
  .matrix thead th{background:#f8f9fc;color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.03em}
296
  .mk-y{color:var(--good);font-weight:800}
297
  .mk-n{color:#ccd2e0}
298
  .mk-s{color:var(--orange);font-weight:800;font-size:11px}
299
 
300
  @media (max-width:1040px){
301
    .kpis{grid-template-columns:repeat(3,1fr)}
302
    .g2,.g3{grid-template-columns:1fr}
303
    .form-grid{grid-template-columns:1fr}.fld.full{grid-column:1}
304
    .search{display:none}
305
  }
306
</style>
307
</head>
308
<body>
309
 
310
<!-- ============ APP BAR ============ -->
311
<div class="appbar">
312
  <div class="inner">
313
    <div class="logo"><span class="mk">SD</span><div>SmartDukaan · LMS<small>LEAD MANAGEMENT SYSTEM</small></div></div>
314
    <div class="search">
315
      <span class="si">&#128269;</span>
316
      <input id="lmsSearch" placeholder="Search LMS ID, business, phone, retailer…  e.g. LMS-UPW-26-000123">
317
      <span class="hint">/ to focus</span>
318
    </div>
319
    <button class="abtn coral" onclick="window.open(CTX+'/getOpenLead','_blank')">+ New Lead</button>
320
    <div class="role">
321
      <div class="av">SD</div>
322
      <div class="who"><b>Lead Dashboard</b><br><span>live · real data</span></div>
323
    </div>
324
  </div>
325
</div>
326
 
327
<!-- ============ TABS ============ -->
328
<div class="tabbar">
329
  <div class="inner">
330
    <button class="tab active" onclick="go('cmd',this)">Command Center</button>
331
    <button class="tab" onclick="go('record',this)">Lead Record</button>
332
    <button class="tab" onclick="go('create',this)">Create Lead</button>
333
    <button class="tab" onclick="go('assign',this)">Auto-Assignment</button>
334
    <button class="tab" onclick="go('dash',this)">Dashboards</button>
335
    <button class="tab" onclick="go('audit',this)">Recordings &amp; Audit</button>
336
  </div>
337
</div>
338
 
339
<div class="wrap">
340
 
341
  <!-- ======================= COMMAND CENTER ========================= -->
342
  <div id="cmd">
343
    <div class="pagehead">
344
      <div>
345
        <div class="crumb">Sales · Lead Pipeline</div>
346
        <h1 class="page">Command Center</h1>
347
        <div class="sub">Every lead you own or oversee — from creation to onboarding. SLA clock runs on all NEW records.</div>
348
      </div>
349
      <div class="hd-right">
350
        <select class="ctl" id="fRegion">
351
          <option value="">All regions</option>
352
          #foreach($r in $regions)
353
            <option value="$r.getId()">$!r.getName()#if($r.getRegionCode()) ($r.getRegionCode())#end</option>
354
          #end
355
        </select>
356
        <input type="date" class="ctl" id="fFrom" value="$!fromDate">
357
        <input type="date" class="ctl" id="fTo" value="$!toDate">
358
      </div>
359
    </div>
360
 
361
    <div class="kpis" id="ccKpis"></div>
362
 
363
    <div class="sectionlabel">Lifecycle Funnel — selected period</div>
364
    <div class="card"><div class="funnel" id="ccFunnel"></div></div>
365
 
37692 vikas 366
    <div class="card">
367
      <h2>Needs attention now</h2>
368
      <p class="desc">Actionable queues · click to work them.</p>
369
      <div id="ccAttention" class="attstrip"></div>
370
    </div>
371
 
372
    <div class="card">
373
        <h2 style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">Lead pipeline
374
          <span style="display:flex;gap:6px;align-items:center">
375
            <input id="pipeQ" class="inp" style="width:230px;font-size:12.5px;padding:7px 10px"
376
                   placeholder="Name, outlet, mobile, city, created by">
377
            <button class="btn ghost sm" onclick="pipeSearch()">Search</button>
378
            <button class="btn ghost sm hide" id="pipeClear" onclick="pipeClearSearch()">Clear</button>
379
          </span>
380
        </h2>
381
        <p class="desc" id="pipeDesc">Click any row &rarr; full LMS record &amp; trail. Rows shaded by SLA urgency.</p>
382
        <div class="pipewrap">
37125 vikas 383
        <table>
37692 vikas 384
          <colgroup>
385
            <col style="width:132px"><col><col style="width:64px"><col style="width:112px">
386
            <col style="width:130px"><col style="width:130px"><col style="width:130px">
387
            <col style="width:104px"><col style="width:84px">
388
          </colgroup>
389
          <thead><tr>
390
            <th class="sortable" data-sort="created">LMS ID</th>
391
            <th class="sortable" data-sort="name">Business / Retailer</th>
392
            <th>Path</th>
393
            <th class="sortable" data-sort="stage">Stage</th>
394
            <th>Owner</th>
395
            <th class="sortable" data-sort="city">City</th>
396
            <th class="sortable" data-sort="createdBy">Created by</th>
397
            <th class="sortable" data-sort="sla">SLA</th>
398
            <th class="sortable num" data-sort="value">Value</th>
399
          </tr></thead>
400
          <tbody id="ccPipeline"><tr><td colspan="9"><div class="ph">Loading…</div></td></tr></tbody>
37125 vikas 401
        </table>
37692 vikas 402
        </div>
403
        <div id="pipeFoot" style="display:flex;align-items:center;justify-content:space-between;gap:10px;
404
             margin-top:10px;flex-wrap:wrap">
405
          <span class="note" id="pipeCount"></span>
406
          <span style="display:flex;gap:6px;align-items:center">
407
            <button class="btn ghost sm" id="pipePrev" onclick="pipePage(-1)">&larr; Prev</button>
408
            <span class="note" id="pipePageLbl"></span>
409
            <button class="btn ghost sm" id="pipeNext" onclick="pipePage(1)">Next &rarr;</button>
410
          </span>
411
        </div>
37125 vikas 412
    </div>
413
  </div>
414
 
415
  <!-- ======================= LEAD RECORD ========================= -->
416
  <div id="record" class="hide">
417
    <div class="pagehead">
418
      <div>
419
        <div class="crumb">Command Center · Lead Record</div>
420
        <h1 class="page">Lead Record</h1>
421
        <div class="sub">The single source of truth for a lead — stepper, immutable trail, SLA &amp; disposition. Loads the real record.</div>
422
      </div>
423
      <div class="hd-right">
424
        <div class="lookup">
425
          <input id="recLookup" placeholder="Lead # (e.g. 123)" inputmode="numeric">
426
          <button class="btn sm" onclick="loadRecord()">Load</button>
427
        </div>
428
      </div>
429
    </div>
430
    <div class="recordHost" id="recordHost"><div class="card"><div class="ph">Loading the most recent lead…</div></div></div>
37692 vikas 431
    <div class="note" style="margin-left:2px">Acts on the real record: edit, call, disposition and stage moves all write here, and every change lands in the trail.</div>
37125 vikas 432
  </div>
433
 
434
  <!-- ======================= CREATE LEAD ========================= -->
435
  <div id="create" class="hide">
436
    <div class="pagehead">
437
      <div>
438
        <div class="crumb">Create · New Lead</div>
439
        <h1 class="page">Create Lead</h1>
37651 vikas 440
        <div class="sub">Only what an agent can know on a first call. LMS ID is generated on submit and the lead is auto-assigned from region. Address, store photo and geo-pin come from the capture link, which is created automatically and copied to your clipboard.</div>
37125 vikas 441
      </div>
442
      <div class="hd-right">
443
        <div class="ctl" style="padding:4px;display:flex;gap:4px">
444
          <button class="btn coral sm" id="pathA" style="border-radius:7px" onclick="setPath('A',this)">Path A · BGC outbound</button>
445
          <button class="btn ghost sm" id="pathB" style="border-radius:7px" onclick="setPath('B',this)">Path B · Field encounter</button>
446
        </div>
447
      </div>
448
    </div>
449
 
450
    <div class="grid g3">
451
      <div class="card">
452
        <h2>Lead details</h2>
453
        <p class="desc" id="createDesc">Path A — captured by BGC agent during an outbound call, after consent.</p>
454
        <div class="form-grid">
455
          <div class="fld"><label>Retailer name <span class="m">*</span></label><input class="inp" id="cRetailer" placeholder="Contact person"></div>
456
          <div class="fld"><label>Business name <span class="m">*</span></label><input class="inp" id="cBusiness" placeholder="Shop / trade name"></div>
457
          <div class="fld"><label>Contact number <span class="m">*</span></label><input class="inp mono" id="cContact" placeholder="10-digit mobile" inputmode="numeric"></div>
37651 vikas 458
          <div class="fld full">
459
            <label>Monthly business value — brand wise <span class="auto" id="cValueTotal">total ₹0</span></label>
460
            <div class="brandgrid" id="cBrandGrid">
461
              #foreach($b in $leadBrands)
462
                <div class="brandcell">
463
                  <span class="bname">$b</span>
464
                  <input class="inp bval mono" data-brand="$b" placeholder="0" inputmode="numeric"
465
                         oninput="brandTotal()">
466
                </div>
467
              #end
468
            </div>
469
            <div class="hinttext">Type in rupees per month — 100000 or 1L, 50k both work. Leave a brand blank if it is not stocked.</div>
470
          </div>
37125 vikas 471
          <div class="fld"><label>Interest status</label><select class="inp" id="cInterest"><option>Interested</option><option>Callback</option><option>Not Interested</option></select></div>
472
          <div class="fld full">
473
            <label>Region / State <span class="m">*</span> <span class="auto">drives auto-assignment</span></label>
474
            <select class="inp" id="cRegion" onchange="resolveBM(this.value)">
475
              <option value="">Select a region…</option>
476
              #foreach($r in $regions)
477
                <option value="$r.getId()">$!r.getName()#if($r.getRegionCode()) ($r.getRegionCode())#end</option>
478
              #end
479
            </select>
480
          </div>
481
        </div>
482
        <div style="display:flex;gap:9px;margin-top:16px;justify-content:flex-end">
483
          <button class="btn coral" onclick="submitLead()">Submit &amp; generate LMS ID</button>
484
        </div>
485
      </div>
486
 
487
      <div>
488
        <div class="card">
489
          <h2>Auto-assignment preview</h2>
490
          <p class="desc">On Region select, the engine resolves the BM/RSM and shows it for confirmation before submit.</p>
491
          <div class="resolvebox" id="resolveBox">
492
            <div class="ra" id="raAv">—</div>
493
            <div>
494
              <div class="rt">Resolved BM / RSM · <span id="rRegion">—</span></div>
495
              <div class="rn" id="rName">Pick a region…</div>
496
              <div class="rc" id="rEsc">The owning BM/RSM is resolved from the region (cs.position).</div>
497
            </div>
498
          </div>
499
          <div class="note">If a region has no active BM/RSM, the LMS enters a <b>HOLD queue</b> and the Sales Head is notified.</div>
500
        </div>
501
        <div class="card">
502
          <h2>What happens on submit</h2>
503
          <div class="trail" style="margin-top:4px">
504
            <div class="tevt win"><div class="tdot">1</div><div class="tt">Validate fields &amp; generate LMS ID</div><div class="tm">immutable, searchable</div></div>
505
            <div class="tevt sys"><div class="tdot">2</div><div class="tt">Set stage = Assigned</div><div class="tm">BM/RSM resolved from region</div></div>
506
            <div class="tevt sys"><div class="tdot">3</div><div class="tt">Dispatch assignment email</div><div class="tm">BM/RSM + CC Reporting Mgr</div></div>
507
            <div class="tevt call"><div class="tdot">4</div><div class="tt">Start 5 hr SLA timer</div><div class="tm">first-contact clock begins</div></div>
508
          </div>
509
        </div>
510
      </div>
511
    </div>
512
  </div>
513
 
514
  <!-- ======================= AUTO-ASSIGNMENT ========================= -->
515
  <div id="assign" class="hide">
516
    <div class="pagehead">
517
      <div>
518
        <div class="crumb">Sales Ops · Routing</div>
519
        <h1 class="page">Auto-Assignment Engine</h1>
520
        <div class="sub">Region &rarr; BM/RSM mapping resolves ownership at submit — from the live cs.position table. HOLD when a region has no active BM.</div>
521
      </div>
522
    </div>
523
 
524
    <div class="kpis" style="grid-template-columns:repeat(4,1fr)" id="assignKpis"></div>
525
 
526
    <div class="grid g3">
527
      <div class="card">
528
        <h2>Region &rarr; BM/RSM mapping</h2>
529
        <p class="desc">The live routing table — resolved for each region right now.</p>
530
        <table>
531
          <thead><tr><th>Region / State</th><th>Assigned BM / RSM</th><th>Status</th></tr></thead>
532
          <tbody id="assignMap"><tr><td colspan="3"><div class="ph">Resolving…</div></td></tr></tbody>
533
        </table>
534
      </div>
535
      <div>
536
        <div class="card">
537
          <h2>Engine rules</h2>
538
          <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#eef1fb;color:#3b5bdb">1</div><div class="ab"><div class="atitle">Resolve at submit</div><div class="adet">Region drives ownership; BM/RSM shown for confirmation.</div></div></div>
539
          <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#fff4e6;color:#e8590c">2</div><div class="ab"><div class="atitle">Tier fallback</div><div class="adet">L4 → L5 → L3 within the region (cs.position).</div></div></div>
540
          <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#fff0f0;color:#e03131">3</div><div class="ab"><div class="atitle">HOLD queue</div><div class="adet">No active BM/RSM &rarr; LMS held; Sales Head notified.</div></div></div>
541
          <div class="att" style="margin-bottom:0"><div class="ic" style="background:#f3f0ff;color:#7048e8">4</div><div class="ab"><div class="atitle">Manual reassignment</div><div class="adet">BM/RSM/Sales Head can override — always logged.</div></div></div>
542
        </div>
543
        <div class="card" style="background:#fff5f5;border-color:#ffd9d5">
544
          <h2 style="color:#c92a2a">HOLD queue</h2>
545
          <p class="desc" style="margin-bottom:8px">LMS with no active BM — waiting until one is mapped.</p>
546
          <div id="holdQueue"><div class="ph">Loading…</div></div>
547
        </div>
548
      </div>
549
    </div>
550
  </div>
551
 
552
  <!-- ======================= DASHBOARDS ========================= -->
553
  <div id="dash" class="hide">
554
    <div class="pagehead">
555
      <div>
556
        <div class="crumb">Management · Cross-region roll-up</div>
557
        <h1 class="page">Dashboards</h1>
558
        <div class="sub">Funnel, SLA compliance, ageing &amp; servicing across all regions — derived from the lead record.</div>
559
      </div>
560
      <div class="hd-right">
561
        <span class="ctl"><span class="lbl">Period</span><span id="dashPeriod">—</span></span>
562
        <button class="btn ghost sm" onclick="toast('Export uses the app report suite',1)">Export</button>
563
      </div>
564
    </div>
565
 
566
    <div class="kpis" id="dashKpis"></div>
567
 
568
    <div class="sectionlabel">State funnel — NEW &rarr; ONBOARDED by region</div>
569
    <div class="card">
570
      <table>
571
        <thead><tr><th>Region</th><th class="num">New</th><th class="num">Contacted</th><th class="num">Qualified</th><th class="num">Visited</th><th class="num">Onboarded</th><th class="num">Conv%</th><th class="num">SLA%</th></tr></thead>
572
        <tbody id="dashState"></tbody>
573
      </table>
574
    </div>
575
 
576
    <div class="grid g2">
577
      <div class="card">
578
        <h2>SLA compliance — owner heat-map</h2>
579
        <p class="desc">% first contact within SLA, by BM (rows) across recent weeks (cols). Red = chronic breach.</p>
580
        <div id="dashHeat"></div>
581
        <div class="note">SLA = first contact within 5 hrs of creation (SOP §11). Reminder T-1h; escalation to BM at T+5h.</div>
582
      </div>
583
      <div class="card">
584
        <h2>Standard dashboards</h2>
585
        <p class="desc">SOP §18.2 report suite — Live = from the lead record; Partial/Pending need their source system.</p>
586
        <table><tbody style="font-size:12.5px">
587
          <tr class="clickrow" data-rep="State Funnel"><td>&#128200; <b>State Funnel</b><span class="rbadge live">Live</span></td><td style="color:#69748c">New &rarr; onboarded by region, BM, ASM</td></tr>
588
          <tr class="clickrow" data-rep="SLA Compliance"><td>&#9878; <b>SLA Compliance</b><span class="rbadge live">Live</span></td><td style="color:#69748c">% within SLA, owner heat-map</td></tr>
589
          <tr class="clickrow" data-rep="Ageing"><td>&#8987; <b>Ageing</b><span class="rbadge live">Live</span></td><td style="color:#69748c">Stuck by stage, days-since-action</td></tr>
590
          <tr class="clickrow" data-rep="Management Roll-up"><td>&#128081; <b>Management Roll-up</b><span class="rbadge live">Live</span></td><td style="color:#69748c">Cross-region leads, onboardings, value</td></tr>
591
          <tr class="clickrow" data-rep="BGC Daily"><td>&#128202; <b>BGC Daily</b><span class="rbadge partial">Partial</span></td><td style="color:#69748c">Created + dispositions real; calls are a proxy (no telephony)</td></tr>
592
          <tr class="clickrow" data-rep="Audit Hygiene"><td>&#129529; <b>Audit Hygiene</b><span class="rbadge partial">Partial</span></td><td style="color:#69748c">Missing dispositions / HOLD; DND &amp; recordings pending</td></tr>
593
          <tr class="clickrow" data-rep="RBM Servicing"><td>&#128260; <b>RBM Servicing</b><span class="rbadge soon">Pending data</span></td><td style="color:#69748c">Repeat-order / complaint / TAT need order data</td></tr>
594
        </tbody></table>
595
      </div>
596
    </div>
597
 
598
    <div class="sectionlabel">What to fix</div>
599
    <div class="callout">
600
      <h2>Recommended actions — from this period's data</h2>
601
      <p class="desc">Each links to the section above.</p>
602
      <div id="dashFix"></div>
603
    </div>
604
  </div>
605
 
606
  <!-- ======================= RECORDINGS & AUDIT ========================= -->
607
  <div id="audit" class="hide">
608
    <div class="pagehead">
609
      <div>
610
        <div class="crumb">Audit · Access Control</div>
611
        <h1 class="page">Recordings &amp; Audit</h1>
612
        <div class="sub">Recordings are gated by role + reporting hierarchy; every open is logged. Hygiene flags are live; the recording repo is a pending source system.</div>
613
      </div>
614
    </div>
615
 
616
    <div class="kpis" style="grid-template-columns:repeat(5,1fr)" id="auditKpis"></div>
617
 
618
    <div class="grid g2">
619
      <div class="card">
620
        <h2>Access &amp; recording visibility matrix</h2>
621
        <p class="desc">What each role can open. Recording access is scoped by role + reporting hierarchy (SOP §15).</p>
622
        <table class="matrix">
623
          <thead><tr><th>Role</th><th>Own LMS</th><th>Reports'</th><th>State-wide</th><th>All records</th><th>Recordings</th></tr></thead>
624
          <tbody>
625
            <tr><td>Individual (BGC/ASM)</td><td class="mk-y">&#10003;</td><td class="mk-n">&mdash;</td><td class="mk-n">&mdash;</td><td class="mk-n">&mdash;</td><td class="mk-s">own only</td></tr>
626
            <tr><td>Reporting Manager</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-n">&mdash;</td><td class="mk-n">&mdash;</td><td class="mk-s">reports'</td></tr>
627
            <tr><td>BM / RSM</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-n">&mdash;</td><td class="mk-s">state-wide</td></tr>
628
            <tr><td>Audit Team</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-s">all · read-only</td></tr>
629
            <tr><td>Upper Management</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-s">via BI drill</td></tr>
630
          </tbody>
631
        </table>
632
        <div class="note">Recording repository (signed URLs, DND enforcement, 24-mo retention) is a Phase-2 source system — not yet wired to real data.</div>
633
      </div>
634
 
635
      <div class="card">
636
        <h2>Weekly hygiene flags <span style="color:#97a1b5;font-weight:500;font-size:12px">· live</span></h2>
637
        <p class="desc">Derived from the lead record — click to list the leads.</p>
638
        <div id="auditHygiene"><div class="ph">Loading…</div></div>
639
      </div>
640
    </div>
641
 
642
    <div class="grid g2">
643
      <div class="card">
644
        <h2>Audit &amp; compliance program (SOP §17)</h2>
645
        <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#e6fcf5;color:#0ca678">&#127925;</div><div class="ab"><div class="atitle">Weekly recording sampling</div><div class="adet">Across BGC, ASM &amp; RBM for quality &amp; process adherence.</div></div></div>
646
        <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#e6fcf5;color:#0ca678">&#129529;</div><div class="ab"><div class="atitle">5% deep audit of onboarded</div><div class="adet">Verify data integrity &amp; process compliance.</div></div></div>
647
        <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#fff0f0;color:#e03131">&#128683;</div><div class="ab"><div class="atitle">DND enforcement</div><div class="adet">Audit maintains the list; repeat calls auto-flag the user.</div></div></div>
648
        <div class="att" style="margin-bottom:0"><div class="ic" style="background:#eef1f6;color:#69748c">&#128451;</div><div class="ab"><div class="atitle">Retention policy</div><div class="adet">24 months for recordings · 5 years for LMS records.</div></div></div>
649
      </div>
650
      <div class="card">
651
        <h2>Recording repository <span style="color:#97a1b5;font-weight:500;font-size:12px">· pending source</span></h2>
652
        <p class="desc">Each recording would be tagged with LMS ID, user, timestamp, duration &amp; disposition.</p>
653
        <div class="ph">No recording repository connected yet — this arrives with the C2C telephony bridge (Phase 2/3).</div>
654
      </div>
655
    </div>
656
  </div>
657
 
658
</div>
659
 
660
<!-- drawer + toast -->
661
<div class="drawer-ov" id="ov" onclick="closeDrawer()"></div>
662
<div class="drawer" id="drawer">
663
  <div class="dh"><div><div class="crumb2" id="dCrumb"></div><h3 id="dTitle"></h3><div class="dsub" id="dSub"></div></div><button class="x" onclick="closeDrawer()">&times;</button></div>
664
  <div class="dbody" id="dBody"></div>
665
</div>
37692 vikas 666
<!-- Record actions: edit the record, and log a call outcome. Both write to the same endpoints
667
     the in-app lead record uses. -->
668
<div class="modal hide" id="editModal">
669
  <div class="box">
670
    <div class="mh"><h2>Edit record</h2>
671
      <p class="desc">Every change is written to the trail against your name.</p></div>
672
    <div class="mb" id="editBody"></div>
673
    <div class="mf"><button class="btn ghost" onclick="closeEdit()">Cancel</button>
674
      <button class="btn" style="background:#1f2a5e;color:#fff" onclick="saveEdit()">Save changes</button></div>
675
  </div>
676
</div>
677
 
678
<div class="modal hide" id="dispModal">
679
  <div class="box">
680
    <div class="mh"><h2>Call disposition</h2>
681
      <p class="desc">Structured outcome on every interaction (SOP &sect;12.2).</p></div>
682
    <div class="mb">
683
      <label class="lbl">Outcome (required)</label>
684
      <div class="dispgrid" id="dispGrid"></div>
685
      <div id="dispExtra"></div>
686
      <label class="lbl">Note (attaches to the trail)</label>
687
      <textarea id="dispNote" class="inp" rows="2" style="width:100%;resize:vertical"></textarea>
688
    </div>
689
    <div class="mf"><button class="btn ghost" onclick="closeDisp()">Cancel</button>
690
      <button class="btn coral" onclick="saveDisp()">Save disposition</button></div>
691
  </div>
692
</div>
693
 
694
<!-- Manual geo verification (SOP §6: geo-pin). Same endpoints the Leads screen uses:
695
     /lead-geo/geocode-address, /lead-geo/upload-image, /lead-geo/manual-verify. -->
696
<div class="modal hide" id="geoModal">
697
  <div class="box">
698
    <div class="mh"><h2>Verify location manually</h2>
699
      <p class="desc">For when the retailer will not tap the capture link — confirm the coordinates
700
        over the phone, or read them off a Maps link they shared. Saved as approved, against your name.</p></div>
701
    <div class="mb">
702
      <label class="lbl">Address</label>
703
      <div style="display:flex;gap:6px">
704
        <input id="geoAddress" class="inp" style="flex:1" placeholder="Shop address with city, state, pincode">
705
        <button class="btn ghost sm" id="geoFindBtn" onclick="geoGeocode()">Find on map</button>
706
      </div>
707
      <label class="lbl">Latitude, longitude</label>
708
      <div style="display:flex;gap:6px">
709
        <input id="geoLatLng" class="inp" style="flex:1" placeholder="28.6139,77.2090 — or paste a Google Maps link">
710
        <button class="btn ghost sm" onclick="geoPreview()">Show on map</button>
711
      </div>
712
      <div id="geoMapWrap" class="hide" style="margin-top:10px">
713
        <iframe id="geoMapFrame" style="width:100%;height:220px;border:1px solid var(--line);border-radius:10px" loading="lazy"></iframe>
714
        <a id="geoOpenMap" class="note" target="_blank" rel="noopener" href="#">Open in Google Maps &rarr;</a>
715
      </div>
716
      <label class="lbl">Store-board photo (required)</label>
717
      <input id="geoPhoto" type="file" accept="image/jpeg,image/png" class="inp" onchange="geoPickPhoto()">
718
      <div class="note">The only evidence that someone actually saw the store-board.</div>
719
      <img id="geoPhotoImg" class="hide" style="margin-top:8px;max-height:130px;border-radius:8px;border:1px solid var(--line)">
720
      <label class="lbl">Remark</label>
721
      <input id="geoRemark" class="inp" placeholder="Optional — how the location was confirmed">
722
      <div id="geoErr" class="hide" style="margin-top:10px;color:#e03131;font-size:12.5px"></div>
723
    </div>
724
    <div class="mf"><button class="btn ghost" onclick="closeGeo()">Cancel</button>
725
      <button class="btn" style="background:#1f2a5e;color:#fff" id="geoSaveBtn" onclick="geoSave()">Save &amp; verify</button></div>
726
  </div>
727
</div>
728
 
37125 vikas 729
<div class="toastwrap" id="toasts"></div>
730
 
731
<script>
732
  var CTX = "${rc.contextPath}";
733
  var SEED = { summary:$summaryJson, state:$stateFunnelJson, heat:$slaHeatmapJson, ageing:$ageingJson };
734
  var STATE = { regionId:'', from:'$!fromDate', to:'$!toDate' };
735
  var DATA = { summary:null, state:null, heat:null, ageing:null };
736
 
737
  function byId(x){ return document.getElementById(x); }
738
  function esc(s){ if(s==null) return ''; return (''+s).replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
739
  function fmtInt(n){ if(n==null) return '0'; return (''+n).replace(/\B(?=(\d{3})+(?!\d))/g,','); }
740
  function fmtInr(v){ if(v==null||v===''||isNaN(v)||Number(v)<=0) return '&#8377;0'; v=Number(v);
741
    if(v>=1e7) return '&#8377;'+(v/1e7).toFixed(1)+'<small> Cr</small>'; if(v>=1e5) return '&#8377;'+(v/1e5).toFixed(1)+'<small> L</small>';
742
    if(v>=1e3) return '&#8377;'+Math.round(v/1e3)+'<small>K</small>'; return '&#8377;'+Math.round(v); }
37692 vikas 743
  /**
744
   * Business value in lakhs.
745
   *
746
   * Two conventions live in user.lead.potential: the form captures LAKHS (rows hold 1–99), but
747
   * ~1,355 older rows were entered in RUPEES (1,000 – 2,00,00,000). Nothing between 100 and 999
748
   * exists, so the gap is a safe separator: 1000 and above is read as rupees and brought onto the
749
   * lakh scale. Normalised on read only — no stored value is rewritten.
750
   */
751
  var LAKH_CUTOFF=1000;
752
  function toLakh(v){ v=Number(v); return v>=LAKH_CUTOFF ? v/100000 : v; }
753
  function inrShort(v){ if(v==null||isNaN(v)||Number(v)<=0) return '&#8377;0';
754
    var l=toLakh(v);
755
    // Under a lakh needs two decimals: a ₹1,000 lead is 0.01L, and one decimal would print it as
756
    // ₹0L — the same information loss the old scaling caused, just at the other end.
757
    var n=l<1?Math.round(l*100)/100:Math.round(l*10)/10;
758
    return '&#8377;'+(n%1===0?n:n.toFixed(l<1?2:1))+'L'; }
37125 vikas 759
 
760
  // ---- tabs
761
  var SCREENS=['cmd','record','create','assign','dash','audit'];
762
  var LOADED={};
763
  function go(id,btn){ SCREENS.forEach(function(s){ byId(s).classList.toggle('hide',s!==id); });
764
    document.querySelectorAll('.tab').forEach(function(t){ t.classList.remove('active'); }); if(btn) btn.classList.add('active');
765
    if(id==='dash') byId('dashPeriod').textContent=(STATE.from||'')+' → '+(STATE.to||'');
766
    if(id==='record' && !LOADED.record){ LOADED.record=true; loadRecentRecord(); }
767
    if(id==='assign' && !LOADED.assign){ LOADED.assign=true; buildAssign(); }
768
    if(id==='audit'){ buildAudit(); } }
769
 
770
  // ---- toast
771
  function toast(msg,ok){ var w=byId('toasts'); var t=document.createElement('div'); t.className='toast';
772
    t.innerHTML=(ok?'<span class="ok">&#10003;</span>':'')+esc(msg); w.appendChild(t);
773
    setTimeout(function(){ t.style.opacity='0'; t.style.transition='opacity .3s'; setTimeout(function(){ t.remove(); },300); },2600); }
774
 
775
  // ---- filters + fetch
776
  function qs(){ var q=''; if(STATE.regionId)q+='&regionId='+encodeURIComponent(STATE.regionId);
777
    if(STATE.from)q+='&from='+encodeURIComponent(STATE.from); if(STATE.to)q+='&to='+encodeURIComponent(STATE.to); return q; }
37651 vikas 778
  function getJSON(path,cb,onErr){ fetch(CTX+path,{credentials:'same-origin',headers:{'X-Requested-With':'XMLHttpRequest'}})
779
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
780
    .then(function(j){ cb((j&&j.response!==undefined)?j.response:j); })
781
    .catch(function(e){ console.error('LMS fetch failed',path,e);
782
      if(typeof onErr==='function'){ onErr(e); } else { toast('Could not load data'); } }); }
37125 vikas 783
 
784
  // ---- stage helpers
785
  var STCLASS={NEW:'st-new',ASSIGNED:'st-assigned',CONTACTED:'st-contacted',QUALIFIED:'st-qualified',
786
    BEAT_PLANNED:'st-beat',VISITED:'st-visited',ONBOARDED:'st-onboarded',ACTIVE:'st-active',NOT_INTERESTED:'st-ni',DROPPED:'st-dead'};
787
  function stagePill(st,lb){ if(!st) return '<span class="stage st-new">—</span>'; return '<span class="stage '+(STCLASS[st]||'st-new')+'">'+esc(lb||st)+'</span>'; }
788
  function slaCell(state){ switch(state){
789
    case'MET': return '<span class="sla ok"><span class="slabar"><i style="width:100%;background:#2f9e44"></i></span><span class="clk">met</span></span>';
790
    case'RUNNING': return '<span class="sla ok"><span class="slabar"><i style="width:50%;background:#1f2a5e"></i></span><span class="clk">running</span></span>';
791
    case'AT_RISK': return '<span class="sla warn"><span class="slabar"><i style="width:85%;background:#f08c00"></i></span><span class="clk">&lt; 1 hr</span></span>';
792
    case'BREACHED': return '<span class="sla bad"><span class="slabar"><i style="width:100%;background:#e03131"></i></span><span class="clk">breached</span></span>';
793
    default: return '<span style="color:#97a1b5;font-size:12px">&mdash;</span>'; } }
794
 
795
  // ---- COMMAND CENTER
796
  var CC_KPI={ 'new':{i:'&#128229;',bg:'#eef1fb',fg:'#3b5bdb'}, awaiting:{i:'&#9203;',bg:'#fff4e6',fg:'#f08c00',v:'#f08c00'},
797
    sla:{i:'&#9888;',bg:'#fff0f0',fg:'#e03131',v:'#e03131'}, contacted:{i:'&#128222;',bg:'#e3fafc',fg:'#0c8599'},
798
    qualified:{i:'&#10003;',bg:'#e6fcf5',fg:'#0ca678'}, onboarded:{i:'&#127942;',bg:'#ebfbee',fg:'#2f9e44'} };
799
  var ATT_META={ BREACHED_NO_CONTACT:{i:'&#9888;',bg:'#fff0f0',fg:'#e03131',c:'badflag'}, HOLD:{i:'&#128100;',bg:'#fff0f0',fg:'#e03131',c:'badflag'},
800
    SLA_UNDER_1H:{i:'&#9203;',bg:'#fff4e6',fg:'#e8590c',c:'warnflag'}, MISSING_DISP:{i:'&#128172;',bg:'#fff4e6',fg:'#e8590c',c:'warnflag'},
801
    QUALIFIED_NO_BEAT:{i:'&#128337;',bg:'#eef1f6',fg:'#69748c',c:''}, ONBOARDED_PENDING:{i:'&#128260;',bg:'#f3f0ff',fg:'#7048e8',c:''} };
802
 
803
  function renderSummary(d){ DATA.summary=d;
804
    var kh=''; (d.kpis||[]).forEach(function(k){ var m=CC_KPI[k.key]||{i:'&#128202;',bg:'#eef1f6',fg:'#69748c'};
805
      kh+='<div class="kpi" data-kpi="'+esc(k.key)+'"><div class="top"><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.i+'</div>'+
806
        '<div class="label">'+esc(k.label)+'</div></div><div class="val"'+(m.v?' style="color:'+m.v+'"':'')+'>'+fmtInt(k.value)+'</div>'+
807
        '<div class="foot">'+esc(k.foot)+'</div></div>'; });
808
    byId('ccKpis').innerHTML=kh;
809
    renderFunnel(d.funnel||[]);
810
    var ah=''; (d.attention||[]).forEach(function(a){ var m=ATT_META[a.key]||{i:'&#128202;',bg:'#eef1f6',fg:'#69748c',c:''};
811
      ah+='<div class="att" data-att="'+esc(a.key)+'" data-attt="'+esc(a.title)+'"><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.i+'</div>'+
812
        '<div class="ab"><div class="atitle">'+esc(a.title)+'</div><div class="adet">'+esc(a.detail)+'</div></div>'+
813
        '<div class="acount '+m.c+'">'+fmtInt(a.count)+'</div></div>'; });
814
    byId('ccAttention').innerHTML=ah;
815
    buildDashKpis(); buildFix();
816
  }
817
 
818
  function renderFunnel(funnel){
819
    var byStage={}; funnel.forEach(function(s){ byStage[s.stage]=s; });
820
    var seq=[['ALL','New'],['ASSIGNED','Assigned'],['CONTACTED','Contacted'],['QUALIFIED','Qualified'],['VISITED','Visited'],['ONBOARDED','Onboarded']];
821
    var h=''; var prev=null;
822
    seq.forEach(function(p,idx){ var s=byStage[p[0]]; if(!s) return; var last=(idx===seq.length-1);
823
      var cap; if(idx===0){ cap='<div class="keep">created</div>'; }
824
      else if(last){ cap='<div class="keep">'+s.pct+'% conversion</div>'; }
825
      else { var drop=prev?prev.count-s.count:0; cap=drop>0?('<div class="drop">&minus;'+fmtInt(drop)+'</div>'):('<div class="keep">'+s.pct+'%</div>'); }
826
      h+='<div class="fstep" data-stage="'+p[0]+'" data-label="'+esc(p[1])+'"><div class="fn">'+esc(p[1])+'</div><div class="fv">'+fmtInt(s.count)+'</div>'+
827
        '<div class="fbar" style="width:'+Math.max(s.pct,3)+'%"></div>'+cap+(last?'':'<span class="arrow">&#10148;</span>')+'</div>';
828
      prev=s; });
829
    byId('ccFunnel').innerHTML=h||'<div class="ph">No leads in scope.</div>';
830
  }
831
 
37692 vikas 832
  // ---- Lead pipeline: filtered, sorted and paged on the server ------------------------------
833
  // PIPE.q is the search term. While it is set the date filter does not apply — a search hunts for
834
  // one known retailer, and quietly scoping it to the selected month would report "not found" for a
835
  // lead that exists. The caption says which mode is in force so that is never a surprise.
836
  var PIPE = { q:'', sort:'created', dir:'desc', page:1, pageSize:50, pages:1, total:0 };
37125 vikas 837
 
37692 vikas 838
  function loadPipeline(){
839
    byId('ccPipeline').innerHTML='<tr><td colspan="9"><div class="ph">Loading…</div></td></tr>';
840
    var p='/lms/dashboard/pipeline?page='+PIPE.page+'&pageSize='+PIPE.pageSize+
841
          '&sort='+encodeURIComponent(PIPE.sort)+'&dir='+encodeURIComponent(PIPE.dir);
842
    if(PIPE.q){ p+='&q='+encodeURIComponent(PIPE.q);
843
                if(STATE.regionId) p+='&regionId='+encodeURIComponent(STATE.regionId); }
844
    else { p+=qs(); }
845
    getJSON(p,function(d){
846
      d=d||{}; var rows=d.rows||[];
847
      PIPE.total=d.total||0; PIPE.pages=d.pages||1; PIPE.page=d.page||1;
848
      renderPipeHead();
849
      if(!rows.length){
850
        byId('ccPipeline').innerHTML='<tr><td colspan="9"><div class="ph">'+
851
          (PIPE.q?('No lead matches “'+esc(PIPE.q)+'”.'):'No leads in scope.')+'</div></td></tr>';
852
      } else {
853
        var h='';
854
        rows.forEach(function(l){
855
          var rc=l.slaState==='BREACHED'?'rowbad':(l.slaState==='AT_RISK'?'rowwarn':'');
856
          h+='<tr class="clickrow '+rc+'" data-leadid="'+l.id+'">'+
857
            '<td class="nowrap"><span class="idpill">'+esc(l.lmsCode)+'</span></td>'+
858
            '<td class="wrapok"><b>'+esc(l.name||'—')+'</b>'+(l.outlet?'<br><span style="color:#97a1b5;font-size:11px">'+esc(l.outlet)+'</span>':'')+'</td>'+
859
            '<td class="nowrap">'+(l.path==='B'?'<span class="tag b">B · Field</span>':'<span class="tag a">A · BGC</span>')+'</td>'+
860
            '<td class="nowrap">'+stagePill(l.stage,l.stageLabel)+'</td>'+
861
            // title= so a name clipped by the fixed width is still readable on hover.
862
            '<td class="nowrap" title="'+esc(l.owner||'')+'">'+esc(l.owner||'—')+'</td>'+
863
            '<td class="nowrap" title="'+esc(l.city||'')+'">'+esc(l.city||'—')+'</td>'+
864
            '<td class="nowrap" title="'+esc(l.createdBy||'')+'">'+esc(l.createdBy||'—')+'</td>'+
865
            '<td class="nowrap">'+slaCell(l.slaState)+'</td>'+
866
            '<td class="num nowrap">'+inrShort(l.value)+'</td></tr>';
867
        });
868
        byId('ccPipeline').innerHTML=h;
869
      }
870
      // Say how many there actually are, not how many were drawn.
871
      var shown=rows.length, first=(PIPE.page-1)*PIPE.pageSize+(shown?1:0), last=(PIPE.page-1)*PIPE.pageSize+shown;
872
      byId('pipeCount').textContent=PIPE.total
873
        ? ('Showing '+first+'–'+last+' of '+fmtInt(PIPE.total)+(PIPE.q?' matching leads (all dates)':' leads in the selected period'))
874
        : '';
875
      byId('pipePageLbl').textContent='Page '+PIPE.page+' / '+Math.max(PIPE.pages,1);
876
      byId('pipePrev').disabled=(PIPE.page<=1);
877
      byId('pipeNext').disabled=(PIPE.page>=PIPE.pages);
878
      byId('pipeDesc').innerHTML=PIPE.q
879
        ? 'Searching every lead for “<b>'+esc(PIPE.q)+'</b>” — the date filter is ignored while a search is active.'
880
        : 'Click any row &rarr; full LMS record &amp; trail. Rows shaded by SLA urgency.';
881
      byId('pipeClear').classList.toggle('hide', !PIPE.q);
882
    });
883
  }
884
 
885
  /**
886
   * Mark the active column and its direction.
887
   *
888
   * The label is captured once into data-label and re-read from there. Deriving it from
889
   * textContent instead re-read the arrow this function had just appended, so every sort click
890
   * stacked another one onto the header.
891
   */
892
  function renderPipeHead(){
893
    document.querySelectorAll('th.sortable').forEach(function(th){
894
      if(!th.hasAttribute('data-label')) th.setAttribute('data-label', th.textContent.trim());
895
      var on=(th.getAttribute('data-sort')===PIPE.sort);
896
      th.classList.toggle('on',on);
897
      th.innerHTML=esc(th.getAttribute('data-label'))+
898
        (on?'<span class="arrow '+(PIPE.dir==='asc'?'up':'down')+'"></span>':'');
899
    });
900
  }
901
 
902
  function pipeSort(col){
903
    // Same column toggles direction; a new column starts descending, which is what people expect
904
    // from value and dates and is harmless for the text columns.
905
    if(PIPE.sort===col){ PIPE.dir=(PIPE.dir==='asc'?'desc':'asc'); }
906
    else { PIPE.sort=col; PIPE.dir='desc'; }
907
    PIPE.page=1; loadPipeline();
908
  }
909
  function pipeSearch(){
910
    var v=(byId('pipeQ').value||'').trim();
911
    if(v && v.length<2){ toast('Type at least 2 characters'); return; }
912
    PIPE.q=v; PIPE.page=1; loadPipeline();
913
  }
914
  function pipeClearSearch(){ byId('pipeQ').value=''; PIPE.q=''; PIPE.page=1; loadPipeline(); }
915
  function pipePage(step){
916
    var n=PIPE.page+step;
917
    if(n<1||n>PIPE.pages) return;
918
    PIPE.page=n; loadPipeline();
919
  }
920
 
37125 vikas 921
  function kpiBucket(k){ switch(k){case'new':return['STAGE','NEW'];case'awaiting':return['STAGE','ASSIGNED'];
922
    case'sla':return['ATTENTION','BREACHED_NO_CONTACT'];case'contacted':return['STAGE','CONTACTED'];
923
    case'qualified':return['STAGE','QUALIFIED'];case'onboarded':return['STAGE','ONBOARDED'];default:return['ALL','']; } }
924
 
925
  // ---- DASHBOARDS
926
  var DASH_KPI=[ {i:'&#128229;',bg:'#eef1fb',fg:'#3b5bdb'}, {i:'&#128200;',bg:'#e6fcf5',fg:'#0ca678',v:'#0ca678'},
927
    {i:'&#9878;',bg:'#fff4e6',fg:'#f08c00',v:'#f08c00'}, {i:'&#128222;',bg:'#e3fafc',fg:'#0c8599'},
928
    {i:'&#8987;',bg:'#fff0f0',fg:'#e03131',v:'#e03131'}, {i:'&#128176;',bg:'#ebfbee',fg:'#2f9e44'} ];
929
  function pctColor(p){ return p>=25?'#2f9e44':(p>=18?'#f08c00':(p>=10?'#e8590c':'#e03131')); }
930
  function slaColor(p){ return p>=85?'#2f9e44':(p>=70?'#f08c00':'#e03131'); }
931
 
932
  function renderState(d){ DATA.state=d; var rows=(d&&d.rows)?d.rows:[];
933
    var h=''; rows.forEach(function(r){ var cls=r.convPct<15?'rowbad':(r.slaPct<60?'rowwarn':'');
934
      h+='<tr class="clickrow '+cls+'" data-region="'+esc(r.regionCode)+'" data-rn="'+esc(r.regionName)+'">'+
935
        '<td><b>'+esc(r.regionName)+'</b> <span class="idpill">'+esc(r.regionCode)+'</span></td>'+
936
        '<td class="num">'+fmtInt(r.newCount)+'</td><td class="num">'+fmtInt(r.contacted)+'</td><td class="num">'+fmtInt(r.qualified)+'</td>'+
937
        '<td class="num">'+fmtInt(r.visited)+'</td><td class="num">'+fmtInt(r.onboarded)+'</td>'+
938
        '<td class="num"><b style="color:'+pctColor(r.convPct)+'">'+r.convPct+'%</b></td>'+
939
        '<td class="num"><b style="color:'+slaColor(r.slaPct)+'">'+r.slaPct+'%</b></td></tr>'; });
940
    byId('dashState').innerHTML=h||'<tr><td colspan="8"><div class="ph">No regional data.</div></td></tr>';
941
    buildDashKpis(); buildFix();
942
  }
943
 
944
  function renderHeat(d){ DATA.heat=d; var weeks=(d&&d.weeks)?d.weeks:[],bms=(d&&d.bms)?d.bms:[];
945
    if(!bms.length){ byId('dashHeat').innerHTML='<div class="ph">No SLA data for the selected period.</div>'; return; }
946
    function hc(p){ if(p>=90)return'#40c057';if(p>=80)return'#82c91e';if(p>=70)return'#fab005';if(p>=60)return'#fd7e14';if(p>=50)return'#fa5252';return'#e03131'; }
947
    var h='<table class="heat"><thead><tr><td style="background:none;border:0"></td>';
948
    weeks.forEach(function(w){ h+='<td style="background:none;border:0;color:#97a1b5;font-size:10px;font-weight:700">'+esc(w)+'</td>'; });
949
    h+='</tr></thead><tbody>';
950
    bms.forEach(function(bm){ h+='<tr><td style="background:none;color:#69748c;font-size:11px;text-align:left;width:auto;border:0">'+esc(bm.bmName)+'</td>';
951
      (bm.cells||[]).forEach(function(c){ if(c.pct==null){ h+='<td style="background:#eef1f6;color:#97a1b5">–</td>'; }
952
        else { var col=hc(c.pct),tc=(c.pct>=70&&c.pct<80)?'#333':'#fff'; h+='<td style="background:'+col+';color:'+tc+'">'+c.pct+'</td>'; } }); h+='</tr>'; });
953
    h+='</tbody></table>'; byId('dashHeat').innerHTML=h;
954
  }
955
 
956
  function renderAgeing(d){ DATA.ageing=d; buildDashKpis(); buildFix(); }
957
 
958
  function buildDashKpis(){ var s=DATA.summary; if(!s) return;
959
    var contacted=0; (s.funnel||[]).forEach(function(f){ if(f.stage==='CONTACTED')contacted=f.count; });
960
    var tot=0,acc=0; ((DATA.state&&DATA.state.rows)||[]).forEach(function(r){ tot+=r.newCount; acc+=r.slaPct*r.newCount; });
961
    var sla=tot>0?Math.round(acc/tot):0;
962
    var vals=[ {v:fmtInt(s.total),f:'in period'}, {v:s.conversionPct+'<small>%</small>',f:'new &rarr; onboarded'},
963
      {v:sla+'<small>%</small>',f:'first contact ≤ 5h'}, {v:fmtInt(Math.round(contacted/90)),f:'proxy · no telephony'},
964
      {v:DATA.ageing?fmtInt(DATA.ageing.total):'—',f:'stuck by stage'}, {v:fmtInr(s.onboardedValue),f:'est. potential'} ];
965
    var labels=['LMS created','Conversion','SLA compliance','Calls / day (BGC)','Ageing &gt; 7 days','Onboarded value'];
966
    var h=''; vals.forEach(function(x,i){ var m=DASH_KPI[i];
967
      h+='<div class="kpi"><div class="top"><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.i+'</div>'+
968
        '<div class="label">'+labels[i]+'</div></div><div class="val"'+(m.v?' style="color:'+m.v+'"':'')+'>'+x.v+'</div><div class="foot">'+x.f+'</div></div>'; });
969
    byId('dashKpis').innerHTML=h;
970
  }
971
 
972
  function buildFix(){ var rows=((DATA.state&&DATA.state.rows)||[]).slice();
973
    var out='';
974
    if(rows.length){ var worst=rows.slice().sort(function(a,b){return a.convPct-b.convPct;})[0];
975
      out+='<div class="fix"><div class="sev" style="background:#e03131"></div><div class="fb"><div class="ft">'+esc(worst.regionName)+' is leaking at the top</div>'+
976
        '<div class="fd"><b>'+fmtInt(worst.newCount)+' created, only '+worst.convPct+'% onboarded and '+worst.slaPct+'% SLA</b> — the weakest region this period.</div>'+
977
        '<div class="act">&rarr; Review its stuck leads; check BM mapping / HOLD queue.</div></div></div>';
978
      var lowSla=rows.slice().sort(function(a,b){return a.slaPct-b.slaPct;})[0];
979
      if(lowSla && lowSla.regionCode!==worst.regionCode){ out+='<div class="fix"><div class="sev" style="background:#f59f00"></div><div class="fb"><div class="ft">'+esc(lowSla.regionName)+' SLA slipping</div>'+
980
        '<div class="fd"><b>'+lowSla.slaPct+'% on-time first contact</b> — first-contact discipline is breaking down.</div>'+
981
        '<div class="act">&rarr; Enforce ASM mapping (≤2h) + coaching.</div></div></div>'; } }
982
    var age=DATA.ageing?DATA.ageing.total:0;
983
    out+='<div class="fix"><div class="sev" style="background:#f59f00"></div><div class="fb"><div class="ft">'+fmtInt(age)+' leads ageing &gt; 7 days</div>'+
984
      '<div class="fd"><b>Stuck open leads by stage</b> — qualified leads not being added to beats lose revival odds.</div>'+
985
      '<div class="act">&rarr; Nudge ASMs to beat-plan qualified LMS within 48h.</div></div></div>';
986
    byId('dashFix').innerHTML=out;
987
  }
988
 
989
  // ---- drill drawer
990
  function openDrawer(crumb,title,sub,html){ byId('dCrumb').textContent=crumb||''; byId('dTitle').textContent=title||'';
991
    byId('dSub').textContent=sub||''; byId('dBody').innerHTML=html||''; byId('ov').classList.add('open'); byId('drawer').classList.add('open'); }
992
  function closeDrawer(){ byId('ov').classList.remove('open'); byId('drawer').classList.remove('open'); }
993
  document.addEventListener('keydown',function(e){ if(e.key==='Escape')closeDrawer();
994
    if(e.key==='/'&&document.activeElement.tagName!=='INPUT'){ e.preventDefault(); byId('lmsSearch').focus(); } });
995
 
996
  function drawerLeadTable(leads){ if(!leads||!leads.length) return '<div class="ph">No leads in this bucket.</div>';
997
    var h='<div class="card"><table><thead><tr><th>LMS ID</th><th>Business</th><th>Stage</th><th>Owner</th><th>SLA</th><th class="num">Value</th></tr></thead><tbody>';
998
    leads.forEach(function(l){ h+='<tr class="clickrow" data-leadid="'+l.id+'"><td><span class="idpill">'+esc(l.lmsCode)+'</span></td>'+
999
      '<td><b>'+esc(l.name||'—')+'</b>'+(l.outlet?'<br><span style="color:#97a1b5;font-size:11px">'+esc(l.outlet)+'</span>':'')+'</td>'+
1000
      '<td>'+stagePill(l.stage,l.stageLabel)+'</td><td>'+esc(l.owner||'—')+'</td><td>'+slaCell(l.slaState)+'</td>'+
1001
      '<td class="num">'+inrShort(l.value)+'</td></tr>'; });
1002
    return h+'</tbody></table></div>'; }
1003
  function drill(crumb,title,sub,bt,bk){ openDrawer(crumb,title,'Loading…','<div class="ph">Loading…</div>');
1004
    var q='?bucketType='+encodeURIComponent(bt)+(bk?'&bucketKey='+encodeURIComponent(bk):'')+qs();
1005
    getJSON('/lms/dashboard/leads'+q,function(d){ var leads=(d&&d.leads)?d.leads:[];
1006
      openDrawer(crumb,title,(sub||'')+' · '+leads.length+' lead(s)',drawerLeadTable(leads)); }); }
1007
 
37651 vikas 1008
  // ---- app-bar search: LMS id / retailer / business / phone / city -> results in the drawer
1009
  var searchTimer=null, searchSeq=0;
1010
  function runSearch(){ var q=(byId('lmsSearch').value||'').trim();
1011
    if(q.length<2){ toast('Type at least 2 characters'); return; }
1012
    var seq=++searchSeq;
1013
    openDrawer('Search','\u201c'+q+'\u201d','Searching…','<div class="ph">Searching…</div>');
1014
    getJSON('/lms/dashboard/search?q='+encodeURIComponent(q),function(d){
1015
      if(seq!==searchSeq) return;                       // a newer search already won
1016
      var leads=(d&&d.leads)?d.leads:[];
1017
      openDrawer('Search','\u201c'+q+'\u201d',leads.length+' match(es)',drawerLeadTable(leads)); },
1018
      function(){ if(seq!==searchSeq) return;
1019
        openDrawer('Search','\u201c'+q+'\u201d','Search failed','<div class="ph">Could not run the search.</div>'); }); }
37692 vikas 1020
  byId('pipeQ').addEventListener('keydown',function(e){
1021
    if(e.key==='Enter'){ e.preventDefault(); pipeSearch(); }
1022
    else if(e.key==='Escape'){ pipeClearSearch(); } });
1023
 
37651 vikas 1024
  byId('lmsSearch').addEventListener('keydown',function(e){
1025
    if(e.key==='Enter'){ e.preventDefault(); clearTimeout(searchTimer); runSearch(); }
1026
    else if(e.key==='Escape'){ this.blur(); closeDrawer(); } });
1027
  byId('lmsSearch').addEventListener('input',function(){ clearTimeout(searchTimer);
1028
    var v=(this.value||'').trim(); if(v.length<2) return;
1029
    searchTimer=setTimeout(runSearch,400); });
1030
 
37125 vikas 1031
  var REPORT_NOTE={ 'State Funnel':'Live from the lead record — grouped by region, BM and ASM.',
1032
    'SLA Compliance':'Live — first_contacted_at vs first_contact_due, owner heat-map.',
1033
    'Ageing':'Live — open leads untouched > 7 days, by stage.',
1034
    'Management Roll-up':'Live — cross-region leads, onboardings and estimated value.',
1035
    'BGC Daily':'Partial — created + dispositions are real; call volume is a PROXY (contacted ÷ days). No telephony bridge yet.',
1036
    'Audit Hygiene':'Partial — missing-disposition & HOLD are shown; DND breaches & recording flags need the call/recording log.',
1037
    'RBM Servicing':'Pending data — repeat-order / complaint / resolution-TAT need order + ticket data outside the lead record.' };
1038
 
1039
  // ---- delegated clicks
1040
  document.addEventListener('click',function(e){
37692 vikas 1041
    var th=e.target.closest('th.sortable'); if(th){ pipeSort(th.getAttribute('data-sort')); return; }
37125 vikas 1042
    var kpi=e.target.closest('.kpi[data-kpi]'); if(kpi){ var b=kpiBucket(kpi.getAttribute('data-kpi'));
1043
      drill('Command Center',kpi.querySelector('.label').textContent,'KPI drill',b[0],b[1]); return; }
1044
    var fs=e.target.closest('.fstep[data-stage]'); if(fs){ var st=fs.getAttribute('data-stage');
1045
      drill('Lifecycle funnel',fs.getAttribute('data-label'),'Reached this stage',st==='ALL'?'ALL':'STAGE',st==='ALL'?'':st); return; }
1046
    var att=e.target.closest('.att[data-att]'); if(att){ drill('Needs attention',att.getAttribute('data-attt'),'Attention queue','ATTENTION',att.getAttribute('data-att')); return; }
1047
    var reg=e.target.closest('tr[data-region]'); if(reg){ drill('State funnel',reg.getAttribute('data-rn'),'Region '+reg.getAttribute('data-region'),'REGION',reg.getAttribute('data-region')); return; }
1048
    var rep=e.target.closest('tr[data-rep]'); if(rep){ var nm=rep.getAttribute('data-rep');
1049
      openDrawer('Report suite',nm,'SOP §18.2','<div class="card"><div class="dnote">'+esc(REPORT_NOTE[nm]||'')+'</div></div>'); return; }
1050
    var lead=e.target.closest('[data-leadid]'); if(lead){ var lid=lead.getAttribute('data-leadid');
1051
      closeDrawer(); LOADED.record=true; byId('recLookup').value=lid; injectRecord(lid);
1052
      go('record',document.querySelectorAll('.tab')[1]); return; }
1053
  });
1054
 
1055
  // ---- filters
1056
  function refresh(){ STATE.regionId=byId('fRegion').value||''; STATE.from=byId('fFrom').value||''; STATE.to=byId('fTo').value||'';
1057
    getJSON('/lms/dashboard/summary?_=1'+qs(),renderSummary); loadPipeline();
1058
    getJSON('/lms/dashboard/state-funnel?_=1'+qs(),renderState);
1059
    getJSON('/lms/dashboard/sla-heatmap?_=1'+qs(),renderHeat);
1060
    getJSON('/lms/dashboard/ageing',renderAgeing);
1061
    byId('dashPeriod').textContent=(STATE.from||'')+' → '+(STATE.to||''); }
1062
  ['fRegion','fFrom','fTo'].forEach(function(id){ byId(id).addEventListener('change',refresh); });
1063
 
1064
  // ====================== LEAD RECORD (native sts-mockup layout, real data) ======================
1065
  var STEPS=[['NEW','New'],['ASSIGNED','Assigned'],['CONTACTED','Contacted'],['QUALIFIED','Qualified'],
1066
    ['BEAT_PLANNED','Beat-plan'],['VISITED','Visited'],['ONBOARDED','Onboarded'],['ACTIVE','Active']];
1067
  function fmtDT(s){ if(!s) return '—'; var d=new Date(s); if(isNaN(d)) return esc(s);
1068
    var mo=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
1069
    function p(n){ return (n<10?'0':'')+n; }
1070
    return p(d.getDate())+' '+mo[d.getMonth()]+' '+d.getFullYear()+' · '+p(d.getHours())+':'+p(d.getMinutes()); }
1071
  function kvRow(k,v){ return '<div class="k">'+k+'</div><div class="v">'+(v==null||v===''?'—':v)+'</div>'; }
1072
  function trailType(t){ if(t==='TELEPHONIC'||t==='CALL') return 'call'; if(!t) return 'sys'; return ''; }
1073
 
1074
  function injectRecord(id){ byId('recordHost').innerHTML='<div class="ph">Loading lead #'+esc(id)+'…</div>';
1075
    getJSON('/lms/dashboard/record?leadId='+encodeURIComponent(id),function(d){ if(!d||!d.id){ byId('recordHost').innerHTML='<div class="ph">Lead #'+esc(id)+' not found.</div>'; return; } renderRecord(d); }); }
1076
  function loadRecord(){ var v=(byId('recLookup').value||'').replace(/\D/g,''); if(!v){ toast('Enter a lead #'); return; } injectRecord(v); }
1077
  function loadRecentRecord(){ getJSON('/lms/dashboard/leads?bucketType=ALL'+qs(),function(d){ var leads=(d&&d.leads)?d.leads:[];
1078
    if(leads.length){ byId('recLookup').value=leads[0].id; injectRecord(leads[0].id); }
1079
    else { byId('recordHost').innerHTML='<div class="ph">No leads to show. Create one from the Create Lead tab.</div>'; } }); }
1080
 
37692 vikas 1081
  /** Trail entries shown before the list starts scrolling. */
1082
  var TRAIL_VISIBLE=5;
1083
 
1084
  /**
1085
   * Cap the trail at TRAIL_VISIBLE entries and scroll the rest.
1086
   *
1087
   * Measured from the 6th entry's own offset rather than assumed from a row height — entries vary a
1088
   * lot (a one-line note, a wrapped remark, one carrying an audio player), so any fixed px guess
1089
   * would cut an entry in half on most leads.
1090
   */
1091
  function capTrail(){
1092
    var box=byId('trailScroll'); if(!box) return;
1093
    var items=box.children;
1094
    if(items.length<=TRAIL_VISIBLE){ box.style.maxHeight=''; box.style.overflowY=''; box.classList.remove('scrolls'); return; }
1095
    var cut=items[TRAIL_VISIBLE];
1096
    box.style.maxHeight=Math.round(cut.offsetTop-box.firstElementChild.offsetTop)+'px';
1097
    box.style.overflowY='auto';
1098
    box.classList.add('scrolls');
1099
  }
1100
 
37125 vikas 1101
  function renderRecord(d){
37692 vikas 1102
    REC=d; CALL.id=null;
37125 vikas 1103
    // header
1104
    var head='<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">'+
1105
      '<div><div class="crumb">'+(d.lmsCode?('<span class="idpill">'+esc(d.lmsCode)+'</span>'):('Lead #'+d.id))+'</div>'+
1106
      '<h1 class="page" style="margin-top:4px">'+esc(d.name||'—')+(d.outlet?' <span style="font-weight:500;color:#59668a;font-size:18px">· '+esc(d.outlet)+'</span>':'')+'</h1></div>'+
1107
      '<div style="display:flex;gap:8px;align-items:center">'+stagePill(d.stage,d.stageLabel)+
1108
      ' <span class="stage" style="background:#eef1f6;color:#69748c">SLA: '+esc(d.slaState||'NA')+'</span>'+
1109
      (d.assignmentStatus==='HOLD'?' <span class="stage st-ni">HOLD</span>':'')+'</div></div>';
1110
    // stepper
1111
    var idx=(d.stageIndex==null?-1:d.stageIndex);
37692 vikas 1112
    // A terminal lead has no stepper to draw, and a whole card repeating what the header pill and
1113
    // the Record card's Current stage already say is just a band of empty space. Omit it.
1114
    var step='';
1115
    if(!d.terminal){
1116
      step='<div class="card" style="padding:16px 22px"><div class="rec-stepper">';
1117
      STEPS.forEach(function(s,i){ var cls=i<idx?'done':(i===idx?'cur':''); var last=(i===STEPS.length-1);
1118
        step+='<div class="rec-step '+cls+'"><div class="dot">'+(i<idx?'&#10003;':(i+1))+'</div><div class="sl">'+esc(s[1])+'</div>'+(last?'':'<div class="bar"></div>')+'</div>'; });
1119
      step+='</div></div>';
1120
    }
37125 vikas 1121
    // details
37692 vikas 1122
    var details='<div class="card"><h2 style="display:flex;align-items:center;justify-content:space-between;gap:10px">Record'+
1123
      '<button class="btn ghost sm" onclick="openEdit()">&#9998; Edit</button></h2>'+
1124
      '<p class="desc">ID, dates &amp; auto-assignment are system-set and immutable. Everything else is correctable.</p>'+
37125 vikas 1125
      '<div class="grid g2" style="gap:20px"><div class="kv">'+
1126
        kvRow('LMS ID', d.lmsCode?('<span class="mono">'+esc(d.lmsCode)+'</span>'):'—')+
1127
        kvRow('Created', fmtDT(d.created)+(d.createdBy?(' · '+esc(d.createdBy)):''))+
1128
        kvRow('Creation path', d.path?('<span class="tag '+(d.path==='B'?'b':'a')+'">'+(d.path==='B'?'B · Field':'A · BGC')+'</span>'):'—')+
1129
        kvRow('Retailer', esc(d.name))+
1130
        kvRow('Business', esc(d.outlet))+
1131
        kvRow('Contact', d.contact?('<span class="mono">'+esc(d.contact)+'</span>'):'—')+
1132
      '</div><div class="kv">'+
1133
        kvRow('Location', esc(d.location))+
1134
        kvRow('Region', esc(d.regionCode))+
1135
        kvRow('Business value', inrShort(d.value))+
1136
        kvRow('Source', esc(d.source))+
1137
        kvRow('Last disposition', d.disposition?esc(d.disposition):'—')+
1138
        kvRow('Owner BM/RSM', esc(d.ownerBm))+
1139
      '</div></div><div class="divider"></div>'+
1140
      '<div class="kv" style="grid-template-columns:130px 1fr 130px 1fr">'+
1141
        kvRow('Working owner', esc(d.owner))+kvRow('Current stage', stagePill(d.stage,d.stageLabel))+
1142
        kvRow('First contact', d.firstContactedAt?fmtDT(d.firstContactedAt):'<span style="color:#e8590c">not yet</span>')+
1143
        kvRow('Unreachable tries', d.unreachableCount==null?'0':d.unreachableCount)+
1144
      '</div></div>';
1145
    // SLA card
1146
    var slaClr=d.slaState==='MET'?'#2f9e44':(d.slaState==='BREACHED'?'#e03131':(d.slaState==='AT_RISK'?'#f08c00':'#69748c'));
1147
    var sla='<div class="card"><h2>First-contact SLA</h2><p class="desc">5-hr commitment from creation (SOP §11).</p>'+
1148
      '<div style="font-size:26px;font-weight:800;color:'+slaClr+'">'+esc(d.slaState||'NA')+'</div>'+
1149
      '<div class="kv" style="margin-top:10px">'+kvRow('Due by', d.firstContactDue?fmtDT(d.firstContactDue):'—')+
1150
      kvRow('First contact', d.firstContactedAt?fmtDT(d.firstContactedAt):'<span style="color:#e8590c">not yet</span>')+'</div></div>';
1151
    // trail
1152
    var trail='<div class="card"><h2>Trail <span style="color:#97a1b5;font-weight:500;font-size:12px">· append-only</span></h2>';
1153
    if(!d.trail||!d.trail.length){ trail+='<div class="ph">No activity yet.</div>'; }
37692 vikas 1154
    else { trail+='<div class="trail" id="trailScroll">'; d.trail.forEach(function(t){
1155
      trail+='<div class="tevt '+trailType(t.type)+'"><div class="tdot">&#9679;</div>'+
1156
        '<div class="tt">'+(t.type?esc(t.type):'Update')+'</div>'+
1157
        '<div class="tm">'+esc(t.actor||'System')+' · '+fmtDT(t.when)+(t.scheduled?(' · scheduled '+fmtDT(t.scheduled)):'')+'</div>'+
1158
        (t.body?('<div class="td">'+esc(t.body)+'</div>'):'');
1159
      // The recording of the call this entry came from, so the agent's account of the conversation
1160
      // and the conversation itself sit together instead of in two separate lists.
1161
      if(t.callId){
1162
        trail+='<div class="trec"><audio controls preload="none" src="'+CTX+'/lms/recording/'+t.callId+'"></audio>'+
1163
          (t.durationSeconds?('<span class="note">'+t.durationSeconds+'s</span>'):'')+
1164
          (t.archived?'':'<span class="note">archiving…</span>')+'</div>';
1165
      }
1166
      trail+='</div>'; }); trail+='</div>'; }
37125 vikas 1167
    trail+='</div>';
1168
 
37692 vikas 1169
    // ---- Click-to-call (SOP §12). VBC places the call server-side: our own device rings first,
1170
    // then the retailer. A blocked number never gets a button at all — the refusal belongs in
1171
    // front of the agent, not in the response to a dial they already started.
1172
    var call='<div class="card"><h2>Click-to-call</h2>';
1173
    if(d.dnd){ call+='<p class="desc" style="color:#e03131"><b>Do-not-call.</b> '+esc(d.dndReason||'This retailer asked not to be contacted.')+'</p>'; }
1174
    else if(!d.contact){ call+='<p class="desc">No contact number on this lead.</p>'; }
1175
    else { call+='<p class="desc">Bridged call &middot; disposition required on disconnect.</p>'+
1176
      '<button class="btn coral" id="callBtn" onclick="startCall()">&#9742; Call retailer (C2C)</button>'+
1177
      '<div id="callBar" class="hide" style="margin-top:12px;padding:12px;border:1px solid #e6e9f2;border-radius:10px;background:#f8f9fc">'+
1178
        '<div style="display:flex;align-items:center;justify-content:space-between;gap:10px">'+
1179
          '<span id="callState" style="font-weight:700;color:#1f2a5e">Starting&hellip;</span>'+
1180
          '<span id="callTimer" class="mono" style="color:#69748c">00:00</span></div>'+
1181
        '<div style="margin-top:10px;display:flex;gap:8px">'+
1182
          '<button class="btn ghost sm" onclick="endCall()">Hang up</button>'+
1183
          '<button class="btn ghost sm" onclick="openDisp()">Disposition&hellip;</button></div>'+
1184
        '<div id="callErr" class="hide" style="margin-top:8px;color:#e03131;font-size:12px"></div></div>'; }
1185
    call+='<div class="note" style="margin-top:10px">A call is only worth what its disposition says — log one on every disconnect.</div></div>';
1186
 
1187
    // ---- Beat plan. Read-only on purpose: adding a stop belongs to the beat planner, and the
1188
    // gate that matters (an approved geo-pin) is what this card exists to report.
1189
    // The card used to state the geo gate and leave the agent to go and find the Leads screen.
1190
    // The action that clears the gate now lives on it.
1191
    var mapLink=(d.geoLat!=null&&d.geoLng!=null)
1192
      ? ' <a class="btn ghost sm" target="_blank" rel="noopener" href="https://www.google.com/maps?q='+d.geoLat+','+d.geoLng+'">View on map</a>' : '';
1193
    var photoLink=(d.geoPhotoId>0)
1194
      ? ' <a class="btn ghost sm" target="_blank" rel="noopener" href="'+CTX+'/open-attachment?documentId='+d.geoPhotoId+'">Store photo</a>' : '';
1195
    var beat='<div class="card"><h2>Beat plan</h2>'+
1196
      (d.geoApproved
1197
        ? '<p class="desc"><span class="stage st-visited">Geo verified</span> &mdash; this lead can be added to a beat.</p>'
1198
        : '<p class="desc" style="color:#a9720a">Geo-pin not yet approved'+
1199
          (d.geoStatus?(' ('+esc(d.geoStatus.toLowerCase())+')'):'')+
1200
          '. Verify the location before adding this lead to a beat.</p>')+
1201
      '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px">'+
1202
        '<button class="btn ghost sm" onclick="openGeo()">'+(d.geoApproved?'Re-verify location':'Verify manually')+'</button>'+
1203
        mapLink+photoLink+'</div>'+
1204
      '<div class="note">Check-in at the retailer moves the stage to Visited.</div></div>';
1205
 
1206
    // ---- Advance stage. Forward-only and comment-mandatory, same rules the endpoint enforces.
1207
    var adv='';
1208
    if(!d.terminal){
1209
      var opts='<option value="" selected disabled>Move to&hellip;</option>';
1210
      STEPS.forEach(function(st,i){ if(i>idx) opts+='<option value="'+st[0]+'">'+esc(st[1])+'</option>'; });
1211
      ['NOT_INTERESTED','DROPPED'].forEach(function(t){ opts+='<option value="'+t+'">'+t.replace('_',' ')+'</option>'; });
1212
      adv='<div class="card"><h2>Advance stage</h2><p class="desc">Forward-only. The comment becomes the trail entry.</p>'+
1213
        '<select id="advStage" class="inp" style="width:100%;margin-bottom:8px">'+opts+'</select>'+
1214
        '<input id="advComment" class="inp" style="width:100%;margin-bottom:10px" placeholder="Comment (required)">'+
1215
        '<button class="btn" style="background:#1f2a5e;color:#fff" onclick="advance()">Advance</button></div>';
1216
    } else {
1217
      adv='<div class="card"><h2>Advance stage</h2><p class="desc">'+esc(d.stageLabel)+' is terminal — this lead cannot be moved on.</p></div>';
1218
    }
1219
 
1220
    byId('recordHost').innerHTML=head+step+
1221
      '<div class="grid g3"><div>'+details+trail+'</div><div>'+sla+call+beat+adv+'</div></div>';
1222
    capTrail();
37125 vikas 1223
  }
1224
 
37692 vikas 1225
  // ====================== RECORD ACTIONS (edit · call · disposition · stage) =================
1226
  // Every control here drives the SAME endpoints the in-app record uses, so the two screens cannot
1227
  // drift into disagreeing about what a disposition or a stage move means.
1228
 
1229
  var REC = null;                 // the record currently rendered, for the action panels
1230
  var CALL = { id:null, poll:null, tick:null, startedAt:0 };
1231
 
1232
  /** POST form-encoded (advanceStage / dialer take @RequestParam, not a JSON body). */
1233
  function postForm(path, params, cb, onErr){
1234
    var body = Object.keys(params).map(function(k){
1235
      return encodeURIComponent(k)+'='+encodeURIComponent(params[k]==null?'':params[k]); }).join('&');
1236
    fetch(CTX+path,{method:'POST',credentials:'same-origin',
1237
      headers:{'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest'},body:body})
1238
      .then(function(r){ return r.text(); })
1239
      .then(function(t){ var d=null; try{ d=JSON.parse(t); }catch(e){}
1240
        var res=(d&&d.response!==undefined)?d.response:d; cb(res); })
1241
      .catch(function(e){ console.error('LMS post failed',path,e);
1242
        if(typeof onErr==='function') onErr(e); else toast('Request failed'); });
1243
  }
1244
 
1245
  /** POST JSON (disposition / updateLead take @RequestBody). */
1246
  function postJSON(path, payload, cb, onErr){
1247
    fetch(CTX+path,{method:'POST',credentials:'same-origin',
1248
      headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},body:JSON.stringify(payload)})
1249
      .then(function(r){ return r.text(); })
1250
      .then(function(t){ var d=null; try{ d=JSON.parse(t); }catch(e){}
1251
        var res=(d&&d.response!==undefined)?d.response:d; cb(res); })
1252
      .catch(function(e){ console.error('LMS post failed',path,e);
1253
        if(typeof onErr==='function') onErr(e); else toast('Request failed'); });
1254
  }
1255
 
1256
  /** A refusal comes back as a bare string under `response`; success is an object. */
1257
  function refusal(res){ return (typeof res==='string' && res) ? res : null; }
1258
 
1259
  function reloadRecord(){ if(REC) injectRecord(REC.id); }
1260
 
1261
  // ---- stage --------------------------------------------------------------------------------
1262
  function advance(){
1263
    var to=byId('advStage').value, c=(byId('advComment').value||'').trim();
1264
    if(!to){ toast('Choose a stage'); return; }
1265
    if(!c){ toast('A comment is required'); return; }
1266
    postForm('/lms/advanceStage',{leadId:REC.id,toStage:to,comment:c},function(res){
1267
      var why=refusal(res); if(why){ toast(why); return; }
1268
      toast('Stage advanced to '+to.replace('_',' '),1); reloadRecord(); refresh();
1269
    });
1270
  }
1271
 
1272
  // ---- edit ---------------------------------------------------------------------------------
1273
  function openEdit(){
1274
    if(!REC) return;
1275
    var regionOpts='<option value="">&mdash; Not set &mdash;</option>';
1276
    // Same region list the Create tab renders, so the two forms cannot offer different regions.
1277
    byId('cRegion').querySelectorAll('option').forEach(function(o){
1278
      if(!o.value) return;
1279
      regionOpts+='<option value="'+esc(o.value)+'"'+(String(REC.regionId)===String(o.value)?' selected':'')+'>'+esc(o.textContent)+'</option>';
1280
    });
1281
    byId('editBody').innerHTML=
1282
      '<div class="kv" style="margin-bottom:14px">'+
1283
        kvRow('LMS ID','<span class="mono">'+esc(REC.lmsCode||('#'+REC.id))+'</span> <span class="note" style="display:inline">locked</span>')+
1284
        kvRow('Created', fmtDT(REC.created)+' <span class="note" style="display:inline">locked</span>')+
1285
      '</div>'+
1286
      '<div class="grid g2" style="gap:12px">'+
1287
        fld('eName','Retailer name (required)',REC.name)+
1288
        fld('eBusiness','Business name',REC.outlet)+
1289
        fld('eContact','Contact number (required)',REC.contact)+
1290
        fld('eValue','Business value (&#8377; lakh / month)',(REC.value>0?Math.round(toLakh(REC.value)*10)/10:''))+
1291
      '</div>'+
1292
      fld('eAddress','Address',REC.address)+
1293
      '<div class="grid g2" style="gap:12px">'+fld('eCity','City',REC.city)+fld('eState','State',REC.state)+'</div>'+
1294
      '<label class="lbl">Region</label><select id="eRegion" class="inp" style="width:100%">'+regionOpts+'</select>'+
1295
      '<div class="note">Changing the region re-runs auto-assignment. A lead already mapped to a named owner keeps that owner.</div>';
1296
    byId('editModal').classList.remove('hide');
1297
  }
1298
  function fld(id,label,val){
1299
    return '<div><label class="lbl">'+label+'</label><input id="'+id+'" class="inp" style="width:100%" value="'+esc(val==null?'':val)+'"></div>';
1300
  }
1301
  function closeEdit(){ byId('editModal').classList.add('hide'); }
1302
  function saveEdit(){
1303
    var name=(byId('eName').value||'').trim();
1304
    if(!name){ toast('Retailer name is required'); return; }
1305
    var mob=(byId('eContact').value||'').replace(/\D/g,'');
1306
    if(mob.length<10){ toast('A valid 10-digit contact number is required'); return; }
1307
    var v=parseFloat(byId('eValue').value), r=byId('eRegion').value;
1308
    postJSON('/lms/updateLead',{leadId:REC.id,retailerName:name,businessName:byId('eBusiness').value,
1309
      mobile:mob,address:byId('eAddress').value,city:byId('eCity').value,state:byId('eState').value,
1310
      regionId:r?parseInt(r,10):null,potential:isNaN(v)?null:v},function(res){
1311
        var why=refusal(res); if(why){ toast(why); return; }
1312
        closeEdit(); toast('Record updated · '+(res&&res.changes||0)+' change(s) logged',1); reloadRecord();
1313
      });
1314
  }
1315
 
1316
  // ---- call ---------------------------------------------------------------------------------
1317
  function callErr(msg){ var e=byId('callErr'); if(!e) return; e.textContent=msg; e.classList.remove('hide'); }
1318
  function callState(t){ var e=byId('callState'); if(e) e.textContent=t; }
1319
  function startCall(){
1320
    if(!REC || CALL.id) return;
1321
    byId('callBtn').disabled=true;
1322
    // Pre-check server-side: DND and the 09:00-21:00 calling window. A check that only lives in
1323
    // the browser is not a check, which is why this endpoint exists at all.
1324
    postForm('/lms/dialer/precheck',{leadId:REC.id},function(res){
1325
      var why=refusal(res);
1326
      if(why || !res || res.ok!==true){ byId('callBtn').disabled=false; toast(why||(res&&res.reason)||'Cannot place the call'); return; }
1327
      byId('callBar').classList.remove('hide'); callState('Ringing your device…');
1328
      postForm('/lms/dialer/dial',{leadId:REC.id},function(r2){
1329
        var w2=refusal(r2);
1330
        if(w2 || !r2 || r2.ok!==true){ byId('callBtn').disabled=false; byId('callBar').classList.add('hide');
1331
          toast(w2||'Could not place the call'); return; }
1332
        CALL.id=r2.leadCallId; CALL.startedAt=Date.now();
1333
        CALL.tick=setInterval(function(){ var s=Math.floor((Date.now()-CALL.startedAt)/1000);
1334
          byId('callTimer').textContent=('0'+Math.floor(s/60)).slice(-2)+':'+('0'+(s%60)).slice(-2); },1000);
1335
        // click2dial has no event webhook, so the browser has to ask.
1336
        CALL.poll=setInterval(pollCall,3000);
1337
      });
1338
    });
1339
  }
1340
  function pollCall(){
1341
    if(!CALL.id) return;
1342
    getJSON('/lms/dialer/state?leadCallId='+CALL.id,function(st){
1343
      if(!st) return;
1344
      if(st.status) callState(String(st.status).replace(/_/g,' ').toLowerCase());
1345
      if(st.terminal){ stopCall(); callState('Call ended'); openDisp(); }
1346
    },function(){ /* a dropped poll is not a dropped call — keep waiting */ });
1347
  }
1348
  function stopCall(){ if(CALL.poll) clearInterval(CALL.poll); if(CALL.tick) clearInterval(CALL.tick);
1349
    CALL.poll=CALL.tick=null; var b=byId('callBtn'); if(b) b.disabled=false; }
1350
  function endCall(){
1351
    if(!CALL.id){ stopCall(); return; }
1352
    postForm('/lms/dialer/hangup',{leadCallId:CALL.id},function(){ stopCall(); callState('Call ended'); openDisp(); });
1353
  }
1354
 
1355
  // ---- disposition --------------------------------------------------------------------------
1356
  var DISPS=[['INTERESTED','Interested'],['CALLBACK','Callback'],['NOT_REACHABLE','Not reachable'],
1357
             ['WRONG_NUMBER','Wrong number'],['FOLLOW_UP','Follow-up'],['NOT_INTERESTED','Not interested'],
1358
             ['DO_NOT_CALL','Do not call']];
1359
  var DISP=null;
1360
  function openDisp(){
1361
    if(!REC) return;
1362
    DISP=null;
1363
    byId('dispGrid').innerHTML=DISPS.map(function(d){
1364
      return '<button class="btn ghost sm dispopt" data-d="'+d[0]+'" onclick="pickDisp(\''+d[0]+'\')">'+d[1]+'</button>'; }).join('');
1365
    byId('dispExtra').innerHTML=''; byId('dispNote').value='';
1366
    byId('dispModal').classList.remove('hide');
1367
  }
1368
  function closeDisp(){ byId('dispModal').classList.add('hide'); }
1369
  function pickDisp(d){
1370
    DISP=d;
1371
    document.querySelectorAll('.dispopt').forEach(function(b){
1372
      b.className='btn '+(b.getAttribute('data-d')===d?'coral':'ghost')+' sm dispopt'; });
1373
    // Contextual sub-fields, mirroring SOP §12.2 and the in-app modal.
1374
    var x='';
1375
    if(d==='INTERESTED')        x=fld('dxValue','Business value (&#8377; lakh / month) — required','');
1376
    else if(d==='CALLBACK')     x='<label class="lbl">Callback date &amp; time — required</label><input id="dxCallback" type="datetime-local" class="inp" style="width:100%">';
1377
    else if(d==='NOT_REACHABLE')x=fld('dxRetry','Retry schedule (optional)','');
1378
    else if(d==='WRONG_NUMBER') x=fld('dxCorrected','Corrected number (blank closes the lead)','');
1379
    else if(d==='FOLLOW_UP')    x='<label class="lbl">Follow-up type</label><select id="dxFuType" class="inp" style="width:100%"><option value="CALL">Call</option><option value="MEETING">Meeting / visit</option></select>'+
1380
                                  '<label class="lbl">Follow-up date &amp; time — required</label><input id="dxFollowUp" type="datetime-local" class="inp" style="width:100%">';
1381
    else if(d==='NOT_INTERESTED')x='<label class="lbl">Sub-reason</label><select id="dxSub" class="inp" style="width:100%">'+
1382
                                  ['Price','Terms','Already partnered','Category mismatch','Other'].map(function(o){return '<option>'+o+'</option>';}).join('')+'</select>';
1383
    else if(d==='DO_NOT_CALL')  x='<div class="note" style="color:#e03131">Blocks this number permanently across every lead, not just this one.</div>';
1384
    byId('dispExtra').innerHTML=x;
1385
  }
1386
  function saveDisp(){
1387
    if(!DISP){ toast('Pick a disposition'); return; }
1388
    var p={leadId:REC.id,disposition:DISP,note:byId('dispNote').value,leadCallId:CALL.id||null};
1389
    if(DISP==='INTERESTED'){ var v=parseFloat(byId('dxValue').value);
1390
      if(!v||v<=0){ toast('Business value is required'); return; } p.value=v; }
1391
    else if(DISP==='CALLBACK'){ if(!byId('dxCallback').value){ toast('Callback date/time is required'); return; }
1392
      p.callbackAt=byId('dxCallback').value; }
1393
    else if(DISP==='NOT_REACHABLE') p.retrySchedule=byId('dxRetry').value;
1394
    else if(DISP==='WRONG_NUMBER')  p.correctedNumber=byId('dxCorrected').value;
1395
    else if(DISP==='FOLLOW_UP'){ if(!byId('dxFollowUp').value){ toast('Follow-up date/time is required'); return; }
1396
      p.followUpType=byId('dxFuType').value; p.followUpAt=byId('dxFollowUp').value; }
1397
    else if(DISP==='NOT_INTERESTED') p.subReason=byId('dxSub').value;
1398
    postJSON('/lms/disposition',p,function(res){
1399
      var why=refusal(res); if(why){ toast(why); return; }
1400
      closeDisp(); CALL.id=null; toast('Disposition saved: '+DISP.replace(/_/g,' '),1); reloadRecord(); refresh();
1401
    });
1402
  }
1403
 
1404
  // ---- manual geo verification ---------------------------------------------------------------
1405
  function geoErr(msg){ var e=byId('geoErr'); e.textContent=msg; e.classList.remove('hide'); }
1406
  function geoClearErr(){ byId('geoErr').classList.add('hide'); }
1407
 
1408
  function openGeo(){
1409
    if(!REC) return;
1410
    geoClearErr();
1411
    // Seed from what the record already knows, so a nudge is an edit rather than a re-entry.
1412
    byId('geoAddress').value=[REC.address,REC.city,REC.state].filter(function(x){return x;}).join(', ');
1413
    byId('geoLatLng').value=(REC.geoLat!=null&&REC.geoLng!=null)?(REC.geoLat+','+REC.geoLng):'';
1414
    byId('geoRemark').value='';
1415
    byId('geoPhoto').value='';
1416
    byId('geoPhotoImg').classList.add('hide');
1417
    byId('geoMapWrap').classList.add('hide');
1418
    byId('geoModal').classList.remove('hide');
1419
    if(REC.geoLat!=null&&REC.geoLng!=null) geoShowMap(REC.geoLat,REC.geoLng);
1420
  }
1421
  function closeGeo(){ byId('geoModal').classList.add('hide'); }
1422
 
1423
  /** Accepts "lat,lng" or a Maps URL: /@lat,lng, ?q=lat,lng, ?ll=, ?destination=. */
1424
  function parseLatLng(raw){
1425
    if(!raw) return null;
1426
    var m=String(raw).match(/(-?\d{1,3}\.\d+)\s*,\s*(-?\d{1,3}\.\d+)/);
1427
    return m?{lat:parseFloat(m[1]),lng:parseFloat(m[2])}:null;
1428
  }
1429
  function geoShowMap(lat,lng){
1430
    byId('geoMapFrame').src='https://www.google.com/maps?q='+lat+','+lng+'&z=17&output=embed';
1431
    byId('geoOpenMap').href='https://www.google.com/maps?q='+lat+','+lng;
1432
    byId('geoMapWrap').classList.remove('hide');
1433
  }
1434
  function geoPreview(){
1435
    var p=parseLatLng(byId('geoLatLng').value);
1436
    if(!p){ geoErr('Enter latitude,longitude first — like 28.6139,77.2090.'); return; }
1437
    geoClearErr(); geoShowMap(p.lat,p.lng);
1438
  }
1439
  function geoGeocode(){
1440
    var a=(byId('geoAddress').value||'').trim();
1441
    if(!a){ geoErr('Enter an address first.'); return; }
1442
    geoClearErr();
1443
    var b=byId('geoFindBtn'); b.disabled=true; b.textContent='Finding…';
1444
    postForm('/lead-geo/geocode-address',{address:a},function(r){
1445
      b.disabled=false; b.textContent='Find on map';
1446
      if(!r||!r.success){ geoErr((r&&r.message)||'Could not geocode that address.'); return; }
1447
      byId('geoLatLng').value=r.latitude+','+r.longitude;
1448
      geoShowMap(r.latitude,r.longitude);
1449
    },function(){ b.disabled=false; b.textContent='Find on map'; geoErr('Geocode request failed.'); });
1450
  }
1451
  function geoPickPhoto(){
1452
    var f=byId('geoPhoto').files&&byId('geoPhoto').files[0];
1453
    if(!f){ byId('geoPhotoImg').classList.add('hide'); return; }
1454
    var fr=new FileReader();
1455
    fr.onload=function(ev){ byId('geoPhotoImg').src=ev.target.result; byId('geoPhotoImg').classList.remove('hide'); };
1456
    fr.readAsDataURL(f);
1457
  }
1458
  function geoSave(){
1459
    var p=parseLatLng(byId('geoLatLng').value);
1460
    if(!p){ geoErr('Could not read latitude/longitude. Paste like 28.6139,77.2090.'); return; }
1461
    if(p.lat<-90||p.lat>90||p.lng<-180||p.lng>180||(p.lat===0&&p.lng===0)){ geoErr('Latitude/longitude out of range.'); return; }
1462
    var f=byId('geoPhoto').files&&byId('geoPhoto').files[0];
1463
    if(!f){ geoErr('Attach a store-board photo — the server requires one.'); return; }
1464
    geoClearErr();
1465
    var b=byId('geoSaveBtn'); b.disabled=true; b.textContent='Uploading photo…';
1466
 
1467
    // Upload first: manual-verify needs the document id, and uploading only on save means a
1468
    // cancelled dialog never orphans a document.
1469
    var fd=new FormData(); fd.append('file',f,f.name||'store-photo.jpg');
1470
    fetch(CTX+'/lead-geo/upload-image',{method:'POST',credentials:'same-origin',
1471
        headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
1472
      .then(function(r){ return r.text(); })
1473
      .then(function(t){
1474
        var d=null; try{ d=JSON.parse(t); }catch(e){}
1475
        var r=(d&&d.response!==undefined)?d.response:d;
1476
        var docId=r&&(r.document_id||r.documentId||r.id);
1477
        if(!docId){ b.disabled=false; b.textContent='Save & verify'; geoErr('Photo upload failed. Try again.'); return; }
1478
        b.textContent='Verifying…';
1479
        postForm('/lead-geo/manual-verify',
1480
          {leadId:REC.id,latitude:p.lat,longitude:p.lng,remark:byId('geoRemark').value,imageDocumentId:docId},
1481
          function(res){
1482
            b.disabled=false; b.textContent='Save & verify';
1483
            var why=refusal(res);
1484
            if(why){ geoErr(why); return; }
1485
            closeGeo(); toast('Location verified — this lead can now go on a beat',1); reloadRecord();
1486
          },
1487
          function(){ b.disabled=false; b.textContent='Save & verify'; geoErr('Could not save the verification.'); });
1488
      })
1489
      .catch(function(){ b.disabled=false; b.textContent='Save & verify'; geoErr('Photo upload failed. Try again.'); });
1490
  }
1491
 
37125 vikas 1492
  // ====================== CREATE LEAD (real /lms/resolve-region + /createLead) ======================
1493
  var CREATE_PATH='A';
1494
  function setPath(p,btn){ CREATE_PATH=p;
1495
    byId('pathA').className='btn '+(p==='A'?'coral':'ghost')+' sm'; byId('pathB').className='btn '+(p==='B'?'coral':'ghost')+' sm';
37651 vikas 1496
    byId('createDesc').textContent=(p==='A')?'Path A — captured by a BGC agent during an outbound call, after consent. Owner is the region BM.':'Path B — field encounter. Owner is you, the creator.';
1497
  }
37125 vikas 1498
  function initials(n){ n=(n||'').trim(); if(!n) return '—'; var p=n.split(/\s+/); return ((p[0]||'')[0]||'').toUpperCase()+((p[1]||'')[0]||'').toUpperCase(); }
1499
  function resolveBM(regionId){ if(!regionId){ byId('rName').textContent='Pick a region…'; byId('rRegion').textContent='—'; byId('raAv').textContent='—';
1500
      byId('rEsc').textContent='The owning BM/RSM is resolved from the region (cs.position).'; return; }
1501
    getJSON('/lms/resolve-region?regionId='+encodeURIComponent(regionId),function(d){ d=d||{};
1502
      byId('rRegion').textContent=d.regionCode||''; var nm=d.bmName||'';
1503
      if(d.assignmentStatus==='HOLD' || !nm){ byId('rName').textContent='No active BM/RSM'; byId('raAv').textContent='!';
1504
        byId('raAv').style.background='#e03131'; byId('rEsc').innerHTML='Region has no active owner &rarr; <b style="color:#e03131">HOLD queue</b>, Sales Head notified.'; }
1505
      else { byId('rName').textContent=nm; byId('raAv').textContent=initials(nm); byId('raAv').style.background='#1f2a5e';
1506
        byId('rEsc').textContent='Auto-resolved from region · escalation contact copied on the assignment email.'; } }); }
37651 vikas 1507
  // ---- brand-wise business value ------------------------------------------------------------
1508
  // Agents write "1L", "50k", "1.5 lakh" as readily as digits, and rejecting those would just push
1509
  // them back to typing a single lump sum. Parsed here so the stored value is always plain rupees.
1510
  function parseMoney(raw){
1511
    if(raw===null||raw===undefined) return 0;
1512
    var t=(''+raw).trim().toLowerCase().replace(/[₹,\s]/g,'');
1513
    if(!t) return 0;
1514
    var m=t.match(/^([0-9]*\.?[0-9]+)(k|l|lac|lacs|lakh|lakhs|cr|crore|crores)?$/);
1515
    if(!m) return 0;
1516
    var n=parseFloat(m[1]); if(isNaN(n)) return 0;
1517
    switch(m[2]){
1518
      case 'k': return Math.round(n*1000);
1519
      case 'l': case 'lac': case 'lacs': case 'lakh': case 'lakhs': return Math.round(n*100000);
1520
      case 'cr': case 'crore': case 'crores': return Math.round(n*10000000);
1521
      default: return Math.round(n);
1522
    }
1523
  }
1524
  function collectBrands(){
1525
    var out=[];
1526
    document.querySelectorAll('#cBrandGrid .bval').forEach(function(el){
1527
      var v=parseMoney(el.value);
1528
      if(v>0) out.push({brand:el.getAttribute('data-brand'), value:v});
1529
    });
1530
    return out;
1531
  }
1532
  function brandTotal(){
1533
    var t=0; collectBrands().forEach(function(b){ t+=b.value; });
1534
    var el=byId('cValueTotal');
1535
    if(el) el.textContent='total '+(t>0?fmtMoney(t):'₹0');
1536
    return t;
1537
  }
1538
  function fmtMoney(n){
1539
    if(n>=10000000) return '₹'+(n/10000000).toFixed(n%10000000?2:0)+'Cr';
1540
    if(n>=100000)   return '₹'+(n/100000).toFixed(n%100000?2:0)+'L';
1541
    if(n>=1000)     return '₹'+(n/1000).toFixed(n%1000?1:0)+'K';
1542
    return '₹'+n;
1543
  }
1544
 
37125 vikas 1545
  function val(id){ var e=byId(id); return e?e.value:''; }
37651 vikas 1546
  function submitLead(){ var fn=val('cRetailer').trim(), biz=val('cBusiness').trim();
1547
    var phone=(val('cContact')||'').replace(/\D/g,'').slice(-10);
1548
    var brands=collectBrands(); var value=brandTotal();
37125 vikas 1549
    var region=val('cRegion'); var path=CREATE_PATH;
37651 vikas 1550
    if(!fn){ toast('Retailer name is required'); return; }
1551
    if(phone.length!==10){ toast('A valid 10-digit contact is required'); return; }
1552
    if(!region){ toast('Pick a region'); return; }
1553
    // No address check on either path any more: the capture link is what establishes location,
1554
    // and it is generated for every lead regardless of path.
1555
    var payload={ firstName:fn, mobile:phone, outletName:biz||'', source:'LMS Dashboard',
1556
      regionId:parseInt(region,10), creationPath:path };
1557
    // potential is the sum, so the funnel's value column keeps working, while the per-brand split
1558
    // is what actually tells a BM what the counter is worth.
37125 vikas 1559
    if(value && value>0) payload.potential=value;
37651 vikas 1560
    if(brands.length) payload.leadBrands=brands;
1561
    // /lms/createLead, NOT the shared /createLead: this one honours regionId and creationPath, so
1562
    // the lead actually gets a stage, an LMS code, an owner and an SLA clock.
1563
    fetch(CTX+'/lms/createLead',{method:'POST',credentials:'same-origin',
1564
        headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
1565
        body:JSON.stringify(payload)})
1566
      .then(function(r){ return r.text(); })
1567
      .then(function(t){
1568
        var d=null; try{ d=JSON.parse(t); }catch(e){ d=null; }
1569
        var res=(d&&d.response)?d.response:d;
1570
        if(!res || res.ok!==true){
1571
          // A refusal carries the reason as a bare string under `response` (badRequest("...")),
1572
          // whereas success is an object. Surface the reason, not a generic failure.
1573
          toast((typeof res==='string' && res) || (res&&res.message) || 'Create failed');
1574
          return;
1575
        }
1576
        var held=(res.assignmentStatus==='HOLD');
1577
        toast(held ? ('Lead '+res.lmsCode+' created · no BM for that region, parked in HOLD')
1578
                   : ('Lead '+res.lmsCode+' created · assigned to '+(res.ownerName||'the region BM')+' · SLA started'), 1);
1579
        ['cRetailer','cBusiness','cContact'].forEach(function(x){ var e=byId(x); if(e) e.value=''; });
1580
        document.querySelectorAll('#cBrandGrid .bval').forEach(function(el){ el.value=''; });
1581
        brandTotal();
1582
 
1583
        // Hand the capture link over immediately — the whole point of generating it on create is
1584
        // that the agent is still on the call with the retailer.
1585
        if(res.geoLink){
1586
          if(navigator.clipboard && navigator.clipboard.writeText){
1587
            navigator.clipboard.writeText(res.geoLink).then(function(){
1588
              alert('Capture link copied to your clipboard — send it to the retailer now:\n\n'+res.geoLink);
1589
            }, function(){ prompt('Send this capture link to the retailer:', res.geoLink); });
1590
          } else {
1591
            prompt('Send this capture link to the retailer:', res.geoLink);
1592
          }
1593
        }
1594
 
1595
        byId('recLookup').value=res.leadId; injectRecord(res.leadId);
1596
        go('record',document.querySelectorAll('.tab')[1]); refresh(); })
37125 vikas 1597
      .catch(function(e){ toast('Create failed'); }); }
1598
 
1599
  // ====================== AUTO-ASSIGNMENT (real resolve per region) ======================
37651 vikas 1600
  function buildAssign(){ var opts=byId('cRegion').querySelectorAll('option'); var holdCount=0, assignedCount=0, pending=0;
1601
    var body=byId('assignMap'); body.innerHTML='';
1602
    // Rows are created up-front in region order, then filled in as each resolve lands — otherwise
1603
    // the table would be ordered by whichever request happened to answer first.
37125 vikas 1604
    opts.forEach(function(o){ if(!o.value) return; pending++;
37651 vikas 1605
      var label=o.textContent;
1606
      var tr=document.createElement('tr');
1607
      tr.innerHTML='<td><b>'+esc(label)+'</b></td><td colspan="2"><span class="ph">Resolving…</span></td>';
1608
      body.appendChild(tr);
1609
      function done(){ if(--pending===0){ renderAssignKpis(assignedCount,holdCount); } }
1610
      getJSON('/lms/resolve-region?regionId='+encodeURIComponent(o.value),function(d){ d=d||{};
37125 vikas 1611
        var hold=(d.assignmentStatus==='HOLD' || !d.bmName);
1612
        if(hold) holdCount++; else assignedCount++;
1613
        tr.innerHTML='<td><b>'+esc(label)+'</b></td>'+
1614
          '<td>'+(hold?'<span class="warnflag">— vacant —</span>':esc(d.bmName))+'</td>'+
1615
          '<td>'+(hold?'<span class="stage st-ni">HOLD</span>':'<span class="stage st-active">Active</span>')+'</td>';
37651 vikas 1616
        done();
1617
      },function(){ tr.innerHTML='<td><b>'+esc(label)+'</b></td><td colspan="2"><span class="warnflag">could not resolve</span></td>';
1618
        done(); }); });
37125 vikas 1619
    // HOLD queue leads
1620
    getJSON('/lms/dashboard/leads?bucketType=ATTENTION&bucketKey=HOLD',function(d){ var leads=(d&&d.leads)?d.leads:[];
1621
      if(!leads.length){ byId('holdQueue').innerHTML='<div class="ph">No leads in HOLD. 🎉</div>'; return; }
1622
      var h=''; leads.slice(0,8).forEach(function(l){ h+='<div style="display:flex;align-items:center;gap:10px;font-size:12.5px;padding:5px 0" class="clickrow" data-leadid="'+l.id+'">'+
1623
        '<span class="idpill">'+esc(l.lmsCode)+'</span> <span>'+esc(l.name||l.outlet||'—')+'</span></div>'; });
1624
      byId('holdQueue').innerHTML=h; }); }
1625
  function renderAssignKpis(assigned,hold){ var k=[
1626
      {i:'&#128231;',bg:'#eef1fb',fg:'#3b5bdb',l:'Regions mapped',v:assigned,f:'active BM/RSM'},
1627
      {i:'&#9208;',bg:'#fff0f0',fg:'#e03131',l:'Regions on HOLD',v:hold,f:'no active BM',vc:'#e03131'},
1628
      {i:'&#128100;',bg:'#fff4e6',fg:'#e8590c',l:'HOLD leads',v:(DATA.summary&&attn('HOLD'))||0,f:'awaiting a BM',vc:'#e8590c'},
1629
      {i:'&#9889;',bg:'#ebfbee',fg:'#2f9e44',l:'Resolve tiers',v:'L4→L5→L3',f:'cs.position'} ];
1630
    var h=''; k.forEach(function(x){ h+='<div class="kpi"><div class="top"><div class="ic" style="background:'+x.bg+';color:'+x.fg+'">'+x.i+'</div>'+
1631
      '<div class="label">'+esc(x.l)+'</div></div><div class="val"'+(x.vc?' style="color:'+x.vc+'"':'')+'>'+(typeof x.v==='number'?fmtInt(x.v):x.v)+'</div><div class="foot">'+esc(x.f)+'</div></div>'; });
1632
    byId('assignKpis').innerHTML=h; }
1633
 
1634
  function attn(key){ var s=DATA.summary; if(!s||!s.attention) return 0; var f=0; s.attention.forEach(function(a){ if(a.key===key)f=a.count; }); return f; }
1635
 
1636
  // ====================== RECORDINGS & AUDIT (live hygiene from attention) ======================
1637
  function buildAudit(){
1638
    // KPIs — missing dispositions is live; recording metrics are pending source.
1639
    var miss=attn('MISSING_DISP'), br=attn('BREACHED_NO_CONTACT'), hold=attn('HOLD');
1640
    var kp=[ {i:'&#127925;',bg:'#fff0ef',fg:'#f0483e',l:'Recordings (24 mo)',v:'—',f:'pending source'},
1641
      {i:'&#128172;',bg:'#fff4e6',fg:'#e8590c',l:'Missing dispositions',v:miss,f:'live',vc:'#e8590c'},
1642
      {i:'&#128683;',bg:'#fff0f0',fg:'#e03131',l:'DND breaches',v:'—',f:'needs call log'},
1643
      {i:'&#128065;',bg:'#eef1fb',fg:'#3b5bdb',l:'Recording opens',v:'—',f:'pending source'},
1644
      {i:'&#129529;',bg:'#e6fcf5',fg:'#0ca678',l:'Onboarded (deep audit)',v:fmtInt(onboardedCount()),f:'5% sampled'} ];
1645
    var h=''; kp.forEach(function(x){ h+='<div class="kpi"><div class="top"><div class="ic" style="background:'+x.bg+';color:'+x.fg+'">'+x.i+'</div>'+
1646
      '<div class="label">'+esc(x.l)+'</div></div><div class="val"'+(x.vc?' style="color:'+x.vc+'"':'')+'>'+(typeof x.v==='number'?fmtInt(x.v):x.v)+'</div><div class="foot">'+esc(x.f)+'</div></div>'; });
1647
    byId('auditKpis').innerHTML=h;
1648
    // hygiene flags (clickable via data-att)
1649
    var flags=[ {k:'MISSING_DISP',i:'&#128172;',bg:'#fff4e6',fg:'#e8590c',t:'LMS with missing dispositions',d:'Next action stays locked until dispositioned',c:'warnflag',v:miss},
1650
      {k:'BREACHED_NO_CONTACT',i:'&#9888;',bg:'#fff0f0',fg:'#e03131',t:'SLA breaches — first contact',d:'Escalated to BM/RSM per matrix',c:'badflag',v:br},
1651
      {k:'HOLD',i:'&#128100;',bg:'#fff0f0',fg:'#e03131',t:'Unassigned records (HOLD)',d:'Region awaiting a BM',c:'badflag',v:hold} ];
1652
    var fh=''; flags.forEach(function(a){ fh+='<div class="att" data-att="'+a.k+'" data-attt="'+esc(a.t)+'"><div class="ic" style="background:'+a.bg+';color:'+a.fg+'">'+a.i+'</div>'+
1653
      '<div class="ab"><div class="atitle">'+esc(a.t)+'</div><div class="adet">'+esc(a.d)+'</div></div><div class="acount '+a.c+'">'+fmtInt(a.v)+'</div></div>'; });
1654
    byId('auditHygiene').innerHTML=fh; }
1655
  function onboardedCount(){ var s=DATA.summary; if(!s||!s.funnel) return 0; var c=0; s.funnel.forEach(function(f){ if(f.stage==='ONBOARDED')c=f.count; }); return c; }
1656
 
1657
  // ---- initial paint from seeds, pipeline loads live
1658
  renderSummary(SEED.summary); renderState(SEED.state); renderHeat(SEED.heat); renderAgeing(SEED.ageing);
1659
  byId('dashPeriod').textContent=(STATE.from||'')+' → '+(STATE.to||'');
1660
  loadPipeline();
1661
 
1662
  // ---- deep-link: a URL hash such as dash or record opens that tab
1663
  (function(){ var TABIDX={cmd:0,record:1,create:2,assign:3,dash:4,audit:5};
1664
    var h=(location.hash||'').replace('#','').trim();
1665
    if(h && TABIDX[h]!=null){ go(h, document.querySelectorAll('.tab')[TABIDX[h]]); }
1666
    window.addEventListener('hashchange',function(){ var k=(location.hash||'').replace('#','').trim();
1667
      if(k && TABIDX[k]!=null){ go(k, document.querySelectorAll('.tab')[TABIDX[k]]); } }); })();
1668
</script>
1669
</body>
1670
</html>