| 37651 |
vikas |
1 |
package com.spice.profitmandi.web.controller;
|
|
|
2 |
|
|
|
3 |
import com.spice.profitmandi.common.web.util.ResponseSender;
|
|
|
4 |
import com.spice.profitmandi.dao.entity.auth.AuthUser;
|
|
|
5 |
import com.spice.profitmandi.dao.entity.user.Lead;
|
|
|
6 |
import com.spice.profitmandi.dao.entity.user.LeadActivity;
|
|
|
7 |
import com.spice.profitmandi.dao.entity.user.LeadCall;
|
|
|
8 |
import com.spice.profitmandi.dao.entity.user.LeadDnd;
|
|
|
9 |
import com.spice.profitmandi.dao.entity.user.LeadLiveLocation;
|
|
|
10 |
import com.spice.profitmandi.dao.enumuration.dtr.CommunicationType;
|
|
|
11 |
import com.spice.profitmandi.dao.enumuration.dtr.LeadDisposition;
|
|
|
12 |
import com.spice.profitmandi.dao.enumuration.dtr.LeadStage;
|
|
|
13 |
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
|
|
|
14 |
import com.spice.profitmandi.dao.repository.dtr.LeadActivityRepository;
|
|
|
15 |
import com.spice.profitmandi.dao.repository.dtr.LeadCallRepository;
|
|
|
16 |
import com.spice.profitmandi.dao.repository.dtr.LeadDndRepository;
|
|
|
17 |
import com.spice.profitmandi.dao.repository.dtr.LeadLiveLocationRepository;
|
| 37737 |
vikas |
18 |
import com.spice.profitmandi.dao.entity.cs.Position;
|
|
|
19 |
import com.spice.profitmandi.dao.entity.cs.Region;
|
|
|
20 |
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
|
|
|
21 |
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
|
| 37651 |
vikas |
22 |
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
|
| 37737 |
vikas |
23 |
import com.spice.profitmandi.dao.entity.user.LeadCallAnswer;
|
|
|
24 |
import com.spice.profitmandi.dao.entity.user.LeadCallQuestion;
|
|
|
25 |
import com.spice.profitmandi.dao.repository.dtr.LeadCallChecklistRepository;
|
| 37651 |
vikas |
26 |
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
|
|
|
27 |
import com.spice.profitmandi.service.LmsAssignmentService;
|
|
|
28 |
import com.spice.profitmandi.web.model.LoginDetails;
|
|
|
29 |
import com.spice.profitmandi.web.util.CookiesProcessor;
|
|
|
30 |
import org.apache.logging.log4j.LogManager;
|
|
|
31 |
import org.apache.logging.log4j.Logger;
|
|
|
32 |
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
33 |
import org.springframework.http.MediaType;
|
|
|
34 |
import org.springframework.http.ResponseEntity;
|
|
|
35 |
import org.springframework.stereotype.Controller;
|
|
|
36 |
import org.springframework.transaction.annotation.Transactional;
|
|
|
37 |
import org.springframework.ui.Model;
|
|
|
38 |
import org.springframework.web.bind.annotation.RequestBody;
|
|
|
39 |
import org.springframework.web.bind.annotation.RequestMapping;
|
|
|
40 |
import org.springframework.web.bind.annotation.RequestMethod;
|
|
|
41 |
import org.springframework.web.bind.annotation.RequestParam;
|
|
|
42 |
import org.springframework.web.bind.annotation.ResponseBody;
|
|
|
43 |
|
|
|
44 |
import javax.servlet.http.HttpServletRequest;
|
|
|
45 |
import java.time.LocalDateTime;
|
|
|
46 |
import java.time.format.DateTimeFormatter;
|
|
|
47 |
import java.util.ArrayList;
|
| 37737 |
vikas |
48 |
import java.util.Arrays;
|
| 37651 |
vikas |
49 |
import java.util.HashMap;
|
|
|
50 |
import java.util.HashSet;
|
|
|
51 |
import java.util.List;
|
|
|
52 |
import com.spice.profitmandi.dao.model.LeadBrandModel;
|
|
|
53 |
import com.spice.profitmandi.dao.model.LeadDetailModel;
|
|
|
54 |
import org.springframework.beans.factory.annotation.Value;
|
|
|
55 |
import org.springframework.http.HttpStatus;
|
|
|
56 |
import java.util.LinkedHashMap;
|
|
|
57 |
import java.util.Map;
|
|
|
58 |
import java.util.Set;
|
|
|
59 |
|
|
|
60 |
/**
|
|
|
61 |
* LMS operating core — the per-lead screen and the two mutations it drives (SOP §8/§10/§12).
|
|
|
62 |
*
|
|
|
63 |
* <ul>
|
|
|
64 |
* <li><b>{@code GET /leadRecord}</b> — full-page lead record fragment ({@code lead-record.vm}),
|
|
|
65 |
* loaded into {@code #main-content} and also opened from the standalone dashboard.</li>
|
|
|
66 |
* <li><b>{@code POST /lms/advanceStage}</b> — forward-only stage move with a mandatory comment.</li>
|
|
|
67 |
* <li><b>{@code POST /lms/disposition}</b> — call outcome; drives the stage transition, stamps
|
|
|
68 |
* first contact (closing the SLA) and appends to the trail.</li>
|
|
|
69 |
* <li><b>{@code GET /lms/resolve-region}</b> — region → owning BM/RSM preview, used by the
|
|
|
70 |
* Create-Lead form and the dashboard's Auto-Assignment tab.</li>
|
|
|
71 |
* </ul>
|
|
|
72 |
*
|
|
|
73 |
* Every mutation appends an immutable {@link LeadActivity} row and keeps the legacy
|
|
|
74 |
* {@code Lead.status} in sync via {@link LeadStage#toLegacyStatus()}, so the existing lead lists,
|
|
|
75 |
* exports and beat flows keep working untouched. Read-side aggregation lives in
|
|
|
76 |
* {@code LmsDashboardService}; assignment/SLA rules live in {@link LmsAssignmentService}.
|
|
|
77 |
*/
|
|
|
78 |
@Controller
|
|
|
79 |
@Transactional(rollbackFor = Throwable.class)
|
|
|
80 |
public class LmsLeadController {
|
|
|
81 |
|
|
|
82 |
private static final Logger LOGGER = LogManager.getLogger(LmsLeadController.class);
|
|
|
83 |
|
|
|
84 |
/**
|
|
|
85 |
* How far back to look when binding a disposition to a call the browser did not name. Long
|
|
|
86 |
* enough to cover a call plus the agent typing up the outcome; short enough that this morning's
|
|
|
87 |
* call never gets attached to this afternoon's disposition.
|
|
|
88 |
*/
|
|
|
89 |
private static final int CALL_BIND_WINDOW_MINUTES = 30;
|
|
|
90 |
|
|
|
91 |
/** Trail/record timestamp format, shared by every date the record page prints. */
|
|
|
92 |
private static final DateTimeFormatter RECORD_FORMAT = DateTimeFormatter.ofPattern("dd MMM yyyy · HH:mm");
|
|
|
93 |
|
|
|
94 |
@Autowired
|
|
|
95 |
private LeadRepository leadRepository;
|
|
|
96 |
|
|
|
97 |
@Autowired
|
|
|
98 |
private LeadActivityRepository leadActivityRepository;
|
|
|
99 |
|
|
|
100 |
@Autowired
|
|
|
101 |
private LeadLiveLocationRepository leadLiveLocationRepository;
|
|
|
102 |
|
|
|
103 |
@Autowired
|
|
|
104 |
private LeadCallRepository leadCallRepository;
|
|
|
105 |
|
|
|
106 |
@Autowired
|
| 37737 |
vikas |
107 |
private LeadCallChecklistRepository leadCallChecklistRepository;
|
|
|
108 |
|
|
|
109 |
@Autowired
|
| 37651 |
vikas |
110 |
private LeadDndRepository leadDndRepository;
|
|
|
111 |
|
|
|
112 |
@Autowired
|
|
|
113 |
private AuthRepository authRepository;
|
|
|
114 |
|
|
|
115 |
@Autowired
|
|
|
116 |
private RegionRepository regionRepository;
|
|
|
117 |
|
|
|
118 |
@Autowired
|
| 37737 |
vikas |
119 |
private PositionRepository positionRepository;
|
|
|
120 |
|
|
|
121 |
@Autowired
|
| 37651 |
vikas |
122 |
private LmsAssignmentService lmsAssignmentService;
|
|
|
123 |
|
|
|
124 |
@Autowired
|
|
|
125 |
private CookiesProcessor cookiesProcessor;
|
|
|
126 |
|
|
|
127 |
@Autowired
|
|
|
128 |
private ResponseSender<?> responseSender;
|
|
|
129 |
|
|
|
130 |
// ---- Record page ------------------------------------------------------------------------
|
|
|
131 |
|
|
|
132 |
/**
|
|
|
133 |
* Full lead record: details, stepper, append-only trail, SLA card and the act-on-it controls.
|
|
|
134 |
* Returned as a fragment — the caller drops it into {@code #main-content}.
|
|
|
135 |
*/
|
|
|
136 |
// Same property the Leads screen's Generate Link button uses, so both produce an identical URL.
|
|
|
137 |
@Value("${lead.geo.public.base-url:}")
|
|
|
138 |
private String leadGeoPublicBaseUrl;
|
|
|
139 |
|
|
|
140 |
@RequestMapping(value = "/leadRecord", method = RequestMethod.GET)
|
|
|
141 |
public String leadRecord(@RequestParam(name = "leadId") int leadId, Model model) {
|
|
|
142 |
Lead lead = leadRepository.selectById(leadId);
|
|
|
143 |
if (lead == null) {
|
|
|
144 |
// Fragment contract: whatever comes back is dropped straight into #main-content.
|
|
|
145 |
model.addAttribute("response1",
|
|
|
146 |
"<div class=\"alert alert-warning\">Lead #" + leadId + " not found.</div>");
|
|
|
147 |
return "response";
|
|
|
148 |
}
|
|
|
149 |
|
|
|
150 |
LeadStage effectiveStage = lead.getEffectiveStage();
|
|
|
151 |
model.addAttribute("lead", lead);
|
|
|
152 |
model.addAttribute("effectiveStage", effectiveStage);
|
|
|
153 |
model.addAttribute("stageIndex", happyPathIndex(effectiveStage));
|
|
|
154 |
model.addAttribute("terminal", isTerminal(effectiveStage));
|
|
|
155 |
model.addAttribute("stages", LeadStage.HAPPY_PATH);
|
|
|
156 |
model.addAttribute("dispositions", LeadDisposition.values());
|
|
|
157 |
model.addAttribute("slaState", lmsAssignmentService.slaState(lead));
|
| 37692 |
vikas |
158 |
model.addAttribute("businessValue", lakhLabel(lead.getPotential()));
|
|
|
159 |
model.addAttribute("businessValueInput", lakhInput(lead.getPotential()));
|
| 37651 |
vikas |
160 |
model.addAttribute("dateTimeFormatter", RECORD_FORMAT);
|
|
|
161 |
|
|
|
162 |
// Region picker in the edit modal — the same list the Create-Lead form offers.
|
|
|
163 |
model.addAttribute("regions", regionRepository.selectAll());
|
|
|
164 |
|
|
|
165 |
model.addAttribute("owner", lead.getAssignTo() > 0 ? authRepository.selectById(lead.getAssignTo()) : null);
|
|
|
166 |
model.addAttribute("bm", (lead.getOwnerBmId() != null && lead.getOwnerBmId() > 0)
|
|
|
167 |
? authRepository.selectById(lead.getOwnerBmId()) : null);
|
|
|
168 |
|
|
|
169 |
LeadLiveLocation geo = leadLiveLocationRepository.selectByLeadId(leadId);
|
|
|
170 |
model.addAttribute("geo", geo);
|
|
|
171 |
|
|
|
172 |
// A blocked number must be visible before the agent reaches for the call button, not only
|
|
|
173 |
// discovered when the dial is refused.
|
|
|
174 |
model.addAttribute("dnd", leadDndRepository.selectByMobile(lead.getLeadMobile()));
|
|
|
175 |
List<LeadCall> calls = leadCallRepository.selectByLeadId(leadId);
|
|
|
176 |
model.addAttribute("calls", calls);
|
|
|
177 |
// Keyed by id so a disposition in the trail can show the recording of the call it came from.
|
|
|
178 |
// A disposition is the agent's account of the conversation; having to hunt for the audio in a
|
|
|
179 |
// separate list to check it against the recording is the friction worth removing here.
|
|
|
180 |
Map<Integer, LeadCall> callById = new HashMap<>();
|
|
|
181 |
if (calls != null) {
|
|
|
182 |
for (LeadCall c : calls) {
|
|
|
183 |
callById.put(c.getId(), c);
|
|
|
184 |
}
|
|
|
185 |
}
|
|
|
186 |
model.addAttribute("callById", callById);
|
|
|
187 |
|
|
|
188 |
// Append-only trail, newest first, with actor names resolved in one batch.
|
|
|
189 |
List<LeadActivity> trail = leadActivityRepository.selectBYLeadId(leadId);
|
|
|
190 |
if (trail == null) {
|
|
|
191 |
trail = new ArrayList<>();
|
|
|
192 |
}
|
|
|
193 |
trail.sort((a, b) -> {
|
|
|
194 |
LocalDateTime ta = a.getCreatedTimestamp();
|
|
|
195 |
LocalDateTime tb = b.getCreatedTimestamp();
|
|
|
196 |
if (ta == null && tb == null) {
|
|
|
197 |
return 0;
|
|
|
198 |
}
|
|
|
199 |
if (ta == null) {
|
|
|
200 |
return 1;
|
|
|
201 |
}
|
|
|
202 |
if (tb == null) {
|
|
|
203 |
return -1;
|
|
|
204 |
}
|
|
|
205 |
return tb.compareTo(ta);
|
|
|
206 |
});
|
|
|
207 |
model.addAttribute("trail", trail);
|
|
|
208 |
model.addAttribute("authUserMap", actorsOf(trail));
|
|
|
209 |
|
|
|
210 |
return "lead-record";
|
|
|
211 |
}
|
|
|
212 |
|
|
|
213 |
// ---- Mutations --------------------------------------------------------------------------
|
|
|
214 |
|
|
|
215 |
/**
|
|
|
216 |
* Move a lead forward along the happy path (or to a terminal state). Forward-only: the enum
|
|
|
217 |
* decides what is legal, so a stale page cannot walk a lead backwards. Comment is mandatory —
|
|
|
218 |
* it becomes the trail entry.
|
|
|
219 |
*/
|
|
|
220 |
@RequestMapping(value = "/lms/advanceStage", method = RequestMethod.POST)
|
|
|
221 |
@ResponseBody
|
|
|
222 |
public ResponseEntity<?> advanceStage(HttpServletRequest request,
|
|
|
223 |
@RequestParam(name = "leadId") int leadId,
|
|
|
224 |
@RequestParam(name = "toStage") String toStage,
|
|
|
225 |
@RequestParam(name = "comment") String comment) {
|
|
|
226 |
if (comment == null || comment.trim().isEmpty()) {
|
|
|
227 |
return responseSender.badRequest("A comment is required to change the stage");
|
|
|
228 |
}
|
|
|
229 |
Lead lead = leadRepository.selectById(leadId);
|
|
|
230 |
if (lead == null) {
|
|
|
231 |
return responseSender.notFound("Lead not found");
|
|
|
232 |
}
|
|
|
233 |
|
|
|
234 |
LeadStage target;
|
|
|
235 |
try {
|
|
|
236 |
target = LeadStage.valueOf(toStage);
|
|
|
237 |
} catch (IllegalArgumentException e) {
|
|
|
238 |
return responseSender.badRequest("Unknown stage: " + toStage);
|
|
|
239 |
}
|
|
|
240 |
|
|
|
241 |
LeadStage current = lead.getEffectiveStage();
|
|
|
242 |
if (isTerminal(current)) {
|
|
|
243 |
return responseSender.badRequest(pretty(current) + " is a terminal state — the lead cannot be moved on");
|
|
|
244 |
}
|
|
|
245 |
if (!current.canAdvanceTo(target)) {
|
|
|
246 |
return responseSender.badRequest("Cannot move from " + pretty(current) + " to " + pretty(target));
|
|
|
247 |
}
|
|
|
248 |
|
|
|
249 |
AuthUser actor = currentUser(request);
|
|
|
250 |
applyStage(lead, target);
|
|
|
251 |
leadRepository.persist(lead);
|
| 37692 |
vikas |
252 |
appendTrail(leadId, actor,
|
|
|
253 |
latin1Safe("Stage " + pretty(current) + " -> " + pretty(target) + ": " + comment.trim()),
|
|
|
254 |
null, null);
|
| 37651 |
vikas |
255 |
|
|
|
256 |
LOGGER.info("LMS stage advanced: lead {} {} -> {} by {}", leadId, current, target,
|
|
|
257 |
actor != null ? actor.getId() : 0);
|
|
|
258 |
return responseSender.ok(stateOf(lead));
|
|
|
259 |
}
|
|
|
260 |
|
|
|
261 |
/**
|
|
|
262 |
* Record a call outcome (SOP §12.2). The disposition drives the stage transition; the first
|
|
|
263 |
* dispositioned contact stamps {@code firstContactedAt}, which is what closes the 5-hr SLA.
|
|
|
264 |
*/
|
|
|
265 |
@RequestMapping(value = "/lms/disposition", method = RequestMethod.POST,
|
|
|
266 |
consumes = MediaType.APPLICATION_JSON_VALUE)
|
|
|
267 |
@ResponseBody
|
|
|
268 |
public ResponseEntity<?> disposition(HttpServletRequest request,
|
|
|
269 |
@RequestBody DispositionRequest body) {
|
|
|
270 |
if (body == null || body.disposition == null || body.disposition.trim().isEmpty()) {
|
|
|
271 |
return responseSender.badRequest("A disposition is required");
|
|
|
272 |
}
|
|
|
273 |
Lead lead = leadRepository.selectById(body.leadId);
|
|
|
274 |
if (lead == null) {
|
|
|
275 |
return responseSender.notFound("Lead not found");
|
|
|
276 |
}
|
|
|
277 |
|
|
|
278 |
LeadDisposition disposition;
|
|
|
279 |
try {
|
|
|
280 |
disposition = LeadDisposition.valueOf(body.disposition);
|
|
|
281 |
} catch (IllegalArgumentException e) {
|
|
|
282 |
return responseSender.badRequest("Unknown disposition: " + body.disposition);
|
|
|
283 |
}
|
|
|
284 |
if (disposition == LeadDisposition.INTERESTED && (body.value == null || body.value <= 0)) {
|
|
|
285 |
return responseSender.badRequest("Business value is required on an INTERESTED disposition");
|
|
|
286 |
}
|
|
|
287 |
|
|
|
288 |
AuthUser actor = currentUser(request);
|
|
|
289 |
LeadStage before = lead.getEffectiveStage();
|
|
|
290 |
LeadCall call = resolveCall(body, lead, actor);
|
|
|
291 |
|
| 37692 |
vikas |
292 |
String subReason = latin1Safe(trimToNull(body.subReason));
|
|
|
293 |
if (subReason != null && subReason.length() > 64) {
|
|
|
294 |
return responseSender.badRequest("Sub-reason is too long - keep it to 64 characters");
|
|
|
295 |
}
|
| 37651 |
vikas |
296 |
lead.setDisposition(disposition);
|
| 37692 |
vikas |
297 |
lead.setDispositionSubReason(subReason);
|
| 37651 |
vikas |
298 |
// Interim manual path — drops out when the dialer starts filling recordings from the webhook.
|
|
|
299 |
if (body.recordingUrl != null && !body.recordingUrl.trim().isEmpty()) {
|
|
|
300 |
lead.setRecordingUrl(body.recordingUrl.trim());
|
|
|
301 |
}
|
|
|
302 |
// Reaching the retailer IS the first contact — stamp once, never move it. NOT_REACHABLE (nobody
|
|
|
303 |
// answered) and WRONG_NUMBER (not the retailer) are not contact: they must not satisfy the SLA,
|
|
|
304 |
// and they must not disturb a stamp an earlier real contact already set.
|
|
|
305 |
if (lead.getFirstContactedAt() == null && countsAsContact(disposition)) {
|
|
|
306 |
// Prefer the moment the retailer actually picked up over "now" — the agent may sit on the
|
|
|
307 |
// disposition modal for minutes, and that gap would silently eat into the 5-hr SLA.
|
|
|
308 |
LocalDateTime contactedAt = (call != null && call.getAnsweredAt() != null)
|
|
|
309 |
? call.getAnsweredAt() : LocalDateTime.now();
|
|
|
310 |
lead.setFirstContactedAt(contactedAt);
|
|
|
311 |
}
|
|
|
312 |
|
|
|
313 |
LocalDateTime scheduled = parseLocal(body.callbackAt != null ? body.callbackAt : body.followUpAt);
|
|
|
314 |
applyDispositionStage(lead, disposition, body);
|
|
|
315 |
leadRepository.persist(lead);
|
|
|
316 |
|
|
|
317 |
CommunicationType type = "MEETING".equalsIgnoreCase(body.followUpType)
|
|
|
318 |
? CommunicationType.VISIT : CommunicationType.TELEPHONIC;
|
|
|
319 |
LeadActivity activity = appendTrail(body.leadId, actor,
|
| 37692 |
vikas |
320 |
latin1Safe(dispositionRemark(disposition, before, lead, body)), type, scheduled,
|
| 37651 |
vikas |
321 |
call != null ? call.getId() : null);
|
|
|
322 |
|
|
|
323 |
// Bind both ways: the trail entry knows its call (for duration + a recording link), and the
|
|
|
324 |
// call knows the disposition it produced (so an unactioned call is findable).
|
|
|
325 |
if (call != null) {
|
|
|
326 |
call.setLeadActivityId(activity.getId());
|
|
|
327 |
leadCallRepository.persist(call);
|
|
|
328 |
}
|
|
|
329 |
|
|
|
330 |
if (disposition == LeadDisposition.DO_NOT_CALL) {
|
|
|
331 |
blockFurtherCalls(lead, actor, body);
|
|
|
332 |
}
|
|
|
333 |
|
|
|
334 |
LOGGER.info("LMS disposition {} on lead {} ({} -> {}) by {}, call {}", disposition, body.leadId, before,
|
|
|
335 |
lead.getEffectiveStage(), actor != null ? actor.getId() : 0, call != null ? call.getId() : null);
|
|
|
336 |
return responseSender.ok(stateOf(lead));
|
|
|
337 |
}
|
|
|
338 |
|
|
|
339 |
/**
|
|
|
340 |
* Which call this disposition is about. The browser normally passes {@code leadCallId} straight
|
|
|
341 |
* from the dialer; when it cannot (agent dialled from their own handset, or the page reloaded
|
|
|
342 |
* mid-call) we fall back to this agent's most recent call on this lead that no disposition has
|
|
|
343 |
* claimed yet. Deliberately narrow — binding the wrong call is worse than binding none, because
|
|
|
344 |
* it would attach someone else's recording to this lead's trail.
|
|
|
345 |
*/
|
|
|
346 |
private LeadCall resolveCall(DispositionRequest body, Lead lead, AuthUser actor) {
|
|
|
347 |
if (body.leadCallId != null && body.leadCallId > 0) {
|
|
|
348 |
LeadCall call = leadCallRepository.selectById(body.leadCallId);
|
|
|
349 |
if (call != null && call.getLeadId() == lead.getId()) {
|
|
|
350 |
return call;
|
|
|
351 |
}
|
|
|
352 |
LOGGER.warn("Ignoring leadCallId {} on lead {} — missing or belongs to another lead",
|
|
|
353 |
body.leadCallId, lead.getId());
|
|
|
354 |
return null;
|
|
|
355 |
}
|
|
|
356 |
if (actor == null) {
|
|
|
357 |
return null;
|
|
|
358 |
}
|
|
|
359 |
LeadCall latest = leadCallRepository.selectLatestByLeadIdAndAuthId(lead.getId(), actor.getId());
|
|
|
360 |
if (latest == null || latest.getLeadActivityId() != null) {
|
|
|
361 |
return null;
|
|
|
362 |
}
|
|
|
363 |
LocalDateTime startedAt = latest.getStartedAt() != null ? latest.getStartedAt() : latest.getCreatedTimestamp();
|
|
|
364 |
if (startedAt == null || startedAt.isBefore(LocalDateTime.now().minusMinutes(CALL_BIND_WINDOW_MINUTES))) {
|
|
|
365 |
return null;
|
|
|
366 |
}
|
|
|
367 |
return latest;
|
|
|
368 |
}
|
|
|
369 |
|
|
|
370 |
/**
|
|
|
371 |
* DO_NOT_CALL means never ring this retailer again (SOP §17). Blocks the number, not the lead —
|
|
|
372 |
* the same person recurs as several leads and a per-lead block would not hold. Before this the
|
|
|
373 |
* disposition only moved the stage, and nothing stopped a re-dial.
|
|
|
374 |
*/
|
|
|
375 |
private void blockFurtherCalls(Lead lead, AuthUser actor, DispositionRequest body) {
|
|
|
376 |
LeadDnd dnd = new LeadDnd();
|
|
|
377 |
dnd.setMobile(lead.getLeadMobile());
|
|
|
378 |
dnd.setLeadId(lead.getId());
|
|
|
379 |
dnd.setAuthId(actor != null ? actor.getId() : null);
|
|
|
380 |
dnd.setSource("DISPOSITION");
|
| 37692 |
vikas |
381 |
dnd.setReason(latin1Safe(trimToNull(body.note) != null
|
|
|
382 |
? trimToNull(body.note) : "Retailer asked not to be contacted"));
|
| 37651 |
vikas |
383 |
leadDndRepository.block(dnd);
|
|
|
384 |
LOGGER.info("LMS DND block on lead {} by {}", lead.getId(), actor != null ? actor.getId() : 0);
|
|
|
385 |
}
|
|
|
386 |
|
|
|
387 |
/**
|
|
|
388 |
* Correct the record's own fields (SOP §6).
|
|
|
389 |
*
|
|
|
390 |
* <p>Everything else on this screen either moves the lead forward or logs a conversation;
|
|
|
391 |
* nothing could fix a misheard shop name or a location that was never captured. Between the
|
|
|
392 |
* create form (which writes {@code address}/{@code city}/{@code state} empty and leaves the
|
|
|
393 |
* geo link to supply the real location) and the legacy Leads edit (which only touches status,
|
|
|
394 |
* assignee, city and state, and is gated behind an approved geo-pin), a lead's business name,
|
|
|
395 |
* address and region were unreachable once created.
|
|
|
396 |
*
|
|
|
397 |
* <p>What stays immutable is what the SOP makes immutable (§7.1): the LMS id, the created
|
|
|
398 |
* stamp, the creation path, the stage and the SLA clock. Region is editable but is not a plain
|
|
|
399 |
* field edit — it re-resolves the owning BM/RSM, so it is handled as a re-assignment below.
|
|
|
400 |
*
|
|
|
401 |
* <p>Every accepted change writes its own trail entry. One entry per field rather than one per
|
|
|
402 |
* save, so "who changed this number, and when" is answerable without diffing two saves.
|
|
|
403 |
*/
|
|
|
404 |
@RequestMapping(value = "/lms/updateLead", method = RequestMethod.POST,
|
|
|
405 |
consumes = MediaType.APPLICATION_JSON_VALUE)
|
|
|
406 |
@ResponseBody
|
|
|
407 |
public ResponseEntity<?> updateLead(HttpServletRequest request, @RequestBody UpdateLeadRequest body) {
|
|
|
408 |
if (body == null) {
|
|
|
409 |
return responseSender.badRequest("Nothing to update");
|
|
|
410 |
}
|
|
|
411 |
Lead lead = leadRepository.selectById(body.leadId);
|
|
|
412 |
if (lead == null) {
|
|
|
413 |
return responseSender.notFound("Lead not found");
|
|
|
414 |
}
|
|
|
415 |
AuthUser me = currentUser(request);
|
|
|
416 |
if (me == null) {
|
|
|
417 |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
|
418 |
}
|
|
|
419 |
|
| 37692 |
vikas |
420 |
String name = latin1Safe(trimToNull(body.retailerName));
|
| 37651 |
vikas |
421 |
if (name == null) {
|
|
|
422 |
return responseSender.badRequest("Retailer name is required");
|
|
|
423 |
}
|
| 37692 |
vikas |
424 |
|
|
|
425 |
// These columns are narrow (city and state are varchar(30)) and the server runs
|
|
|
426 |
// STRICT_TRANS_TABLES, so an over-long value is a 500 at flush rather than a rejected field.
|
|
|
427 |
// Check here and name the field, so the agent can shorten it instead of losing the edit.
|
|
|
428 |
String tooLong = firstTooLong(
|
|
|
429 |
"Retailer name", name, 128,
|
|
|
430 |
"Business name", body.businessName, 100,
|
|
|
431 |
"Address", body.address, 128,
|
|
|
432 |
"City", body.city, 30,
|
|
|
433 |
"State", body.state, 30);
|
|
|
434 |
if (tooLong != null) {
|
|
|
435 |
return responseSender.badRequest(tooLong);
|
|
|
436 |
}
|
| 37651 |
vikas |
437 |
String mobile = digitsOnly(body.mobile);
|
|
|
438 |
if (mobile == null || mobile.length() < 10) {
|
|
|
439 |
return responseSender.badRequest("A valid 10-digit contact number is required");
|
|
|
440 |
}
|
|
|
441 |
mobile = mobile.substring(mobile.length() - 10);
|
|
|
442 |
|
|
|
443 |
// A number change is the one edit that can quietly undo a compliance decision, so it gets
|
|
|
444 |
// the same two checks the create form runs rather than being trusted as a typo fix.
|
|
|
445 |
boolean mobileChanged = !mobile.equals(lead.getLeadMobile());
|
|
|
446 |
if (mobileChanged) {
|
|
|
447 |
if (leadDndRepository.selectByMobile(mobile) != null) {
|
|
|
448 |
return responseSender.badRequest("That number is on the do-not-call register.");
|
|
|
449 |
}
|
|
|
450 |
Lead other = leadRepository.selectByMobileNumber(mobile);
|
|
|
451 |
if (other != null && other.getId() != lead.getId()) {
|
|
|
452 |
return responseSender.badRequest("Lead #" + other.getId() + " already exists for " + mobile);
|
|
|
453 |
}
|
|
|
454 |
}
|
|
|
455 |
|
|
|
456 |
List<String> entries = new ArrayList<>();
|
|
|
457 |
|
|
|
458 |
String beforeName = joinName(lead.getFirstName(), lead.getLastName());
|
|
|
459 |
if (!name.equals(beforeName)) {
|
|
|
460 |
int space = name.lastIndexOf(' ');
|
| 37692 |
vikas |
461 |
// Both halves are varchar(64); a long single-token name would otherwise fail at flush.
|
|
|
462 |
if ((space > 0 ? name.substring(0, space) : name).length() > 64
|
|
|
463 |
|| (space > 0 ? name.substring(space + 1) : "").length() > 64) {
|
|
|
464 |
return responseSender.badRequest(
|
|
|
465 |
"Retailer name is too long - keep each part to 64 characters");
|
|
|
466 |
}
|
| 37651 |
vikas |
467 |
lead.setFirstName(space > 0 ? name.substring(0, space) : name);
|
|
|
468 |
// user.lead.last_name is NOT NULL — a single-word name keeps an empty surname, not null.
|
|
|
469 |
lead.setLastName(space > 0 ? name.substring(space + 1) : "");
|
|
|
470 |
entries.add(fieldChange("Retailer", beforeName, name));
|
|
|
471 |
}
|
|
|
472 |
if (mobileChanged) {
|
|
|
473 |
entries.add(fieldChange("Contact", lead.getLeadMobile(), mobile));
|
|
|
474 |
lead.setLeadMobile(mobile);
|
|
|
475 |
}
|
|
|
476 |
|
| 37692 |
vikas |
477 |
String outlet = latin1Safe(trimToNull(body.businessName));
|
| 37651 |
vikas |
478 |
if (!same(lead.getOutLetName(), outlet)) {
|
|
|
479 |
entries.add(fieldChange("Business", lead.getOutLetName(), outlet));
|
|
|
480 |
lead.setOutLetName(outlet == null ? "" : outlet);
|
|
|
481 |
}
|
|
|
482 |
|
|
|
483 |
// address / city / state are NOT NULL — blanked fields are written empty, never null.
|
| 37692 |
vikas |
484 |
String address = latin1Safe(trimToEmpty(body.address));
|
|
|
485 |
String city = latin1Safe(trimToEmpty(body.city));
|
|
|
486 |
String state = latin1Safe(trimToEmpty(body.state));
|
| 37651 |
vikas |
487 |
String beforeLocation = locationOf(lead.getAddress(), lead.getCity(), lead.getState());
|
|
|
488 |
String afterLocation = locationOf(address, city, state);
|
|
|
489 |
if (!beforeLocation.equals(afterLocation)) {
|
|
|
490 |
lead.setAddress(address);
|
|
|
491 |
lead.setCity(city);
|
|
|
492 |
lead.setState(state);
|
|
|
493 |
entries.add(fieldChange("Location", beforeLocation, afterLocation));
|
|
|
494 |
}
|
|
|
495 |
|
|
|
496 |
if (body.potential != null && body.potential >= 0 && body.potential != lead.getPotential()) {
|
|
|
497 |
entries.add(fieldChange("Business value",
|
|
|
498 |
lead.getPotential() > 0 ? money(lead.getPotential()) : null, money(body.potential)));
|
|
|
499 |
lead.setPotential(body.potential);
|
|
|
500 |
}
|
|
|
501 |
|
|
|
502 |
// Region last: it is a re-assignment, and it reads better in the trail after the field edits.
|
|
|
503 |
if (body.regionId != null && body.regionId > 0 && !body.regionId.equals(lead.getRegionId())) {
|
|
|
504 |
LmsAssignmentService.Assignment a = lmsAssignmentService.resolve(body.regionId);
|
|
|
505 |
if (a.regionId == null) {
|
|
|
506 |
return responseSender.badRequest("Unknown region");
|
|
|
507 |
}
|
|
|
508 |
Integer previousBm = lead.getOwnerBmId();
|
|
|
509 |
String beforeRegion = lead.getRegionCode();
|
|
|
510 |
lead.setRegionId(a.regionId);
|
|
|
511 |
lead.setRegionCode(a.regionCode);
|
|
|
512 |
lead.setAssignmentStatus(a.assignmentStatus);
|
|
|
513 |
lead.setOwnerBmId(a.bm != null ? a.bm.getId() : null);
|
|
|
514 |
|
|
|
515 |
// Follow the region only while the lead is still sitting with whoever the engine picked.
|
|
|
516 |
// Once a BM has handed it to a named ASM, that mapping is a decision — moving the region
|
|
|
517 |
// must not silently undo it.
|
|
|
518 |
boolean stillAutoAssigned = lead.getAssignTo() <= 0
|
|
|
519 |
|| (previousBm != null && lead.getAssignTo() == previousBm.intValue());
|
|
|
520 |
if (stillAutoAssigned) {
|
|
|
521 |
lead.setAssignTo(a.bm != null ? a.bm.getId() : 0);
|
|
|
522 |
}
|
|
|
523 |
|
|
|
524 |
StringBuilder move = new StringBuilder(fieldChange("Region", beforeRegion, a.regionCode));
|
|
|
525 |
if (a.bm != null) {
|
|
|
526 |
move.append(" · owner re-resolved to ").append(a.bm.getFullName());
|
|
|
527 |
if (!stillAutoAssigned) {
|
| 37692 |
vikas |
528 |
move.append(" (working owner left unchanged - the lead is mapped to a named user)");
|
| 37651 |
vikas |
529 |
}
|
|
|
530 |
} else {
|
|
|
531 |
move.append(" · no active BM/RSM for that region, moved to the HOLD queue");
|
|
|
532 |
}
|
|
|
533 |
entries.add(move.toString());
|
|
|
534 |
}
|
|
|
535 |
|
|
|
536 |
if (entries.isEmpty()) {
|
|
|
537 |
return responseSender.badRequest("Nothing changed");
|
|
|
538 |
}
|
|
|
539 |
|
|
|
540 |
lead.setUpdatedTimestamp(LocalDateTime.now());
|
|
|
541 |
leadRepository.persist(lead);
|
|
|
542 |
for (String entry : entries) {
|
| 37692 |
vikas |
543 |
trail(lead.getId(), me.getId(), latin1Safe(entry));
|
| 37651 |
vikas |
544 |
}
|
|
|
545 |
|
|
|
546 |
LOGGER.info("LMS lead {} edited by auth {} — {}", lead.getId(), me.getId(), entries);
|
|
|
547 |
Map<String, Object> out = new LinkedHashMap<>();
|
|
|
548 |
out.put("ok", true);
|
|
|
549 |
out.put("leadId", lead.getId());
|
|
|
550 |
out.put("changes", entries.size());
|
|
|
551 |
return responseSender.ok(out);
|
|
|
552 |
}
|
|
|
553 |
|
|
|
554 |
/** Payload for {@link #updateLead}. Only the fields this screen is allowed to correct. */
|
|
|
555 |
public static class UpdateLeadRequest {
|
|
|
556 |
public int leadId;
|
|
|
557 |
public String retailerName;
|
|
|
558 |
public String businessName;
|
|
|
559 |
public String mobile;
|
|
|
560 |
public String address;
|
|
|
561 |
public String city;
|
|
|
562 |
public String state;
|
|
|
563 |
public Integer regionId;
|
|
|
564 |
public Double potential;
|
|
|
565 |
}
|
|
|
566 |
|
| 37692 |
vikas |
567 |
/**
|
|
|
568 |
* Trail line for one edited field.
|
|
|
569 |
*
|
|
|
570 |
* <p>ASCII only, deliberately. {@code user.lead_activity.remark} is latin1_swedish_ci, so an
|
|
|
571 |
* arrow or an em dash makes the INSERT fail with "Incorrect string value" — and because the
|
|
|
572 |
* failure surfaces at flush rather than at the write, it arrives as an unrelated-looking
|
|
|
573 |
* "null id in LeadActivity entry" 500.
|
|
|
574 |
*/
|
| 37651 |
vikas |
575 |
private String fieldChange(String label, String before, String after) {
|
| 37692 |
vikas |
576 |
return label + " " + orDash(before) + " -> " + orDash(after);
|
| 37651 |
vikas |
577 |
}
|
|
|
578 |
|
|
|
579 |
private String orDash(String s) {
|
| 37692 |
vikas |
580 |
return (s == null || s.trim().isEmpty()) ? "(not set)" : s.trim();
|
| 37651 |
vikas |
581 |
}
|
|
|
582 |
|
| 37692 |
vikas |
583 |
/**
|
|
|
584 |
* First over-long field, as a message naming it and its limit; null when all fit.
|
|
|
585 |
*
|
|
|
586 |
* <p>Args come in (label, value, max) triples. Retailer name is checked against 128 because it
|
|
|
587 |
* is split across first_name and last_name, which are varchar(64) each.
|
|
|
588 |
*/
|
|
|
589 |
private String firstTooLong(Object... fields) {
|
|
|
590 |
for (int i = 0; i + 2 < fields.length; i += 3) {
|
|
|
591 |
String label = (String) fields[i];
|
|
|
592 |
String value = (String) fields[i + 1];
|
|
|
593 |
int max = (Integer) fields[i + 2];
|
|
|
594 |
if (value != null && value.trim().length() > max) {
|
|
|
595 |
return label + " is too long - keep it to " + max + " characters (currently "
|
|
|
596 |
+ value.trim().length() + ")";
|
|
|
597 |
}
|
|
|
598 |
}
|
|
|
599 |
return null;
|
|
|
600 |
}
|
|
|
601 |
|
|
|
602 |
/**
|
|
|
603 |
* Make caller-supplied text safe for the latin1 columns this controller writes.
|
|
|
604 |
*
|
|
|
605 |
* <p>Every text column here — {@code lead_activity.remark}, {@code lead.disposition_sub_reason},
|
|
|
606 |
* the address fields — is latin1_swedish_ci. Fixing our own literals was only half the job: an
|
|
|
607 |
* agent pastes a note from WhatsApp or Word and it arrives full of smart quotes, en dashes and
|
|
|
608 |
* ellipses, none of which exist in latin1. That INSERT fails, and because the failure surfaces
|
|
|
609 |
* at flush it reads as "null id in LeadActivity entry" rather than as a bad character.
|
|
|
610 |
*
|
|
|
611 |
* <p>The common typographic characters are transliterated rather than dropped, because losing an
|
|
|
612 |
* apostrophe out of "retailer's shop" is silent damage. Anything else outside latin1 (emoji,
|
|
|
613 |
* Devanagari) becomes '?' — visible, so it is obvious the text was not stored verbatim.
|
|
|
614 |
*/
|
|
|
615 |
private String latin1Safe(String s) {
|
|
|
616 |
if (s == null || s.isEmpty()) {
|
|
|
617 |
return s;
|
|
|
618 |
}
|
|
|
619 |
StringBuilder out = new StringBuilder(s.length());
|
|
|
620 |
for (int i = 0; i < s.length(); i++) {
|
|
|
621 |
char c = s.charAt(i);
|
|
|
622 |
switch (c) {
|
|
|
623 |
case '\u2018': case '\u2019': case '\u201B': out.append('\''); break; // ' ' ‛
|
|
|
624 |
case '\u201C': case '\u201D': case '\u201E': out.append('"'); break; // " " „
|
|
|
625 |
case '\u2013': case '\u2014': case '\u2212': out.append('-'); break; // – — −
|
|
|
626 |
case '\u2026': out.append("..."); break; // …
|
|
|
627 |
case '\u2192': out.append("->"); break; // →
|
|
|
628 |
case '\u20B9': out.append("Rs"); break; // ₹
|
|
|
629 |
case '\u00A0': out.append(' '); break; // nbsp
|
|
|
630 |
default:
|
|
|
631 |
out.append(c <= 0xFF ? c : '?');
|
|
|
632 |
}
|
|
|
633 |
}
|
|
|
634 |
return out.toString();
|
|
|
635 |
}
|
|
|
636 |
|
| 37651 |
vikas |
637 |
private boolean same(String a, String b) {
|
|
|
638 |
return orDash(a).equals(orDash(b));
|
|
|
639 |
}
|
|
|
640 |
|
|
|
641 |
private String trimToEmpty(String s) {
|
|
|
642 |
return s == null ? "" : s.trim();
|
|
|
643 |
}
|
|
|
644 |
|
|
|
645 |
private String joinName(String first, String last) {
|
|
|
646 |
String joined = ((first == null ? "" : first) + " " + (last == null ? "" : last)).trim();
|
|
|
647 |
return joined.replaceAll("\\s+", " ");
|
|
|
648 |
}
|
|
|
649 |
|
|
|
650 |
/** "address, city, state" with the empty parts dropped — what the record row prints. */
|
|
|
651 |
private String locationOf(String address, String city, String state) {
|
|
|
652 |
StringBuilder sb = new StringBuilder();
|
|
|
653 |
for (String part : new String[]{address, city, state}) {
|
|
|
654 |
if (part == null || part.trim().isEmpty()) {
|
|
|
655 |
continue;
|
|
|
656 |
}
|
|
|
657 |
if (sb.length() > 0) {
|
|
|
658 |
sb.append(", ");
|
|
|
659 |
}
|
|
|
660 |
sb.append(part.trim());
|
|
|
661 |
}
|
|
|
662 |
return sb.toString();
|
|
|
663 |
}
|
|
|
664 |
|
|
|
665 |
private String money(double value) {
|
| 37692 |
vikas |
666 |
String label = lakhLabel(value);
|
|
|
667 |
return label == null ? "(not set)" : label + "/mo";
|
| 37651 |
vikas |
668 |
}
|
|
|
669 |
|
|
|
670 |
/**
|
| 37737 |
vikas |
671 |
* First-call checklist for a lead (SOP §9 Path A step 2).
|
|
|
672 |
*
|
|
|
673 |
* <p>Returns the active question set, any answers already recorded, and — the part the caller
|
|
|
674 |
* cannot work out for itself — whether this is actually the lead's FIRST connected call.
|
|
|
675 |
*
|
|
|
676 |
* <p>"First" means no earlier <em>answered</em> call. A string of unanswered dials does not make
|
|
|
677 |
* the next one a second call: as far as the retailer is concerned nobody has spoken to them yet,
|
|
|
678 |
* and that is exactly when the checklist is worth asking.
|
|
|
679 |
*/
|
|
|
680 |
@RequestMapping(value = "/lms/checklist", method = RequestMethod.GET)
|
|
|
681 |
@ResponseBody
|
|
|
682 |
public ResponseEntity<?> checklist(@RequestParam(name = "leadId") int leadId,
|
|
|
683 |
@RequestParam(name = "leadCallId", required = false) Integer leadCallId) {
|
|
|
684 |
Lead lead = leadRepository.selectById(leadId);
|
|
|
685 |
if (lead == null) {
|
|
|
686 |
return responseSender.notFound("Lead not found");
|
|
|
687 |
}
|
|
|
688 |
|
|
|
689 |
// Only the questions that belong at the lead's CURRENT stage. A question tagged
|
|
|
690 |
// NEW|ASSIGNED is a first-call question by construction; one tagged VISITED is not, and
|
|
|
691 |
// showing the whole bank on every call is how a checklist becomes something people skip.
|
|
|
692 |
String stage = lead.getEffectiveStage() == null ? null : lead.getEffectiveStage().name();
|
|
|
693 |
List<LeadCallAnswer> answers = leadCallChecklistRepository.selectAnswersByLeadId(leadId);
|
|
|
694 |
Map<Integer, LeadCallAnswer> byQuestion = new HashMap<>();
|
|
|
695 |
for (LeadCallAnswer a : answers) {
|
|
|
696 |
byQuestion.put(a.getQuestionId(), a);
|
|
|
697 |
}
|
|
|
698 |
|
|
|
699 |
List<Map<String, Object>> out = new ArrayList<>();
|
|
|
700 |
int availablePoints = 0;
|
|
|
701 |
for (LeadCallQuestion q : leadCallChecklistRepository.selectActiveQuestions()) {
|
|
|
702 |
if (!q.appliesTo(stage)) {
|
|
|
703 |
continue;
|
|
|
704 |
}
|
|
|
705 |
LeadCallAnswer a = byQuestion.get(q.getId());
|
|
|
706 |
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
707 |
m.put("id", q.getId());
|
|
|
708 |
m.put("prompt", q.getPrompt());
|
|
|
709 |
m.put("answerType", q.getAnswerType());
|
|
|
710 |
m.put("choices", q.getChoices() == null || q.getChoices().trim().isEmpty()
|
|
|
711 |
? new ArrayList<String>() : Arrays.asList(q.getChoices().split("\\|")));
|
|
|
712 |
m.put("required", q.isRequired());
|
|
|
713 |
m.put("points", q.getPoints());
|
|
|
714 |
m.put("answer", a == null ? null : a.getAnswer());
|
|
|
715 |
out.add(m);
|
|
|
716 |
availablePoints += q.getPoints();
|
|
|
717 |
}
|
|
|
718 |
|
|
|
719 |
// Score is over EVERY answer the lead has, not just the ones showing now — a lead that
|
|
|
720 |
// answered the early questions keeps those points when it moves on to a later stage.
|
|
|
721 |
int score = 0;
|
|
|
722 |
for (LeadCallAnswer a : answers) {
|
|
|
723 |
score += a.getPointsAwarded();
|
|
|
724 |
}
|
|
|
725 |
|
|
|
726 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
727 |
res.put("leadId", leadId);
|
|
|
728 |
res.put("stage", stage);
|
|
|
729 |
res.put("questions", out);
|
|
|
730 |
res.put("answered", !answers.isEmpty());
|
|
|
731 |
res.put("score", score);
|
|
|
732 |
res.put("availablePoints", availablePoints);
|
|
|
733 |
res.put("firstCall", !leadCallChecklistRepository.hasEarlierConnectedCall(leadId, leadCallId));
|
|
|
734 |
// Worth showing on the panel: the checklist is about this retailer, not a generic form.
|
|
|
735 |
res.put("retailer", joinName(lead.getFirstName(), lead.getLastName()));
|
|
|
736 |
return responseSender.ok(res);
|
|
|
737 |
}
|
|
|
738 |
|
|
|
739 |
/** Record (or correct) the checklist answers for a lead. */
|
|
|
740 |
@RequestMapping(value = "/lms/checklist", method = RequestMethod.POST,
|
|
|
741 |
consumes = MediaType.APPLICATION_JSON_VALUE)
|
|
|
742 |
@ResponseBody
|
|
|
743 |
public ResponseEntity<?> saveChecklist(HttpServletRequest request, @RequestBody ChecklistRequest body) {
|
|
|
744 |
if (body == null || body.leadId <= 0) {
|
|
|
745 |
return responseSender.badRequest("Nothing to save");
|
|
|
746 |
}
|
|
|
747 |
Lead lead = leadRepository.selectById(body.leadId);
|
|
|
748 |
if (lead == null) {
|
|
|
749 |
return responseSender.notFound("Lead not found");
|
|
|
750 |
}
|
|
|
751 |
AuthUser me = currentUser(request);
|
|
|
752 |
if (me == null) {
|
|
|
753 |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
|
754 |
}
|
|
|
755 |
|
|
|
756 |
Map<Integer, LeadCallQuestion> active = new HashMap<>();
|
|
|
757 |
for (LeadCallQuestion q : leadCallChecklistRepository.selectActiveQuestions()) {
|
|
|
758 |
active.put(q.getId(), q);
|
|
|
759 |
}
|
|
|
760 |
|
|
|
761 |
int saved = 0;
|
|
|
762 |
int points = 0;
|
|
|
763 |
List<String> summary = new ArrayList<>();
|
|
|
764 |
if (body.answers != null) {
|
|
|
765 |
for (ChecklistAnswer a : body.answers) {
|
|
|
766 |
LeadCallQuestion q = active.get(a.questionId);
|
|
|
767 |
// Ignore anything that is not a live question rather than storing an answer to
|
|
|
768 |
// something the screen never asked.
|
|
|
769 |
if (q == null) {
|
|
|
770 |
continue;
|
|
|
771 |
}
|
|
|
772 |
String value = trimToNull(a.answer);
|
|
|
773 |
if (value == null) {
|
|
|
774 |
continue;
|
|
|
775 |
}
|
|
|
776 |
if (value.length() > 1000) {
|
|
|
777 |
value = value.substring(0, 1000);
|
|
|
778 |
}
|
|
|
779 |
LeadCallAnswer row = new LeadCallAnswer();
|
|
|
780 |
row.setLeadId(body.leadId);
|
|
|
781 |
row.setLeadCallId(body.leadCallId);
|
|
|
782 |
row.setQuestionId(q.getId());
|
|
|
783 |
row.setAuthId(me.getId());
|
|
|
784 |
row.setAnswer(value);
|
|
|
785 |
// Snapshot the points as priced today, so re-pricing the question later does not
|
|
|
786 |
// retroactively change what this lead scored.
|
|
|
787 |
row.setPointsAwarded(q.getPoints());
|
|
|
788 |
leadCallChecklistRepository.saveAnswer(row);
|
|
|
789 |
saved++;
|
|
|
790 |
points += q.getPoints();
|
|
|
791 |
summary.add(q.getPrompt() + ": " + value);
|
|
|
792 |
}
|
|
|
793 |
}
|
|
|
794 |
|
|
|
795 |
if (saved > 0) {
|
|
|
796 |
// The trail is where the lead's story lives; a checklist that only existed in its own
|
|
|
797 |
// table would be invisible to anyone reading the record.
|
|
|
798 |
trail(body.leadId, me.getId(), latin1Safe("Checklist recorded (" + saved + " answer"
|
|
|
799 |
+ (saved == 1 ? "" : "s") + ", " + points + " pts) - " + String.join(" \u00b7 ", summary)));
|
|
|
800 |
}
|
|
|
801 |
|
|
|
802 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
803 |
res.put("ok", true);
|
|
|
804 |
res.put("saved", saved);
|
|
|
805 |
res.put("points", points);
|
|
|
806 |
LOGGER.info("Checklist saved for lead {} ({} answers) by auth {}", body.leadId, saved, me.getId());
|
|
|
807 |
return responseSender.ok(res);
|
|
|
808 |
}
|
|
|
809 |
|
|
|
810 |
// ---- Assignment -------------------------------------------------------------------------
|
|
|
811 |
|
|
|
812 |
/** Sales category in {@code cs.position} — the same one auto-assignment resolves owners from. */
|
|
|
813 |
private static final int SALES_CATEGORY = com.spice.profitmandi.common.model.ProfitMandiConstants.TICKET_CATEGORY_SALES;
|
|
|
814 |
|
|
|
815 |
/** Tiers a lead can be assigned to. L6+ exist but are not lead owners. */
|
|
|
816 |
private static final List<EscalationType> SALES_TIERS = Arrays.asList(
|
|
|
817 |
EscalationType.L1, EscalationType.L2, EscalationType.L3, EscalationType.L4, EscalationType.L5);
|
|
|
818 |
|
|
|
819 |
/**
|
|
|
820 |
* Sales people a lead can be assigned to, grouped by escalation tier (L1–L5).
|
|
|
821 |
*
|
|
|
822 |
* <p>Read from {@code cs.position}, the same source auto-assignment resolves owners from, so the
|
|
|
823 |
* manual list and the engine can never disagree about who is a sales owner.
|
|
|
824 |
*
|
|
|
825 |
* <p>{@code regionId} does not filter the list — it marks who covers that region, so an agent can
|
|
|
826 |
* see the right owner first without being prevented from picking someone else. A lead in a
|
|
|
827 |
* region with no active owner still has to go to somebody.
|
|
|
828 |
*/
|
|
|
829 |
@RequestMapping(value = "/lms/salespeople", method = RequestMethod.GET)
|
|
|
830 |
@ResponseBody
|
|
|
831 |
public ResponseEntity<?> salespeople(@RequestParam(name = "regionId", required = false) Integer regionId) {
|
|
|
832 |
List<Position> positions = positionRepository.selectPositionByCategoryId(SALES_CATEGORY);
|
|
|
833 |
if (positions == null) {
|
|
|
834 |
positions = new ArrayList<>();
|
|
|
835 |
}
|
|
|
836 |
|
|
|
837 |
Set<Integer> ids = new HashSet<>();
|
|
|
838 |
for (Position p : positions) {
|
|
|
839 |
if (SALES_TIERS.contains(p.getEscalationType())) {
|
|
|
840 |
ids.add(p.getAuthUserId());
|
|
|
841 |
}
|
|
|
842 |
}
|
|
|
843 |
Map<Integer, AuthUser> users = new HashMap<>();
|
|
|
844 |
if (!ids.isEmpty()) {
|
|
|
845 |
for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ids))) {
|
|
|
846 |
users.put(u.getId(), u);
|
|
|
847 |
}
|
|
|
848 |
}
|
|
|
849 |
|
|
|
850 |
// One row per person per tier: somebody can hold an L4 in one region and an L5 in another,
|
|
|
851 |
// and collapsing that would hide which hat they are being picked under.
|
|
|
852 |
Map<String, Map<String, Object>> byKey = new LinkedHashMap<>();
|
|
|
853 |
for (Position p : positions) {
|
|
|
854 |
if (!SALES_TIERS.contains(p.getEscalationType())) {
|
|
|
855 |
continue;
|
|
|
856 |
}
|
|
|
857 |
AuthUser u = users.get(p.getAuthUserId());
|
|
|
858 |
if (u == null || !Boolean.TRUE.equals(u.isActive())) {
|
|
|
859 |
continue; // never offer a departed colleague as an owner
|
|
|
860 |
}
|
|
|
861 |
String key = p.getAuthUserId() + ":" + p.getEscalationType().name();
|
|
|
862 |
Map<String, Object> m = byKey.get(key);
|
|
|
863 |
if (m == null) {
|
|
|
864 |
m = new LinkedHashMap<>();
|
|
|
865 |
m.put("authId", u.getId());
|
|
|
866 |
m.put("name", u.getFullName());
|
|
|
867 |
m.put("email", u.getEmailId());
|
|
|
868 |
m.put("tier", p.getEscalationType().name());
|
|
|
869 |
m.put("regions", new ArrayList<String>());
|
|
|
870 |
m.put("coversRegion", false);
|
|
|
871 |
byKey.put(key, m);
|
|
|
872 |
}
|
|
|
873 |
Region r = p.getRegionId() > 0 ? regionRepository.selectById(p.getRegionId()) : null;
|
|
|
874 |
if (r != null) {
|
|
|
875 |
@SuppressWarnings("unchecked")
|
|
|
876 |
List<String> regions = (List<String>) m.get("regions");
|
|
|
877 |
String code = r.getRegionCode() != null ? r.getRegionCode() : r.getName();
|
|
|
878 |
if (code != null && !regions.contains(code)) {
|
|
|
879 |
regions.add(code);
|
|
|
880 |
}
|
|
|
881 |
if (regionId != null && regionId > 0 && r.getId() == regionId) {
|
|
|
882 |
m.put("coversRegion", true);
|
|
|
883 |
}
|
|
|
884 |
}
|
|
|
885 |
}
|
|
|
886 |
|
|
|
887 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
888 |
res.put("people", new ArrayList<>(byKey.values()));
|
|
|
889 |
List<String> tiers = new ArrayList<>();
|
|
|
890 |
for (EscalationType t : SALES_TIERS) {
|
|
|
891 |
tiers.add(t.name());
|
|
|
892 |
}
|
|
|
893 |
res.put("tiers", tiers);
|
|
|
894 |
return responseSender.ok(res);
|
|
|
895 |
}
|
|
|
896 |
|
|
|
897 |
/**
|
|
|
898 |
* Assign a lead to a sales person.
|
|
|
899 |
*
|
|
|
900 |
* <p>Sets the working owner ({@code assign_to}) only. The auto-resolved {@code owner_bm_id} is
|
|
|
901 |
* left alone: it records which BM the region routed to, and overwriting it on a manual hand-off
|
|
|
902 |
* would erase the routing decision the SLA and the HOLD queue are measured against.
|
|
|
903 |
*/
|
|
|
904 |
@RequestMapping(value = "/lms/assignLead", method = RequestMethod.POST)
|
|
|
905 |
@ResponseBody
|
|
|
906 |
public ResponseEntity<?> assignLead(HttpServletRequest request,
|
|
|
907 |
@RequestParam(name = "leadId") int leadId,
|
|
|
908 |
@RequestParam(name = "authId") int authId) {
|
|
|
909 |
Lead lead = leadRepository.selectById(leadId);
|
|
|
910 |
if (lead == null) {
|
|
|
911 |
return responseSender.notFound("Lead not found");
|
|
|
912 |
}
|
|
|
913 |
AuthUser me = currentUser(request);
|
|
|
914 |
if (me == null) {
|
|
|
915 |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
|
916 |
}
|
|
|
917 |
AuthUser owner = authRepository.selectById(authId);
|
|
|
918 |
if (owner == null || !Boolean.TRUE.equals(owner.isActive())) {
|
|
|
919 |
return responseSender.badRequest("That person is not an active user");
|
|
|
920 |
}
|
|
|
921 |
|
|
|
922 |
// Must hold a sales position — otherwise any auth id could be made a lead owner, and the
|
|
|
923 |
// pipeline would show owners the assignment engine has never heard of.
|
|
|
924 |
EscalationType tier = null;
|
|
|
925 |
List<Position> held = positionRepository.selectPositionByAuthId(authId);
|
|
|
926 |
if (held != null) {
|
|
|
927 |
for (Position p : held) {
|
|
|
928 |
if (p.getCategoryId() == SALES_CATEGORY && SALES_TIERS.contains(p.getEscalationType())) {
|
|
|
929 |
tier = p.getEscalationType();
|
|
|
930 |
break;
|
|
|
931 |
}
|
|
|
932 |
}
|
|
|
933 |
}
|
|
|
934 |
if (tier == null) {
|
|
|
935 |
return responseSender.badRequest(owner.getFullName() + " does not hold a sales position (L1-L5)");
|
|
|
936 |
}
|
|
|
937 |
|
|
|
938 |
AuthUser previous = lead.getAssignTo() > 0 ? authRepository.selectById(lead.getAssignTo()) : null;
|
|
|
939 |
if (previous != null && previous.getId() == authId) {
|
|
|
940 |
return responseSender.badRequest("Already assigned to " + owner.getFullName());
|
|
|
941 |
}
|
|
|
942 |
|
|
|
943 |
lead.setAssignTo(authId);
|
|
|
944 |
// A lead sitting in HOLD because its region had no owner now has one.
|
|
|
945 |
if ("HOLD".equalsIgnoreCase(lead.getAssignmentStatus())) {
|
|
|
946 |
lead.setAssignmentStatus("ASSIGNED");
|
|
|
947 |
}
|
|
|
948 |
lead.setUpdatedTimestamp(LocalDateTime.now());
|
|
|
949 |
leadRepository.persist(lead);
|
|
|
950 |
|
|
|
951 |
trail(leadId, me.getId(), latin1Safe("Assigned to " + owner.getFullName() + " (" + tier.name() + ")"
|
|
|
952 |
+ (previous != null ? " from " + previous.getFullName() : "")));
|
|
|
953 |
|
|
|
954 |
LOGGER.info("Lead {} assigned to auth {} ({}) by auth {}", leadId, authId, tier, me.getId());
|
|
|
955 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
956 |
res.put("ok", true);
|
|
|
957 |
res.put("leadId", leadId);
|
|
|
958 |
res.put("owner", owner.getFullName());
|
|
|
959 |
res.put("tier", tier.name());
|
|
|
960 |
return responseSender.ok(res);
|
|
|
961 |
}
|
|
|
962 |
|
|
|
963 |
// ---- Checklist question management (CRUD) -----------------------------------------------
|
|
|
964 |
|
|
|
965 |
/** Every question, active and inactive, for the management screen. */
|
|
|
966 |
@RequestMapping(value = "/lms/checklist/questions", method = RequestMethod.GET)
|
|
|
967 |
@ResponseBody
|
|
|
968 |
public ResponseEntity<?> listQuestions() {
|
|
|
969 |
List<Map<String, Object>> out = new ArrayList<>();
|
|
|
970 |
for (LeadCallQuestion q : leadCallChecklistRepository.selectAllQuestions()) {
|
|
|
971 |
out.add(questionJson(q));
|
|
|
972 |
}
|
|
|
973 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
974 |
res.put("questions", out);
|
|
|
975 |
// The screen builds its stage picker from this rather than hardcoding the ladder, so a new
|
|
|
976 |
// LeadStage shows up without a front-end change.
|
|
|
977 |
List<String> stages = new ArrayList<>();
|
|
|
978 |
for (LeadStage st : LeadStage.HAPPY_PATH) {
|
|
|
979 |
stages.add(st.name());
|
|
|
980 |
}
|
|
|
981 |
res.put("stages", stages);
|
|
|
982 |
res.put("answerTypes", Arrays.asList("TEXT", "NUMBER", "YESNO", "CHOICE"));
|
|
|
983 |
return responseSender.ok(res);
|
|
|
984 |
}
|
|
|
985 |
|
|
|
986 |
/** Create or update a question. An id of 0 creates. */
|
|
|
987 |
@RequestMapping(value = "/lms/checklist/questions/save", method = RequestMethod.POST,
|
|
|
988 |
consumes = MediaType.APPLICATION_JSON_VALUE)
|
|
|
989 |
@ResponseBody
|
|
|
990 |
public ResponseEntity<?> saveQuestion(HttpServletRequest request, @RequestBody QuestionRequest body) {
|
|
|
991 |
if (body == null) {
|
|
|
992 |
return responseSender.badRequest("Nothing to save");
|
|
|
993 |
}
|
|
|
994 |
AuthUser me = currentUser(request);
|
|
|
995 |
if (me == null) {
|
|
|
996 |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
|
997 |
}
|
|
|
998 |
String prompt = trimToNull(body.prompt);
|
|
|
999 |
if (prompt == null) {
|
|
|
1000 |
return responseSender.badRequest("The question text is required");
|
|
|
1001 |
}
|
|
|
1002 |
if (prompt.length() > 500) {
|
|
|
1003 |
return responseSender.badRequest("Keep the question under 500 characters");
|
|
|
1004 |
}
|
|
|
1005 |
String type = trimToNull(body.answerType) == null ? "TEXT" : body.answerType.trim().toUpperCase();
|
|
|
1006 |
if (!Arrays.asList("TEXT", "NUMBER", "YESNO", "CHOICE").contains(type)) {
|
|
|
1007 |
return responseSender.badRequest("Unknown answer type: " + type);
|
|
|
1008 |
}
|
|
|
1009 |
String choices = trimToNull(body.choices);
|
|
|
1010 |
if ("CHOICE".equals(type) && choices == null) {
|
|
|
1011 |
return responseSender.badRequest("A choice question needs at least one option");
|
|
|
1012 |
}
|
|
|
1013 |
if (body.points != null && body.points < 0) {
|
|
|
1014 |
return responseSender.badRequest("Points cannot be negative");
|
|
|
1015 |
}
|
|
|
1016 |
// Reject unknown stage names rather than storing a filter that silently matches nothing.
|
|
|
1017 |
String stages = trimToNull(body.stages);
|
|
|
1018 |
if (stages != null) {
|
|
|
1019 |
for (String st : stages.split("\\|")) {
|
|
|
1020 |
if (st.trim().isEmpty()) {
|
|
|
1021 |
continue;
|
|
|
1022 |
}
|
|
|
1023 |
try {
|
|
|
1024 |
LeadStage.valueOf(st.trim().toUpperCase());
|
|
|
1025 |
} catch (IllegalArgumentException e) {
|
|
|
1026 |
return responseSender.badRequest("Unknown stage: " + st.trim());
|
|
|
1027 |
}
|
|
|
1028 |
}
|
|
|
1029 |
}
|
|
|
1030 |
|
|
|
1031 |
LeadCallQuestion q;
|
|
|
1032 |
boolean creating = body.id <= 0;
|
|
|
1033 |
if (creating) {
|
|
|
1034 |
q = new LeadCallQuestion();
|
|
|
1035 |
} else {
|
|
|
1036 |
q = leadCallChecklistRepository.selectQuestionById(body.id);
|
|
|
1037 |
if (q == null) {
|
|
|
1038 |
return responseSender.notFound("Question not found");
|
|
|
1039 |
}
|
|
|
1040 |
}
|
|
|
1041 |
q.setPrompt(latin1Safe(prompt));
|
|
|
1042 |
q.setAnswerType(type);
|
|
|
1043 |
q.setChoices("CHOICE".equals(type) ? latin1Safe(choices) : null);
|
|
|
1044 |
q.setRequired(Boolean.TRUE.equals(body.required));
|
|
|
1045 |
q.setActive(body.active == null || Boolean.TRUE.equals(body.active));
|
|
|
1046 |
q.setPoints(body.points == null ? 0 : body.points);
|
|
|
1047 |
q.setStages(stages == null ? null : stages.toUpperCase());
|
|
|
1048 |
q.setSortOrder(body.sortOrder == null ? 0 : body.sortOrder);
|
|
|
1049 |
leadCallChecklistRepository.saveQuestion(q);
|
|
|
1050 |
|
|
|
1051 |
LOGGER.info("Checklist question {} by auth {}: {}", creating ? "created" : "updated", me.getId(), q.getPrompt());
|
|
|
1052 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
1053 |
res.put("ok", true);
|
|
|
1054 |
res.put("id", q.getId());
|
|
|
1055 |
res.put("created", creating);
|
|
|
1056 |
return responseSender.ok(res);
|
|
|
1057 |
}
|
|
|
1058 |
|
|
|
1059 |
/**
|
|
|
1060 |
* Delete a question — but only one nobody has answered.
|
|
|
1061 |
*
|
|
|
1062 |
* <p>A question with answers is retired by clearing {@code active}, never deleted: the answers
|
|
|
1063 |
* reference it, and removing it would leave a lead's recorded history pointing at nothing.
|
|
|
1064 |
*/
|
|
|
1065 |
@RequestMapping(value = "/lms/checklist/questions/delete", method = RequestMethod.POST)
|
|
|
1066 |
@ResponseBody
|
|
|
1067 |
public ResponseEntity<?> deleteQuestion(HttpServletRequest request,
|
|
|
1068 |
@RequestParam(name = "id") int id) {
|
|
|
1069 |
AuthUser me = currentUser(request);
|
|
|
1070 |
if (me == null) {
|
|
|
1071 |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
|
1072 |
}
|
|
|
1073 |
LeadCallQuestion q = leadCallChecklistRepository.selectQuestionById(id);
|
|
|
1074 |
if (q == null) {
|
|
|
1075 |
return responseSender.notFound("Question not found");
|
|
|
1076 |
}
|
|
|
1077 |
long answers = leadCallChecklistRepository.countAnswersForQuestion(id);
|
|
|
1078 |
if (answers > 0) {
|
|
|
1079 |
return responseSender.badRequest("This question has " + answers + " recorded answer"
|
|
|
1080 |
+ (answers == 1 ? "" : "s") + " - switch it off instead of deleting it, so the "
|
|
|
1081 |
+ "answers keep their question");
|
|
|
1082 |
}
|
|
|
1083 |
leadCallChecklistRepository.deleteQuestion(q);
|
|
|
1084 |
LOGGER.info("Checklist question {} deleted by auth {}", id, me.getId());
|
|
|
1085 |
Map<String, Object> res = new LinkedHashMap<>();
|
|
|
1086 |
res.put("ok", true);
|
|
|
1087 |
return responseSender.ok(res);
|
|
|
1088 |
}
|
|
|
1089 |
|
|
|
1090 |
private Map<String, Object> questionJson(LeadCallQuestion q) {
|
|
|
1091 |
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
1092 |
m.put("id", q.getId());
|
|
|
1093 |
m.put("sortOrder", q.getSortOrder());
|
|
|
1094 |
m.put("prompt", q.getPrompt());
|
|
|
1095 |
m.put("answerType", q.getAnswerType());
|
|
|
1096 |
m.put("choices", q.getChoices());
|
|
|
1097 |
m.put("required", q.isRequired());
|
|
|
1098 |
m.put("active", q.isActive());
|
|
|
1099 |
m.put("points", q.getPoints());
|
|
|
1100 |
m.put("stages", q.getStages());
|
|
|
1101 |
m.put("answerCount", leadCallChecklistRepository.countAnswersForQuestion(q.getId()));
|
|
|
1102 |
return m;
|
|
|
1103 |
}
|
|
|
1104 |
|
|
|
1105 |
/** Payload for {@link #saveQuestion}. */
|
|
|
1106 |
public static class QuestionRequest {
|
|
|
1107 |
public int id;
|
|
|
1108 |
public String prompt;
|
|
|
1109 |
public String answerType;
|
|
|
1110 |
public String choices;
|
|
|
1111 |
public Boolean required;
|
|
|
1112 |
public Boolean active;
|
|
|
1113 |
public Integer points;
|
|
|
1114 |
public String stages;
|
|
|
1115 |
public Integer sortOrder;
|
|
|
1116 |
}
|
|
|
1117 |
|
|
|
1118 |
/** Payload for {@link #saveChecklist}. */
|
|
|
1119 |
public static class ChecklistRequest {
|
|
|
1120 |
public int leadId;
|
|
|
1121 |
public Integer leadCallId;
|
|
|
1122 |
public List<ChecklistAnswer> answers;
|
|
|
1123 |
}
|
|
|
1124 |
|
|
|
1125 |
/** One answer in that payload. */
|
|
|
1126 |
public static class ChecklistAnswer {
|
|
|
1127 |
public int questionId;
|
|
|
1128 |
public String answer;
|
|
|
1129 |
}
|
|
|
1130 |
|
|
|
1131 |
/**
|
| 37651 |
vikas |
1132 |
* Region → owning BM/RSM, resolved live from {@code cs.position}. Drives the Create-Lead
|
|
|
1133 |
* assignment preview and the dashboard's routing table; {@code HOLD} means the region has no
|
|
|
1134 |
* active owner and a lead created against it would wait in the HOLD queue.
|
|
|
1135 |
*/
|
|
|
1136 |
@RequestMapping(value = "/lms/resolve-region", method = RequestMethod.GET)
|
|
|
1137 |
@ResponseBody
|
|
|
1138 |
public ResponseEntity<?> resolveRegion(@RequestParam(name = "regionId", required = false) Integer regionId) {
|
|
|
1139 |
LmsAssignmentService.Assignment assignment = lmsAssignmentService.resolve(regionId);
|
|
|
1140 |
Map<String, Object> out = new HashMap<>();
|
|
|
1141 |
out.put("regionId", assignment.regionId);
|
|
|
1142 |
out.put("regionCode", assignment.regionCode);
|
|
|
1143 |
out.put("assignmentStatus", assignment.assignmentStatus);
|
|
|
1144 |
out.put("bmId", assignment.bm != null ? assignment.bm.getId() : null);
|
|
|
1145 |
out.put("bmName", assignment.bm != null ? assignment.bm.getFullName() : null);
|
|
|
1146 |
return responseSender.ok(out);
|
|
|
1147 |
}
|
|
|
1148 |
|
|
|
1149 |
// ---- Stage rules ------------------------------------------------------------------------
|
|
|
1150 |
|
|
|
1151 |
/**
|
|
|
1152 |
* Stage effect of each disposition (SOP §12.2). Only INTERESTED moves the lead forward; the
|
|
|
1153 |
* negative outcomes are terminal, and NOT_REACHABLE drops the lead once the retry budget is
|
|
|
1154 |
* spent. Anything else just records that contact happened.
|
|
|
1155 |
*/
|
|
|
1156 |
private void applyDispositionStage(Lead lead, LeadDisposition disposition, DispositionRequest body) {
|
|
|
1157 |
switch (disposition) {
|
|
|
1158 |
case INTERESTED:
|
|
|
1159 |
if (body.value != null && body.value > 0) {
|
|
|
1160 |
lead.setPotential(body.value);
|
|
|
1161 |
}
|
|
|
1162 |
advanceIfForward(lead, LeadStage.QUALIFIED);
|
|
|
1163 |
break;
|
|
|
1164 |
case NOT_INTERESTED:
|
|
|
1165 |
case DO_NOT_CALL:
|
|
|
1166 |
applyStage(lead, LeadStage.NOT_INTERESTED);
|
|
|
1167 |
break;
|
|
|
1168 |
case WRONG_NUMBER:
|
|
|
1169 |
// A corrected number keeps the lead alive at its current stage — the retailer still
|
|
|
1170 |
// has not been spoken to, so nothing advances. A blank one closes the lead.
|
|
|
1171 |
String corrected = digitsOnly(body.correctedNumber);
|
|
|
1172 |
if (corrected != null && corrected.length() == 10) {
|
|
|
1173 |
lead.setLeadMobile(corrected);
|
|
|
1174 |
lead.setUpdatedTimestamp(LocalDateTime.now());
|
|
|
1175 |
} else {
|
|
|
1176 |
applyStage(lead, LeadStage.DROPPED);
|
|
|
1177 |
}
|
|
|
1178 |
break;
|
|
|
1179 |
case NOT_REACHABLE:
|
|
|
1180 |
int tries = (lead.getUnreachableCount() == null ? 0 : lead.getUnreachableCount()) + 1;
|
|
|
1181 |
lead.setUnreachableCount(tries);
|
|
|
1182 |
if (tries >= LmsAssignmentService.MAX_UNREACHABLE) {
|
|
|
1183 |
applyStage(lead, LeadStage.DROPPED);
|
|
|
1184 |
}
|
|
|
1185 |
break;
|
|
|
1186 |
case CALLBACK:
|
|
|
1187 |
case FOLLOW_UP:
|
|
|
1188 |
default:
|
|
|
1189 |
advanceIfForward(lead, LeadStage.CONTACTED);
|
|
|
1190 |
break;
|
|
|
1191 |
}
|
|
|
1192 |
}
|
|
|
1193 |
|
|
|
1194 |
/** Did the retailer actually get spoken to? Only those outcomes may close the first-contact SLA. */
|
|
|
1195 |
private boolean countsAsContact(LeadDisposition disposition) {
|
|
|
1196 |
return disposition != LeadDisposition.NOT_REACHABLE && disposition != LeadDisposition.WRONG_NUMBER;
|
|
|
1197 |
}
|
|
|
1198 |
|
|
|
1199 |
/** Set stage + keep the legacy status column in lockstep. Every stage write goes through here. */
|
|
|
1200 |
private void applyStage(Lead lead, LeadStage stage) {
|
|
|
1201 |
lead.setStage(stage);
|
|
|
1202 |
lead.setStatus(stage.toLegacyStatus());
|
|
|
1203 |
lead.setUpdatedTimestamp(LocalDateTime.now());
|
|
|
1204 |
}
|
|
|
1205 |
|
|
|
1206 |
/** Move to {@code stage} only if that is a forward move — a later call never rewinds the lead. */
|
|
|
1207 |
private void advanceIfForward(Lead lead, LeadStage stage) {
|
|
|
1208 |
LeadStage current = lead.getEffectiveStage();
|
|
|
1209 |
if (current == stage || current.canAdvanceTo(stage)) {
|
|
|
1210 |
applyStage(lead, stage);
|
|
|
1211 |
} else {
|
|
|
1212 |
lead.setUpdatedTimestamp(LocalDateTime.now());
|
|
|
1213 |
}
|
|
|
1214 |
}
|
|
|
1215 |
|
|
|
1216 |
// ---- Helpers ----------------------------------------------------------------------------
|
|
|
1217 |
|
|
|
1218 |
private LeadActivity appendTrail(int leadId, AuthUser actor, String remark, CommunicationType type,
|
|
|
1219 |
LocalDateTime scheduled) {
|
|
|
1220 |
return appendTrail(leadId, actor, remark, type, scheduled, null);
|
|
|
1221 |
}
|
|
|
1222 |
|
|
|
1223 |
/** As above, additionally linking the trail entry to the call that produced it. */
|
|
|
1224 |
private LeadActivity appendTrail(int leadId, AuthUser actor, String remark, CommunicationType type,
|
|
|
1225 |
LocalDateTime scheduled, Integer leadCallId) {
|
|
|
1226 |
LeadActivity activity = new LeadActivity();
|
|
|
1227 |
activity.setLeadId(leadId);
|
|
|
1228 |
activity.setRemark(remark);
|
|
|
1229 |
activity.setAuthId(actor != null ? actor.getId() : 0);
|
|
|
1230 |
activity.setCommunicationType(type);
|
|
|
1231 |
activity.setSchelduleTimestamp(scheduled);
|
|
|
1232 |
activity.setLeadCallId(leadCallId);
|
|
|
1233 |
activity.setCreatedTimestamp(LocalDateTime.now());
|
|
|
1234 |
leadActivityRepository.persist(activity);
|
|
|
1235 |
return activity;
|
|
|
1236 |
}
|
|
|
1237 |
|
|
|
1238 |
/** Human-readable trail line for a disposition, including the stage move it caused. */
|
|
|
1239 |
private String dispositionRemark(LeadDisposition disposition, LeadStage before, Lead lead,
|
|
|
1240 |
DispositionRequest body) {
|
|
|
1241 |
StringBuilder sb = new StringBuilder(pretty(disposition.name()));
|
|
|
1242 |
if (body.subReason != null && !body.subReason.trim().isEmpty()) {
|
|
|
1243 |
sb.append(" · ").append(body.subReason.trim());
|
|
|
1244 |
}
|
|
|
1245 |
if (disposition == LeadDisposition.NOT_REACHABLE) {
|
|
|
1246 |
sb.append(" · attempt ").append(lead.getUnreachableCount());
|
|
|
1247 |
if (body.retrySchedule != null && !body.retrySchedule.trim().isEmpty()) {
|
|
|
1248 |
sb.append(", retry ").append(body.retrySchedule.trim());
|
|
|
1249 |
}
|
|
|
1250 |
}
|
|
|
1251 |
LeadStage after = lead.getEffectiveStage();
|
|
|
1252 |
if (after != before) {
|
| 37692 |
vikas |
1253 |
sb.append(" · stage ").append(pretty(before)).append(" -> ").append(pretty(after));
|
| 37651 |
vikas |
1254 |
}
|
|
|
1255 |
if (body.note != null && !body.note.trim().isEmpty()) {
|
| 37692 |
vikas |
1256 |
sb.append(" - ").append(body.note.trim());
|
| 37651 |
vikas |
1257 |
}
|
|
|
1258 |
return sb.toString();
|
|
|
1259 |
}
|
|
|
1260 |
|
|
|
1261 |
/** What the caller needs to refresh its row without re-reading the whole record. */
|
|
|
1262 |
private Map<String, Object> stateOf(Lead lead) {
|
|
|
1263 |
LeadStage stage = lead.getEffectiveStage();
|
|
|
1264 |
Map<String, Object> out = new HashMap<>();
|
|
|
1265 |
out.put("leadId", lead.getId());
|
|
|
1266 |
out.put("stage", stage.name());
|
|
|
1267 |
out.put("stageLabel", pretty(stage));
|
|
|
1268 |
out.put("terminal", isTerminal(stage));
|
|
|
1269 |
out.put("slaState", lmsAssignmentService.slaState(lead));
|
|
|
1270 |
return out;
|
|
|
1271 |
}
|
|
|
1272 |
|
|
|
1273 |
private Map<Integer, AuthUser> actorsOf(List<LeadActivity> trail) {
|
|
|
1274 |
Set<Integer> ids = new HashSet<>();
|
|
|
1275 |
for (LeadActivity a : trail) {
|
|
|
1276 |
if (a.getAuthId() > 0) {
|
|
|
1277 |
ids.add(a.getAuthId());
|
|
|
1278 |
}
|
|
|
1279 |
}
|
|
|
1280 |
Map<Integer, AuthUser> actors = new HashMap<>();
|
|
|
1281 |
if (!ids.isEmpty()) {
|
|
|
1282 |
for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ids))) {
|
|
|
1283 |
actors.put(u.getId(), u);
|
|
|
1284 |
}
|
|
|
1285 |
}
|
|
|
1286 |
return actors;
|
|
|
1287 |
}
|
|
|
1288 |
|
|
|
1289 |
private AuthUser currentUser(HttpServletRequest request) {
|
|
|
1290 |
try {
|
|
|
1291 |
LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
|
|
|
1292 |
if (loginDetails != null && loginDetails.getEmailId() != null) {
|
|
|
1293 |
return authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
|
|
|
1294 |
}
|
|
|
1295 |
} catch (Exception e) {
|
|
|
1296 |
LOGGER.warn("Could not resolve the acting user for an LMS mutation", e);
|
|
|
1297 |
}
|
|
|
1298 |
return null;
|
|
|
1299 |
}
|
|
|
1300 |
|
|
|
1301 |
private int happyPathIndex(LeadStage stage) {
|
|
|
1302 |
for (int i = 0; i < LeadStage.HAPPY_PATH.length; i++) {
|
|
|
1303 |
if (LeadStage.HAPPY_PATH[i] == stage) {
|
|
|
1304 |
return i;
|
|
|
1305 |
}
|
|
|
1306 |
}
|
|
|
1307 |
return -1;
|
|
|
1308 |
}
|
|
|
1309 |
|
|
|
1310 |
private boolean isTerminal(LeadStage stage) {
|
|
|
1311 |
return stage == LeadStage.NOT_INTERESTED || stage == LeadStage.DROPPED;
|
|
|
1312 |
}
|
|
|
1313 |
|
|
|
1314 |
private String pretty(LeadStage stage) {
|
| 37692 |
vikas |
1315 |
return stage == null ? "-" : pretty(stage.name());
|
| 37651 |
vikas |
1316 |
}
|
|
|
1317 |
|
|
|
1318 |
private String pretty(String enumName) {
|
|
|
1319 |
return enumName.replace('_', ' ');
|
|
|
1320 |
}
|
|
|
1321 |
|
|
|
1322 |
private String trimToNull(String s) {
|
|
|
1323 |
return (s == null || s.trim().isEmpty()) ? null : s.trim();
|
|
|
1324 |
}
|
|
|
1325 |
|
|
|
1326 |
private String digitsOnly(String s) {
|
|
|
1327 |
return s == null ? null : s.replaceAll("\\D", "");
|
|
|
1328 |
}
|
|
|
1329 |
|
|
|
1330 |
/** Accepts the {@code datetime-local} value the modal posts ({@code 2026-08-27T14:30}); null-safe. */
|
|
|
1331 |
private LocalDateTime parseLocal(String s) {
|
|
|
1332 |
if (s == null || s.trim().isEmpty()) {
|
|
|
1333 |
return null;
|
|
|
1334 |
}
|
|
|
1335 |
try {
|
|
|
1336 |
return LocalDateTime.parse(s.trim());
|
|
|
1337 |
} catch (Exception e) {
|
|
|
1338 |
LOGGER.warn("Ignoring unparseable LMS schedule timestamp: {}", s);
|
|
|
1339 |
return null;
|
|
|
1340 |
}
|
|
|
1341 |
}
|
|
|
1342 |
|
|
|
1343 |
/** JSON body of the disposition modal — one flat shape, sub-fields set per disposition. */
|
|
|
1344 |
public static class DispositionRequest {
|
|
|
1345 |
public int leadId;
|
|
|
1346 |
public String disposition;
|
|
|
1347 |
public String note;
|
|
|
1348 |
/** The {@code user.lead_call} row this outcome belongs to, supplied by the dialer. */
|
|
|
1349 |
public Integer leadCallId;
|
|
|
1350 |
/**
|
|
|
1351 |
* Interim: the free-text recording URL agents paste today. Superseded by {@code leadCallId}
|
|
|
1352 |
* once the dialer captures recordings automatically — kept until then so removing the box
|
|
|
1353 |
* does not leave leads with no recording path at all.
|
|
|
1354 |
*/
|
|
|
1355 |
public String recordingUrl;
|
|
|
1356 |
public Double value; // INTERESTED
|
|
|
1357 |
public String callbackAt; // CALLBACK
|
|
|
1358 |
public String retrySchedule; // NOT_REACHABLE
|
|
|
1359 |
public String correctedNumber;// WRONG_NUMBER
|
|
|
1360 |
public String followUpType; // FOLLOW_UP — CALL | MEETING
|
|
|
1361 |
public String followUpAt; // FOLLOW_UP
|
|
|
1362 |
public String subReason; // NOT_INTERESTED
|
|
|
1363 |
}
|
|
|
1364 |
|
|
|
1365 |
/**
|
|
|
1366 |
* Create a lead from the LMS dashboard.
|
|
|
1367 |
*
|
|
|
1368 |
* <p><b>Deliberately not {@code /createLead}.</b> That endpoint is shared with the legacy Leads
|
|
|
1369 |
* screen and must keep behaving exactly as it does. It also silently ignores the {@code regionId}
|
|
|
1370 |
* and {@code creationPath} this dashboard has always sent — which is why no lead has ever had a
|
|
|
1371 |
* stage, an LMS code or an SLA clock, while the UI cheerfully toasted "auto-assigned · SLA
|
|
|
1372 |
* started". This endpoint is what makes that message true.
|
|
|
1373 |
*
|
|
|
1374 |
* <p>Asks for far less than the legacy form: no store photos, no counter size, no brand-wise
|
|
|
1375 |
* values, no free-text address. The store-board photo and lat/lng arrive through the geo capture
|
|
|
1376 |
* link (auto-generated below), and location is confirmed by that link or by manual verification —
|
|
|
1377 |
* so an agent on a first call is no longer made to invent shop-audit data.
|
|
|
1378 |
*/
|
|
|
1379 |
@RequestMapping(value = "/lms/createLead", method = RequestMethod.POST,
|
|
|
1380 |
consumes = MediaType.APPLICATION_JSON_VALUE)
|
|
|
1381 |
@ResponseBody
|
|
|
1382 |
public ResponseEntity<?> createLead(HttpServletRequest request, @RequestBody CreateLeadRequest body) {
|
|
|
1383 |
if (body == null) {
|
|
|
1384 |
return responseSender.badRequest("Nothing to create");
|
|
|
1385 |
}
|
| 37692 |
vikas |
1386 |
String name = latin1Safe(body.firstName == null ? "" : body.firstName.trim());
|
| 37651 |
vikas |
1387 |
if (name.isEmpty()) {
|
|
|
1388 |
return responseSender.badRequest("Retailer name is required");
|
|
|
1389 |
}
|
|
|
1390 |
String mobile = body.mobile == null ? "" : body.mobile.replaceAll("\\D", "");
|
|
|
1391 |
if (mobile.length() < 10) {
|
|
|
1392 |
return responseSender.badRequest("A valid 10-digit contact number is required");
|
|
|
1393 |
}
|
|
|
1394 |
mobile = mobile.substring(mobile.length() - 10);
|
|
|
1395 |
if (body.regionId == null || body.regionId <= 0) {
|
|
|
1396 |
return responseSender.badRequest("Pick a region — it drives auto-assignment");
|
|
|
1397 |
}
|
|
|
1398 |
|
|
|
1399 |
// Same rule the dialer uses: a number on the do-not-call register never becomes a lead.
|
|
|
1400 |
if (leadDndRepository.selectByMobile(mobile) != null) {
|
|
|
1401 |
return responseSender.badRequest("This number is on the do-not-call register.");
|
|
|
1402 |
}
|
|
|
1403 |
|
|
|
1404 |
Lead existing = leadRepository.selectByMobileNumber(mobile);
|
|
|
1405 |
if (existing != null) {
|
|
|
1406 |
return responseSender.badRequest("Lead #" + existing.getId() + " already exists for "
|
|
|
1407 |
+ mobile + ", created by " + existing.getCreatedBy());
|
|
|
1408 |
}
|
|
|
1409 |
|
|
|
1410 |
AuthUser me = currentUser(request);
|
|
|
1411 |
if (me == null) {
|
|
|
1412 |
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
|
1413 |
}
|
|
|
1414 |
|
|
|
1415 |
Lead lead = new Lead();
|
|
|
1416 |
// Split on the last space so "Jitu Katara" keeps a surname; user.lead.last_name is NOT NULL.
|
|
|
1417 |
int space = name.lastIndexOf(' ');
|
|
|
1418 |
lead.setFirstName(space > 0 ? name.substring(0, space) : name);
|
|
|
1419 |
lead.setLastName(space > 0 ? name.substring(space + 1) : "");
|
|
|
1420 |
lead.setLeadMobile(mobile);
|
|
|
1421 |
// address / city / state are NOT NULL but are no longer asked for: the geo link supplies the
|
|
|
1422 |
// real location. Coalesced rather than left to fail the insert.
|
|
|
1423 |
lead.setAddress("");
|
|
|
1424 |
lead.setCity("");
|
|
|
1425 |
lead.setState("");
|
| 37692 |
vikas |
1426 |
lead.setSource(latin1Safe(body.source == null || body.source.trim().isEmpty()
|
|
|
1427 |
? "LMS Dashboard" : body.source.trim()));
|
| 37651 |
vikas |
1428 |
lead.setCreatedTimestamp(LocalDateTime.now());
|
|
|
1429 |
lead.setUpdatedTimestamp(LocalDateTime.now());
|
|
|
1430 |
lead.setCreatedBy(me.getFirstName() + " " + me.getLastName());
|
|
|
1431 |
lead.setAuthId(me.getId());
|
|
|
1432 |
// The record screen reads the business name off user.lead.outlet_name. Until now it was only
|
|
|
1433 |
// written to lead_detail below — a call that throws for every lead created here, because the
|
|
|
1434 |
// legacy detail path demands store photos this form deliberately does not collect — so the
|
|
|
1435 |
// name the agent typed was silently dropped and the Business row rendered blank.
|
| 37692 |
vikas |
1436 |
lead.setOutLetName(latin1Safe(body.outletName == null ? "" : body.outletName.trim()));
|
| 37651 |
vikas |
1437 |
lead.setRegionId(body.regionId);
|
|
|
1438 |
if (body.potential != null && body.potential > 0) {
|
|
|
1439 |
lead.setPotential(body.potential);
|
|
|
1440 |
}
|
|
|
1441 |
// Path B is a field encounter, so the creator owns it; Path A goes to the region's BM.
|
|
|
1442 |
if ("B".equalsIgnoreCase(body.creationPath)) {
|
|
|
1443 |
lead.setAssignTo(me.getId());
|
|
|
1444 |
}
|
|
|
1445 |
|
|
|
1446 |
// THE point of this endpoint: region -> owner -> stage -> 5hr SLA, per SOP 9.
|
|
|
1447 |
LmsAssignmentService.Assignment assignment = lmsAssignmentService.assign(lead, body.creationPath);
|
|
|
1448 |
leadRepository.persist(lead);
|
|
|
1449 |
|
|
|
1450 |
// lms_code needs the generated id, so it can only be stamped after the insert.
|
|
|
1451 |
lead.setLmsCode(lmsAssignmentService.generateLmsCode(lead));
|
|
|
1452 |
leadRepository.persist(lead);
|
|
|
1453 |
|
|
|
1454 |
boolean hasBrands = body.leadBrands != null && !body.leadBrands.isEmpty();
|
|
|
1455 |
if ((body.outletName != null && !body.outletName.trim().isEmpty()) || hasBrands) {
|
|
|
1456 |
try {
|
|
|
1457 |
LeadDetailModel detail = new LeadDetailModel();
|
|
|
1458 |
detail.setLeadId(lead.getId());
|
|
|
1459 |
detail.setOutletName(body.outletName == null ? "" : body.outletName.trim());
|
|
|
1460 |
if (hasBrands) {
|
|
|
1461 |
List<LeadBrandModel> brands = new ArrayList<>();
|
|
|
1462 |
for (BrandValue bv : body.leadBrands) {
|
|
|
1463 |
if (bv == null || bv.brand == null || bv.brand.trim().isEmpty() || bv.value == null
|
|
|
1464 |
|| bv.value <= 0) {
|
|
|
1465 |
// Only brands the retailer actually stocks. Persisting zeroes for the rest
|
|
|
1466 |
// is what made the legacy brand table useless for reporting.
|
|
|
1467 |
continue;
|
|
|
1468 |
}
|
|
|
1469 |
LeadBrandModel brand = new LeadBrandModel();
|
|
|
1470 |
brand.setBrand(bv.brand.trim());
|
|
|
1471 |
brand.setValue(bv.value.intValue());
|
|
|
1472 |
brands.add(brand);
|
|
|
1473 |
}
|
|
|
1474 |
detail.setLeadBrands(brands);
|
|
|
1475 |
}
|
|
|
1476 |
leadRepository.persistLeadDetail(detail, me);
|
|
|
1477 |
} catch (Exception e) {
|
|
|
1478 |
// Shop name and brand split are not worth losing an otherwise-good lead over.
|
|
|
1479 |
LOGGER.warn("Could not save the lead detail for lead {}", lead.getId(), e);
|
|
|
1480 |
}
|
|
|
1481 |
}
|
|
|
1482 |
|
|
|
1483 |
StringBuilder created = new StringBuilder("Lead created from the LMS dashboard");
|
|
|
1484 |
if (hasBrands) {
|
|
|
1485 |
created.append(" · brand-wise value: ");
|
|
|
1486 |
boolean first = true;
|
|
|
1487 |
for (BrandValue bv : body.leadBrands) {
|
|
|
1488 |
if (bv == null || bv.brand == null || bv.value == null || bv.value <= 0) {
|
|
|
1489 |
continue;
|
|
|
1490 |
}
|
|
|
1491 |
if (!first) {
|
|
|
1492 |
created.append(", ");
|
|
|
1493 |
}
|
|
|
1494 |
created.append(bv.brand.trim()).append(' ').append(bv.value.longValue());
|
|
|
1495 |
first = false;
|
|
|
1496 |
}
|
|
|
1497 |
}
|
| 37692 |
vikas |
1498 |
trail(lead.getId(), me.getId(), latin1Safe(created.toString()
|
| 37651 |
vikas |
1499 |
+ (assignment != null && "HOLD".equals(assignment.assignmentStatus)
|
| 37692 |
vikas |
1500 |
? " - region has no active BM/RSM, parked in the HOLD queue" : "")));
|
| 37651 |
vikas |
1501 |
|
|
|
1502 |
// Auto-generate the geo capture link so the agent can send it during the same call.
|
|
|
1503 |
String geoLink = buildGeoCaptureLink(lead.getId());
|
|
|
1504 |
if (geoLink != null) {
|
|
|
1505 |
trail(lead.getId(), me.getId(), "Geolocation link generated for lead");
|
|
|
1506 |
}
|
|
|
1507 |
|
|
|
1508 |
Map<String, Object> out = new LinkedHashMap<>();
|
|
|
1509 |
out.put("ok", true);
|
|
|
1510 |
out.put("leadId", lead.getId());
|
|
|
1511 |
out.put("lmsCode", lead.getLmsCode());
|
|
|
1512 |
out.put("assignmentStatus", lead.getAssignmentStatus());
|
|
|
1513 |
out.put("ownerName", assignment != null && assignment.bm != null
|
|
|
1514 |
? assignment.bm.getFirstName() + " " + assignment.bm.getLastName() : null);
|
|
|
1515 |
out.put("geoLink", geoLink);
|
|
|
1516 |
LOGGER.info("LMS lead {} created ({}) by auth {} — region {} status {}",
|
|
|
1517 |
lead.getId(), lead.getLmsCode(), me.getId(), lead.getRegionCode(), lead.getAssignmentStatus());
|
|
|
1518 |
return responseSender.ok(out);
|
|
|
1519 |
}
|
|
|
1520 |
|
| 37692 |
vikas |
1521 |
/**
|
|
|
1522 |
* Business value on the lakh scale.
|
|
|
1523 |
*
|
|
|
1524 |
* <p>Two conventions live in {@code user.lead.potential}: the forms capture LAKHS (rows hold
|
|
|
1525 |
* 1–99) but about 1,355 older rows were entered in RUPEES (1,000 upwards). No row sits
|
|
|
1526 |
* between 100 and 999, so that gap is a safe separator — anything from {@value #LAKH_CUTOFF} up
|
|
|
1527 |
* is read as rupees and brought onto the lakh scale. Read-side only: no stored value is
|
|
|
1528 |
* rewritten, so a row keeps whatever it holds until someone edits it.
|
|
|
1529 |
*/
|
|
|
1530 |
private static final double LAKH_CUTOFF = 1000d;
|
|
|
1531 |
|
|
|
1532 |
private double toLakh(double v) {
|
|
|
1533 |
return v >= LAKH_CUTOFF ? v / 100000d : v;
|
|
|
1534 |
}
|
|
|
1535 |
|
|
|
1536 |
/** "12L" / "5.2L" / "0.01L" — a sub-lakh value needs two decimals or it prints as 0L. */
|
|
|
1537 |
private String lakhLabel(double potential) {
|
|
|
1538 |
if (potential <= 0) {
|
|
|
1539 |
return null;
|
| 37651 |
vikas |
1540 |
}
|
| 37692 |
vikas |
1541 |
double l = toLakh(potential);
|
|
|
1542 |
String n = (l < 1) ? trimZeros(String.format("%.2f", l)) : trimZeros(String.format("%.1f", l));
|
|
|
1543 |
return n + "L";
|
| 37651 |
vikas |
1544 |
}
|
|
|
1545 |
|
| 37692 |
vikas |
1546 |
/** The same number, unsuffixed, for the edit form — so saving cannot re-store rupees. */
|
|
|
1547 |
private String lakhInput(double potential) {
|
|
|
1548 |
if (potential <= 0) {
|
|
|
1549 |
return "";
|
|
|
1550 |
}
|
|
|
1551 |
double l = toLakh(potential);
|
|
|
1552 |
return (l < 1) ? trimZeros(String.format("%.2f", l)) : trimZeros(String.format("%.1f", l));
|
|
|
1553 |
}
|
|
|
1554 |
|
|
|
1555 |
private String trimZeros(String s) {
|
|
|
1556 |
return s.contains(".") ? s.replaceAll("0+$", "").replaceAll("\\.$", "") : s;
|
|
|
1557 |
}
|
|
|
1558 |
|
| 37651 |
vikas |
1559 |
/**
|
| 37692 |
vikas |
1560 |
* Append a trail entry.
|
|
|
1561 |
*
|
|
|
1562 |
* <p>Deliberately NOT caught. It used to swallow the exception on the grounds that "a lost note
|
|
|
1563 |
* must not fail the lead", but inside a {@code @Transactional} method that is worse than
|
|
|
1564 |
* useless: the failed entity stays in the Hibernate session with a null id, the request carries
|
|
|
1565 |
* on, and the commit-time flush dies with "null id in LeadActivity entry" — an error that names
|
|
|
1566 |
* neither the lead nor the real cause. An edit that cannot be recorded should fail loudly and
|
|
|
1567 |
* roll back; SOP §6 wants the trail append-only, and a change with no trail entry is worse than
|
|
|
1568 |
* a change that did not happen.
|
|
|
1569 |
*/
|
|
|
1570 |
private void trail(int leadId, int authId, String remark) {
|
|
|
1571 |
LeadActivity activity = new LeadActivity();
|
|
|
1572 |
activity.setLeadId(leadId);
|
|
|
1573 |
activity.setAuthId(authId);
|
|
|
1574 |
activity.setRemark(remark);
|
|
|
1575 |
activity.setCreatedTimestamp(LocalDateTime.now());
|
|
|
1576 |
leadActivityRepository.persist(activity);
|
|
|
1577 |
}
|
|
|
1578 |
|
|
|
1579 |
/**
|
| 37651 |
vikas |
1580 |
* {base}/lead-geo/{leadId} — the same URL the Leads screen's Generate Link button produces.
|
|
|
1581 |
* Null when the base URL is unconfigured, which must not stop a lead being created.
|
|
|
1582 |
*/
|
|
|
1583 |
private String buildGeoCaptureLink(int leadId) {
|
|
|
1584 |
String base = leadGeoPublicBaseUrl;
|
|
|
1585 |
if (base == null || base.trim().isEmpty()) {
|
|
|
1586 |
return null;
|
|
|
1587 |
}
|
|
|
1588 |
base = base.trim();
|
|
|
1589 |
while (base.endsWith("/")) {
|
|
|
1590 |
base = base.substring(0, base.length() - 1);
|
|
|
1591 |
}
|
|
|
1592 |
return base + "/lead-geo/" + leadId;
|
|
|
1593 |
}
|
|
|
1594 |
|
|
|
1595 |
/** Payload for {@link #createLead}. */
|
|
|
1596 |
public static class CreateLeadRequest {
|
|
|
1597 |
public String firstName; // retailer contact name, split into first/last
|
|
|
1598 |
public String mobile;
|
|
|
1599 |
public String outletName; // business / shop name
|
|
|
1600 |
public String source;
|
|
|
1601 |
public Integer regionId; // drives auto-assignment
|
|
|
1602 |
public String creationPath; // A = BGC outbound, B = field encounter
|
|
|
1603 |
public Double potential; // monthly business value — the sum of leadBrands
|
|
|
1604 |
/** Per-brand monthly business. What a BM actually needs to size the counter. */
|
|
|
1605 |
public List<BrandValue> leadBrands;
|
|
|
1606 |
}
|
|
|
1607 |
|
|
|
1608 |
/** One brand's monthly business value. */
|
|
|
1609 |
public static class BrandValue {
|
|
|
1610 |
public String brand;
|
|
|
1611 |
public Double value;
|
|
|
1612 |
}
|
|
|
1613 |
}
|