Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
36618 ranu 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.google.gson.Gson;
4
import com.google.gson.reflect.TypeToken;
5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.model.CustomRetailer;
36763 ranu 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
36618 ranu 8
import com.spice.profitmandi.common.web.util.ResponseSender;
9
import com.spice.profitmandi.dao.entity.auth.AuthUser;
10
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
11
import com.spice.profitmandi.dao.entity.logistics.PublicHolidays;
36644 ranu 12
import com.spice.profitmandi.dao.entity.user.*;
36618 ranu 13
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
37175 amit 14
import com.spice.profitmandi.dao.enumuration.dtr.AgendaSource;
15
import com.spice.profitmandi.dao.enumuration.dtr.AgendaType;
36618 ranu 16
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
17
import com.spice.profitmandi.dao.repository.cs.CsService;
18
import com.spice.profitmandi.dao.repository.dtr.*;
19
import com.spice.profitmandi.dao.repository.logistics.PublicHolidaysRepository;
20
import com.spice.profitmandi.service.user.RetailerService;
21
import com.spice.profitmandi.web.model.LoginDetails;
22
import com.spice.profitmandi.web.util.CookiesProcessor;
23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.http.ResponseEntity;
27
import org.springframework.stereotype.Controller;
28
import org.springframework.transaction.annotation.Transactional;
29
import org.springframework.ui.Model;
30
import org.springframework.web.bind.annotation.GetMapping;
31
import org.springframework.web.bind.annotation.PostMapping;
32
import org.springframework.web.bind.annotation.RequestParam;
33
 
34
import javax.servlet.http.HttpServletRequest;
35
import java.lang.reflect.Type;
36
import java.time.DayOfWeek;
37
import java.time.LocalDate;
38
import java.time.LocalDateTime;
39
import java.time.YearMonth;
40
import java.time.format.DateTimeFormatter;
41
import java.util.*;
42
import java.util.stream.Collectors;
43
 
44
@Controller
45
@Transactional(rollbackFor = Throwable.class)
46
public class BeatPlanController {
47
	private static final Logger LOGGER = LogManager.getLogger(BeatPlanController.class);
48
	private static final String[] BEAT_COLORS = {
49
			"#3498DB", "#E74C3C", "#2ECC71", "#9B59B6", "#F39C12",
50
			"#1ABC9C", "#E67E22", "#34495E", "#16A085", "#C0392B"
51
	};
52
	@Autowired
53
	private CsService csService;
54
	@Autowired
55
	private AuthRepository authRepository;
36686 ranu 56
	// Emails that bypass hierarchy and role gates — single source of truth.
57
	private static final Set<String> SUPER_ADMIN_EMAILS = new HashSet<>(Arrays.asList(
58
			"tarun.verma@smartdukaan.com"
59
	));
36618 ranu 60
	@Autowired
36686 ranu 61
	private com.spice.profitmandi.service.AuthService authService;
36618 ranu 62
	@Autowired
36686 ranu 63
	private com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
64
	@Autowired
36618 ranu 65
	private RetailerService retailerService;
66
	@Autowired
36644 ranu 67
	private BeatRepository beatRepository;
36618 ranu 68
	@Autowired
36644 ranu 69
	private BeatRouteRepository beatRouteRepository;
36618 ranu 70
	@Autowired
36644 ranu 71
	private BeatScheduleRepository beatScheduleRepository;
72
	@Autowired
73
	private LeadRouteRepository leadRouteRepository;
74
	@Autowired
36650 ranu 75
	private com.spice.profitmandi.dao.service.BeatPlanQueryService beatPlanQueryService;
76
	@Autowired
36618 ranu 77
	private AuthUserLocationRepository authUserLocationRepository;
78
	@Autowired
79
	private LeadRepository leadRepository;
80
	@Autowired
81
	private PublicHolidaysRepository publicHolidaysRepository;
82
	@Autowired
83
	private com.spice.profitmandi.service.GeocodingService geocodingService;
84
	@Autowired
85
	private CookiesProcessor cookiesProcessor;
86
	@Autowired
87
	private ResponseSender responseSender;
36686 ranu 88
	@Autowired
89
	private FofoStoreRepository fofoStoreRepository;
36811 ranu 90
	@Autowired
91
	private com.spice.profitmandi.dao.repository.logistics.CompanyOfficeRepository companyOfficeRepository;
37175 amit 92
	@Autowired
93
	private AgendaInstanceRepository agendaInstanceRepository;
94
	@Autowired
95
	private com.spice.profitmandi.service.AgendaInstanceService agendaInstanceService;
36618 ranu 96
 
97
	@GetMapping(value = "/beatPlan")
36686 ranu 98
	public String beatPlan(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
99
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
36618 ranu 100
		return "beat-plan";
101
	}
102
 
36650 ranu 103
	@Autowired
104
	private com.spice.profitmandi.dao.repository.dtr.LeadLiveLocationRepository leadLiveLocationRepositoryAuto;
36651 ranu 105
	@Autowired
106
	private com.spice.profitmandi.dao.repository.dtr.LeadActivityRepository leadActivityRepositoryAuto;
36663 ranu 107
	@Autowired
108
	private com.spice.profitmandi.dao.repository.dtr.UserRepository userRepositoryAuto;
109
	@Autowired
110
	private com.spice.profitmandi.common.web.client.RestClient restClientAuto;
111
	@Autowired
112
	private com.spice.profitmandi.dao.repository.auth.LocationTrackingRepository locationTrackingRepositoryAuto;
36740 ranu 113
	@Autowired
114
	private com.spice.profitmandi.dao.repository.dtr.BeatDeferredVisitRepository beatDeferredVisitRepository;
36650 ranu 115
 
36655 ranu 116
	private static Double parseDoubleOrNull(String s) {
117
		if (s == null || s.trim().isEmpty()) return null;
118
		try {
119
			return Double.parseDouble(s.trim());
120
		} catch (NumberFormatException e) {
121
			return null;
122
		}
123
	}
124
 
125
	private static double haversineKm(double lat1, double lng1, double lat2, double lng2) {
126
		double R = 6371;
127
		double dLat = Math.toRadians(lat2 - lat1);
128
		double dLng = Math.toRadians(lng2 - lng1);
129
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
130
				+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
131
				* Math.sin(dLng / 2) * Math.sin(dLng / 2);
132
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
133
		return R * c;
134
	}
135
 
37060 vikas 136
	// Reorder a day's bulk-upload stops in place into a greedy nearest-neighbor
137
	// route from the given start point (the beat's start location). Codes with no
138
	// known coordinates (offices, or partners missing lat/lng) are parked at the
139
	// end preserving their relative order rather than dropped. Sequence is taken
140
	// from the resulting list position by the caller.
141
	private static void sortPartnersByNearestNeighbor(List<BulkPartner> partners, Double startLat, Double startLng, Map<String, double[]> codeToLatLng) {
142
		if (partners == null || partners.size() < 2) return;
143
 
144
		List<BulkPartner> routable = new ArrayList<>();
145
		List<BulkPartner> parked = new ArrayList<>();
146
		for (BulkPartner p : partners) {
147
			if (codeToLatLng.containsKey(p.code)) routable.add(p);
148
			else parked.add(p);
149
		}
150
 
151
		List<BulkPartner> ordered = new ArrayList<>();
152
		double curLat, curLng;
153
		if (startLat != null && startLng != null) {
154
			curLat = startLat;
155
			curLng = startLng;
156
		} else if (!routable.isEmpty()) {
157
			BulkPartner first = routable.remove(0);
158
			ordered.add(first);
159
			double[] c = codeToLatLng.get(first.code);
160
			curLat = c[0];
161
			curLng = c[1];
162
		} else {
163
			return;
164
		}
165
 
166
		while (!routable.isEmpty()) {
167
			int bestIdx = 0;
168
			double bestD = Double.MAX_VALUE;
169
			for (int i = 0; i < routable.size(); i++) {
170
				double[] c = codeToLatLng.get(routable.get(i).code);
171
				double d = haversineKm(curLat, curLng, c[0], c[1]);
172
				if (d < bestD) {
173
					bestD = d;
174
					bestIdx = i;
175
				}
176
			}
177
			BulkPartner next = routable.remove(bestIdx);
178
			ordered.add(next);
179
			double[] c = codeToLatLng.get(next.code);
180
			curLat = c[0];
181
			curLng = c[1];
182
		}
183
 
184
		partners.clear();
185
		partners.addAll(ordered);
186
		partners.addAll(parked);
187
	}
188
 
36711 ranu 189
    // Mirrors the JS recalcDay() formula. Used by schedule/repeat endpoints
190
    // which create fresh BeatSchedule rows — they need to fill totals from the
191
    // existing beat_route table, not from anything the client posted.
192
    // Returns {totalKm, totalMins}.
193
    private double[] computeDayTotals(int beatId, int dayNumber, String endAction) {
194
        Beat beat = beatRepository.selectById(beatId);
195
        if (beat == null) return new double[]{0d, 0d};
196
 
197
        List<BeatRoute> dayRoutes = beatRouteRepository.selectByBeatId(beatId).stream()
198
                .filter(r -> r.getDayNumber() == dayNumber)
199
                .sorted(java.util.Comparator.comparingInt(BeatRoute::getSequenceOrder))
200
                .collect(Collectors.toList());
201
        if (dayRoutes.isEmpty()) return new double[]{0d, 0d};
202
 
203
        List<Integer> fofoIds = dayRoutes.stream().map(BeatRoute::getFofoId).distinct().collect(Collectors.toList());
204
        Map<Integer, FofoStore> storeMap = new HashMap<>();
205
        try {
206
            for (FofoStore fs : fofoStoreRepository.selectByRetailerIds(fofoIds)) {
207
                storeMap.put(fs.getId(), fs);
208
            }
209
        } catch (Exception ignored) { /* fall through with empty map */ }
210
 
211
        double ROAD_FACTOR = 1.3;
212
        double AVG_SPEED = 30.0; // km/h
213
        int VISIT_MINS = 30;
214
 
215
        Double prevLat = parseDoubleOrNull(beat.getStartLatitude());
216
        Double prevLng = parseDoubleOrNull(beat.getStartLongitude());
217
 
218
        double totalKm = 0d;
219
        for (BeatRoute r : dayRoutes) {
220
            FofoStore fs = storeMap.get(r.getFofoId());
221
            if (fs == null) continue;
222
            Double curLat = parseDoubleOrNull(fs.getLatitude());
223
            Double curLng = parseDoubleOrNull(fs.getLongitude());
224
            if (prevLat != null && prevLng != null && curLat != null && curLng != null) {
225
                totalKm += haversineKm(prevLat, prevLng, curLat, curLng) * ROAD_FACTOR;
226
            }
227
            if (curLat != null && curLng != null) {
228
                prevLat = curLat;
229
                prevLng = curLng;
230
            }
231
        }
232
 
233
        // Return-home leg only when end_action='HOME'
234
        if ("HOME".equalsIgnoreCase(endAction)) {
235
            Double homeLat = parseDoubleOrNull(beat.getStartLatitude());
236
            Double homeLng = parseDoubleOrNull(beat.getStartLongitude());
237
            if (prevLat != null && prevLng != null && homeLat != null && homeLng != null) {
238
                totalKm += haversineKm(prevLat, prevLng, homeLat, homeLng) * ROAD_FACTOR;
239
            }
240
        }
241
 
242
        double totalMins = (totalKm / AVG_SPEED) * 60.0 + dayRoutes.size() * VISIT_MINS;
243
        return new double[]{Math.round(totalKm * 1000d) / 1000d, Math.round(totalMins)};
244
    }
245
 
36663 ranu 246
	// ====================== ASSIGN VISIT ======================
247
	// Day View "Assign Visit" — lets an admin pick parties (stores) for a specific
248
	// auth user on a specific date and pushes them as visit tasks to the v2
249
	// /profitmandi-web/v2/beat-tracking/batch endpoint.
250
 
36716 ranu 251
	// List of parties (stores) assigned to this auth user + their dtr.users.id.
252
	// When date+beatId are passed, each party is also tagged with:
253
	//   inBeat        = is this store part of the scheduled beat's route on that date
254
	//   existingAgendas[] = agendas already saved for this store on that date (so the
255
	//                       modal can pre-fill them and let the user refill rather than re-assign)
36663 ranu 256
	@GetMapping(value = "/beatPlan/assignVisit/parties")
36716 ranu 257
	public ResponseEntity<?> assignVisitParties(
258
			@RequestParam int authUserId,
259
			@RequestParam(required = false) String date,
260
			@RequestParam(required = false) Integer beatId) throws Exception {
36663 ranu 261
		AuthUser au = authRepository.selectById(authUserId);
262
		if (au == null) return responseSender.badRequest("Auth user not found");
263
 
264
		// Map auth_user → dtr.users via email
265
		Integer dtrUserId = null;
266
		try {
267
			com.spice.profitmandi.dao.entity.dtr.User dtrUser =
268
					userRepositoryAuto.selectByEmailId(au.getEmailId());
269
			if (dtrUser != null) dtrUserId = dtrUser.getId();
270
		} catch (Exception ignored) {
271
		}
272
 
36716 ranu 273
		// Parse optional date
274
		LocalDate parsedDate = null;
275
		if (date != null && !date.isEmpty()) {
276
			try {
277
				parsedDate = LocalDate.parse(date);
278
			} catch (Exception ignored) {
279
			}
280
		}
281
 
282
		// Build (fofoId → dayNumber) of partners already in the beat's scheduled route for this date
283
		Set<Integer> inBeatFofoIds = new HashSet<>();
284
		if (beatId != null && parsedDate != null) {
285
			final LocalDate dateF = parsedDate; // capture for lambda (parsedDate is reassigned earlier so not effectively final)
286
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beatId);
287
			BeatSchedule match = schedules.stream()
288
					.filter(s -> s.getStartDate() != null && s.getStartDate().equals(dateF))
289
					.findFirst().orElse(null);
290
			if (match != null) {
291
				List<BeatRoute> routes = beatRouteRepository.selectByBeatId(beatId);
292
				routes.stream()
293
						.filter(r -> r.getDayNumber() == match.getDayNumber() && r.isActive())
294
						.forEach(r -> inBeatFofoIds.add(r.getFofoId()));
295
			}
296
		}
297
 
298
		// Build (fofoId → existingAgendas) and (fofoId → existingDescription) from
299
		// any already-saved location_tracking rows for this user on this date.
300
		// Agenda is stored as task_name = "agenda1, agenda2 | OutletName"
301
		// so we split on " | " to peel the outlet suffix off, then split agendas by ", ".
302
		// Description is stored on task_description (free text).
303
		Map<Integer, List<String>> existingAgendaByFofo = new HashMap<>();
304
		Map<Integer, String> existingDescByFofo = new HashMap<>();
305
		Map<Integer, Integer> existingTrackingIdByFofo = new HashMap<>();
306
		if (dtrUserId != null && parsedDate != null) {
307
			List<com.spice.profitmandi.dao.entity.auth.LocationTracking> existing =
308
					locationTrackingRepositoryAuto.findByUserAndDate(dtrUserId, parsedDate);
309
			for (com.spice.profitmandi.dao.entity.auth.LocationTracking lt : existing) {
310
				if (!"franchisee-visit".equals(lt.getTaskType())) continue;
311
				if (existingAgendaByFofo.containsKey(lt.getTaskId())) continue; // first wins
312
				String taskName = lt.getTaskName() == null ? "" : lt.getTaskName();
313
				String agendaPart = taskName;
314
				int pipeIdx = taskName.lastIndexOf(" | ");
315
				if (pipeIdx > 0) agendaPart = taskName.substring(0, pipeIdx);
316
				List<String> agendas = new ArrayList<>();
317
				for (String a : agendaPart.split(",")) {
318
					String trimmed = a.trim();
319
					if (!trimmed.isEmpty()) agendas.add(trimmed);
320
				}
321
				existingAgendaByFofo.put(lt.getTaskId(), agendas);
322
				existingDescByFofo.put(lt.getTaskId(), lt.getTaskDescription() != null ? lt.getTaskDescription() : "");
323
				existingTrackingIdByFofo.put(lt.getTaskId(), lt.getId());
324
			}
325
		}
326
 
36663 ranu 327
		Map<Integer, List<Integer>> mapping = csService.getAuthUserIdPartnerIdMapping();
328
		List<Integer> fofoIds = mapping.get(authUserId);
329
 
330
		List<Map<String, Object>> parties = new ArrayList<>();
331
		if (fofoIds != null && !fofoIds.isEmpty()) {
332
			List<FofoStore> stores = fofoStoreRepository.selectByRetailerIds(fofoIds);
333
			Map<Integer, CustomRetailer> retailerMap = retailerService.getFofoRetailers(fofoIds);
334
			for (FofoStore store : stores) {
335
				if (!store.isActive() || store.isClosed()) continue;
336
				CustomRetailer retailer = retailerMap.get(store.getId());
337
				Map<String, Object> p = new HashMap<>();
338
				p.put("fofoStoreId", store.getId());
339
				p.put("code", store.getCode());
340
				p.put("outletName", store.getOutletName() != null ? store.getOutletName()
341
						: (retailer != null ? retailer.getBusinessName() : "Store #" + store.getId()));
342
				p.put("latitude", store.getLatitude());
343
				p.put("longitude", store.getLongitude());
344
				p.put("city", retailer != null && retailer.getAddress() != null ? retailer.getAddress().getCity() : null);
36716 ranu 345
				p.put("inBeat", inBeatFofoIds.contains(store.getId()));
346
				p.put("existingAgendas", existingAgendaByFofo.getOrDefault(store.getId(), new ArrayList<>()));
347
				p.put("existingDescription", existingDescByFofo.getOrDefault(store.getId(), ""));
348
				p.put("existingTrackingId", existingTrackingIdByFofo.get(store.getId()));
36663 ranu 349
				parties.add(p);
350
			}
36716 ranu 351
			// In-beat first, then by code
352
			parties.sort((a, b) -> {
353
				boolean ai = Boolean.TRUE.equals(a.get("inBeat"));
354
				boolean bi = Boolean.TRUE.equals(b.get("inBeat"));
355
				if (ai != bi) return ai ? -1 : 1;
356
				return String.valueOf(a.get("code")).compareToIgnoreCase(String.valueOf(b.get("code")));
357
			});
36663 ranu 358
		}
359
 
37175 amit 360
		// Open agenda instances (AUTO + MANUAL) per party — the modal pre-selects
361
		// these; AUTO ones are badged and close only when their metric normalizes.
37182 amit 362
		// Visibility rule: for a REVIVAL store only REVIVAL/CREDIT_DUES/MANUAL
363
		// agendas are populated (the rest keep their lifecycle but stay hidden).
37175 amit 364
		List<Integer> partyIds = new ArrayList<>();
365
		for (Map<String, Object> p : parties) partyIds.add((Integer) p.get("fofoStoreId"));
37182 amit 366
		Map<Integer, List<AgendaInstance>> openByFofo = new HashMap<>();
37175 amit 367
		for (AgendaInstance ai : agendaInstanceRepository.selectOpenByFofoIds(partyIds)) {
37182 amit 368
			openByFofo.computeIfAbsent(ai.getFofoId(), k -> new ArrayList<>()).add(ai);
37175 amit 369
		}
37182 amit 370
		Map<Integer, List<Map<String, Object>>> openAgendasByFofo = new HashMap<>();
371
		for (Map.Entry<Integer, List<AgendaInstance>> e : openByFofo.entrySet()) {
372
			List<Map<String, Object>> visible = new ArrayList<>();
373
			for (AgendaInstance ai : agendaInstanceService.filterVisibleForVisit(e.getValue())) {
374
				Map<String, Object> m = new HashMap<>();
375
				m.put("id", ai.getId());
376
				m.put("agendaType", ai.getAgendaType());
377
				m.put("label", labelFor(ai.getAgendaType()));
378
				m.put("source", ai.getSource());
379
				m.put("openedOn", ai.getOpenedOn() != null ? ai.getOpenedOn().toLocalDate().toString() : null);
380
				visible.add(m);
381
			}
382
			openAgendasByFofo.put(e.getKey(), visible);
383
		}
37175 amit 384
		for (Map<String, Object> p : parties) {
385
			p.put("openAgendas", openAgendasByFofo.getOrDefault((Integer) p.get("fofoStoreId"), new ArrayList<>()));
386
		}
387
 
36663 ranu 388
		Map<String, Object> result = new HashMap<>();
389
		result.put("dtrUserId", dtrUserId);
390
		result.put("authUserId", authUserId);
391
		result.put("userName", au.getFirstName() + " " + au.getLastName());
392
		result.put("parties", parties);
37248 vikas 393
		result.put("agendaOptions", com.spice.profitmandi.dao.enumuration.dtr.VisitAgenda.labels());
394
		// Managers can't assign a visit while a scheduled beat's agenda is unfilled; the
395
		// modal uses this flag to show the warning and disable the assign action. (A
396
		// user with no beat that day is allowed — nothing to fill.)
397
		boolean agendaFilled = agendaAllowsAssign(authUserId, parsedDate != null ? parsedDate : LocalDate.now());
398
		result.put("agendaFilled", agendaFilled);
399
		result.put("agendaNotFilledMessage", AGENDA_NOT_FILLED_MSG);
37182 amit 400
		// Only non-auto agendas are manually assignable; auto ones surface via
401
		// openAgendas (chips) and are woven into task_name server-side on submit.
402
		result.put("agendaOptions", AgendaType.manualAssignableLabels());
36663 ranu 403
		return responseSender.ok(result);
404
	}
405
 
37175 amit 406
	// agenda_type holds the enum NAME (e.g. LOW_SALES); tolerate unknown values.
407
	private String labelFor(String agendaTypeName) {
408
		try {
409
			return AgendaType.valueOf(agendaTypeName).getLabel();
410
		} catch (Exception e) {
411
			return agendaTypeName;
412
		}
413
	}
414
 
36663 ranu 415
	// Submit assignment — accepts a JSON body, builds the v2 payload, posts it
416
	@PostMapping(value = "/beatPlan/assignVisit/submit")
417
	public ResponseEntity<?> assignVisitSubmit(
418
			HttpServletRequest request,
419
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
420
 
421
		Integer authUserId = body.get("authUserId") != null ? ((Number) body.get("authUserId")).intValue() : null;
422
		String planDate = (String) body.get("planDate");
423
		List<Map<String, Object>> selected = (List<Map<String, Object>>) body.get("parties");
424
		if (authUserId == null || planDate == null || selected == null || selected.isEmpty()) {
425
			return responseSender.badRequest("authUserId, planDate and parties are required");
426
		}
427
 
36962 vikas 428
		// Defence-in-depth: Assign Visit is L2-and-above only (mirrors the hidden UI).
37175 amit 429
		AuthUser operator = currentUser(request);
430
		if (!canEditBeat(operator)) {
36962 vikas 431
			return responseSender.badRequest("Assigning a visit is restricted to L2 and above.");
432
		}
37175 amit 433
		Integer operatorAuthId = operator != null ? operator.getId() : null;
36962 vikas 434
 
36663 ranu 435
		AuthUser au = authRepository.selectById(authUserId);
436
		if (au == null) return responseSender.badRequest("Auth user not found");
437
 
438
		// Map auth → dtr.users.id (this is the userId the v2 endpoint expects)
439
		com.spice.profitmandi.dao.entity.dtr.User dtrUser;
440
		try {
441
			dtrUser = userRepositoryAuto.selectByEmailId(au.getEmailId());
442
		} catch (Exception e) {
443
			return responseSender.badRequest("Failed to look up dtr.users for this auth user");
444
		}
445
		if (dtrUser == null) {
446
			return responseSender.badRequest("No dtr.users record found for auth user " + authUserId);
447
		}
448
		int dtrUserId = dtrUser.getId();
449
 
450
		// Persist directly via the shared DAO — mirrors BeatTrackingController.createBatch
451
		// in profitmandi-web. We can't autowire a controller across WARs, but
452
		// LocationTrackingRepository lives in profitmandi-dao and is shared.
453
		LocalDate taskDate;
454
		try {
455
			taskDate = LocalDate.parse(planDate);
456
		} catch (Exception e) {
457
			return responseSender.badRequest("Invalid planDate (expected yyyy-MM-dd): " + planDate);
458
		}
459
 
36716 ranu 460
		// Existing rows for this user on this date — keyed by fofoStoreId.
461
		// If a row already exists for a party, we UPDATE its agenda instead of
462
		// creating a duplicate (this is the "refill agenda" path for already-
463
		// assigned parties).
464
		Map<Integer, com.spice.profitmandi.dao.entity.auth.LocationTracking> existingByFofo = new HashMap<>();
465
		for (com.spice.profitmandi.dao.entity.auth.LocationTracking lt :
466
				locationTrackingRepositoryAuto.findByUserAndDate(dtrUserId, taskDate)) {
467
			if (!"franchisee-visit".equals(lt.getTaskType())) continue;
468
			existingByFofo.putIfAbsent(lt.getTaskId(), lt);
469
		}
470
 
471
		// Defence-in-depth: Assign Visit is only valid for today's run. Hiding the
472
		// button on the UI isn't enough — block at the API too.
473
		if (!taskDate.equals(LocalDate.now())) {
474
			return responseSender.badRequest("Visits can only be assigned for today's date (" + LocalDate.now() + ")");
475
		}
476
 
37248 vikas 477
		// Block when the executive has a beat scheduled today but hasn't filled its
478
		// agenda yet (enforced here so it applies to every caller, not just the UI).
479
		if (!agendaAllowsAssign(authUserId, taskDate)) {
480
			return responseSender.badRequest(AGENDA_NOT_FILLED_MSG);
481
		}
482
 
36663 ranu 483
		LocalDateTime now = LocalDateTime.now();
36716 ranu 484
		int createdCount = 0, updatedCount = 0;
36663 ranu 485
 
486
		for (Map<String, Object> p : selected) {
487
			Integer fofoStoreId = ((Number) p.get("fofoStoreId")).intValue();
488
			String outletName = (String) p.get("outletName");
489
			String lat = (String) p.get("latitude");
490
			String lng = (String) p.get("longitude");
36716 ranu 491
			String description = (String) p.get("description");
492
			if (description != null) description = description.trim();
493
			if (description == null) description = "";
36663 ranu 494
 
36716 ranu 495
			// Multi-agenda: accept agendas[] (new format) or fall back to agenda (legacy single)
496
			List<String> agendas = new ArrayList<>();
497
			Object rawAgendas = p.get("agendas");
498
			if (rawAgendas instanceof List) {
499
				for (Object o : (List<?>) rawAgendas) {
500
					if (o != null) {
501
						String s = String.valueOf(o).trim();
502
						if (!s.isEmpty()) agendas.add(s);
503
					}
504
				}
505
			}
506
			if (agendas.isEmpty()) {
507
				String single = (String) p.get("agenda");
508
				if (single != null && !single.trim().isEmpty()) agendas.add(single.trim());
509
			}
37182 amit 510
			// Compose the final agenda set: visible open instances first (auto
511
			// agendas populate themselves — the planner never assigns them),
512
			// then the picked manual-assignable agendas. Picked labels of
513
			// auto-rule types are ignored (server-authoritative guard).
514
			LinkedHashSet<String> finalAgendas = new LinkedHashSet<>();
515
			for (AgendaInstance ai : agendaInstanceService.filterVisibleForVisit(
516
					agendaInstanceRepository.selectOpenByFofoId(fofoStoreId))) {
517
				finalAgendas.add(labelFor(ai.getAgendaType()));
518
			}
37175 amit 519
			for (String label : agendas) {
520
				AgendaType type = AgendaType.fromLabel(label);
37182 amit 521
				if (type == null) continue; // free text / legacy "Visit" — dropped
522
				if (!type.isManualAssignable()) continue; // auto agendas: cron-only
37175 amit 523
				agendaInstanceService.open(fofoStoreId, type.name(), AgendaSource.MANUAL, operatorAuthId, null);
37182 amit 524
				finalAgendas.add(label);
37175 amit 525
			}
37182 amit 526
			if (finalAgendas.isEmpty()) finalAgendas.add("Visit");
527
			String agendaJoined = String.join(", ", finalAgendas);
37175 amit 528
 
36663 ranu 529
			String visitLocation = (lat != null && lng != null && !lat.isEmpty() && !lng.isEmpty())
530
					? (lat + "," + lng) : "0.0000,0.0000";
531
 
532
			String displayName = (outletName != null && !outletName.isEmpty()) ? outletName : ("Store #" + fofoStoreId);
36716 ranu 533
			String newTaskName = agendaJoined + " | " + displayName;
36663 ranu 534
 
36716 ranu 535
			com.spice.profitmandi.dao.entity.auth.LocationTracking existing = existingByFofo.get(fofoStoreId);
536
			if (existing != null) {
537
				// Refill — agenda (task_name), description, and visit location change
538
				existing.setTaskName(newTaskName);
539
				existing.setTaskDescription(description);
540
				existing.setVisitLocation(visitLocation);
541
				existing.setUpdatedTimestamp(now);
542
				locationTrackingRepositoryAuto.persist(existing);
543
				updatedCount++;
544
				continue;
545
			}
546
 
36663 ranu 547
			com.spice.profitmandi.dao.entity.auth.LocationTracking row =
548
					new com.spice.profitmandi.dao.entity.auth.LocationTracking();
549
			row.setUserId(dtrUserId);
550
			row.setDeviceId("0");
551
			row.setTaskId(fofoStoreId);
552
			row.setTaskDate(taskDate);
36716 ranu 553
			row.setTaskName(newTaskName);
554
			row.setTaskDescription(description);
36663 ranu 555
			row.setTaskType("franchisee-visit");
36764 ranu 556
			row.setMarkType(String.valueOf(ProfitMandiConstants.MARK_TYPE.PENDING));
36663 ranu 557
			row.setAddress("");
558
			row.setVisitLocation(visitLocation);
559
			row.setCheckInLatLng("0.0000,0.0000");
560
			row.setCheckOutLatLng("0.0000,0.0000");
561
			row.setCheckInTime(java.time.LocalTime.MIDNIGHT);
562
			row.setCheckOutTime(java.time.LocalTime.MIDNIGHT);
563
			row.setTransitTime(java.time.LocalTime.MIDNIGHT);
564
			row.setTimeSpent(java.time.LocalTime.MIDNIGHT);
565
			row.setEstimatedTime(java.time.LocalTime.MIDNIGHT);
566
			row.setSessionStartTime(java.time.LocalTime.MIDNIGHT);
567
			row.setSessionEndTime(java.time.LocalTime.MIDNIGHT);
568
			row.setTotalDistance("0.0");
569
			row.setStatus(false);
570
			row.setCreatedTimestamp(now);
571
			row.setUpdatedTimestamp(now);
572
 
573
			// Do NOT try/catch this — if persist throws, let it propagate so
574
			// @Transactional(rollbackFor = Throwable.class) rolls back cleanly.
575
			locationTrackingRepositoryAuto.persist(row);
36716 ranu 576
			createdCount++;
36663 ranu 577
		}
36716 ranu 578
		LOGGER.info("assignVisit dtrUserId={} created={} updated={}", dtrUserId, createdCount, updatedCount);
36663 ranu 579
 
580
		Map<String, Object> result = new HashMap<>();
581
		result.put("status", true);
36716 ranu 582
		result.put("createdCount", createdCount);
583
		result.put("updatedCount", updatedCount);
36663 ranu 584
		result.put("dtrUserId", dtrUserId);
36716 ranu 585
		StringBuilder msg = new StringBuilder();
586
		if (createdCount > 0)
587
			msg.append(createdCount).append(" new visit").append(createdCount == 1 ? "" : "s").append(" assigned");
588
		if (updatedCount > 0) {
589
			if (msg.length() > 0) msg.append(", ");
590
			msg.append(updatedCount).append(" existing agenda").append(updatedCount == 1 ? "" : "s").append(" refilled");
591
		}
592
		msg.append(" for ").append(au.getFirstName()).append(" ").append(au.getLastName());
593
		result.put("message", msg.toString());
36663 ranu 594
		return responseSender.ok(result);
595
	}
596
 
37178 amit 597
	// Close a MANUAL agenda instance. AUTO instances are refused inside
598
	// AgendaInstanceService.closeManual — they close only when their metric
599
	// normalizes (nightly cron).
600
	@PostMapping(value = "/beatPlan/agenda/close")
601
	public ResponseEntity<?> closeAgenda(
602
			HttpServletRequest request,
603
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
604
		Integer instanceId = body.get("instanceId") != null ? ((Number) body.get("instanceId")).intValue() : null;
605
		String remark = body.get("remark") != null ? String.valueOf(body.get("remark")).trim() : null;
606
		if (instanceId == null) return responseSender.badRequest("instanceId is required");
607
 
608
		AuthUser operator = currentUser(request);
609
		if (operator == null) return responseSender.badRequest("Not logged in");
610
 
611
		AgendaInstance instance = agendaInstanceRepository.selectById(instanceId);
612
		if (instance == null) return responseSender.badRequest("Agenda instance not found");
613
		try {
614
			agendaInstanceService.closeManual(instance, operator.getId(), remark);
615
		} catch (ProfitMandiBusinessException e) {
616
			return responseSender.badRequest(e.getMessage());
617
		}
618
		Map<String, Object> result = new HashMap<>();
619
		result.put("status", true);
620
		result.put("instanceId", instanceId);
621
		return responseSender.ok(result);
622
	}
623
 
37248 vikas 624
	// Warning shown (and enforced) when a manager tries to assign a visit before the
625
	// executive has filled their agenda for the day.
626
	static final String AGENDA_NOT_FILLED_MSG = "Agenda not filled yet you cant assign visit";
627
 
628
	// True when the agenda rule permits a manager to assign a visit to `authUserId`
629
	// on `date`: either the executive has no beat scheduled that day (nothing to
630
	// fill), or at least one of their scheduled beats has its agenda_filled_timestamp
631
	// set. ONLY a scheduled-but-unfilled agenda blocks assignment.
632
	private boolean agendaAllowsAssign(int authUserId, LocalDate date) {
633
		if (date == null) return true;
634
		List<Integer> beatIds = beatPlanQueryService.getAllScheduledBeats(date, date).stream()
635
				.filter(b -> b.getAuthUserId() == authUserId)
636
				.map(com.spice.profitmandi.dao.model.BeatDayDetails::getBeatId)
637
				.distinct().collect(Collectors.toList());
638
		if (beatIds.isEmpty()) return true;   // no beat scheduled → agenda rule doesn't apply
639
		for (BeatSchedule bs : beatScheduleRepository.selectByBeatIds(beatIds)) {
640
			if (bs.getStartDate() != null && bs.getStartDate().equals(date)
641
					&& bs.getAgendaFilledTimestamp() != null) {
642
				return true;
643
			}
644
		}
645
		return false;
646
	}
647
 
36740 ranu 648
	// ====================== DEFERRED PARTNERS ======================
649
	// Heads review partners that weren't visited on their planned day and act on
650
	// them. The deferral lifecycle lives in user.beat_deferred_visit (separate
651
	// from the raw location_tracking event log). Detection = explicit
652
	// (mark_type='DEFERRED') + derived (planned beat_route minus completed visits).
653
 
654
	// Page
655
	@GetMapping(value = "/beatPlan/deferredView")
656
	public String deferredView(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
657
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
658
		return "beat-plan-deferred";
659
	}
660
 
661
	// List (syncs the table first, then returns the head's downline deferrals).
662
	@GetMapping(value = "/beatPlan/deferred")
663
	public ResponseEntity<?> deferredList(
664
			HttpServletRequest request,
665
			@RequestParam(required = false) String startDate,
666
			@RequestParam(required = false) String endDate) throws Exception {
667
 
668
		LocalDate start, end;
669
		try {
670
			start = (startDate == null || startDate.isEmpty()) ? LocalDate.now().minusDays(7) : LocalDate.parse(startDate);
671
			end = (endDate == null || endDate.isEmpty()) ? LocalDate.now() : LocalDate.parse(endDate);
672
		} catch (Exception e) {
673
			return responseSender.badRequest("Invalid date — expected yyyy-MM-dd");
674
		}
675
 
676
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
677
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
678
		if (me == null) return responseSender.unauthorized("Not logged in");
679
 
680
		// PURE READ. Deferrals are persisted at the write point (BeatTrackingController,
681
		// when mark_type='DEFERRED' is recorded) — this endpoint never writes.
682
		List<BeatDeferredVisit> source;
683
		if (isSuperAdmin(me)) {
684
			source = beatDeferredVisitRepository.selectByDateRange(start, end);
685
		} else {
686
			Set<Integer> downline = new HashSet<>(authService.getAllReportees(me.getId()));
687
			downline.add(me.getId());
688
			source = beatDeferredVisitRepository.selectByAuthUserIdsAndDateRange(new ArrayList<>(downline), start, end);
689
		}
690
		List<BeatDeferredVisit> rows = source.stream()
691
				.filter(r -> "DEFERRED".equals(r.getStatus()))
692
				.collect(Collectors.toList());
693
 
694
		// ---- nextScheduledDate (info only: does a future run already cover it?) ----
695
		// Only meaningful for partner visits (leads aren't on beat_route). Purely a
696
		// hint — the row stays actionable even when auto-covered, since the next run
697
		// could be far off.
698
		Map<Integer, Map<Integer, LocalDate>> coverCache = new HashMap<>();
699
		Map<Integer, LocalDate> nextByRowId = new HashMap<>();
700
		for (BeatDeferredVisit r : rows) {
701
			if (!"franchisee-visit".equals(r.getTaskType())) continue;
702
			Map<Integer, LocalDate> cover = coverCache.computeIfAbsent(r.getAuthUserId(), this::computeFutureCover);
703
			LocalDate next = cover.get(r.getFofoId());
704
			if (next != null) nextByRowId.put(r.getId(), next);
705
		}
706
 
707
		// ---- resolve user names (display name + type already denormalized on the row) ----
708
		Set<Integer> authIds = rows.stream().map(BeatDeferredVisit::getAuthUserId).collect(Collectors.toSet());
709
		Map<Integer, AuthUser> userMap = new HashMap<>();
710
		if (!authIds.isEmpty())
711
			authRepository.selectByIds(new ArrayList<>(authIds)).forEach(u -> userMap.put(u.getId(), u));
712
 
713
		List<Map<String, Object>> out = new ArrayList<>();
714
		for (BeatDeferredVisit r : rows) {
715
			AuthUser u = userMap.get(r.getAuthUserId());
716
			boolean isLead = "lead".equalsIgnoreCase(r.getTaskType());
36811 ranu 717
			boolean isOffice = "office-visit".equalsIgnoreCase(r.getTaskType());
36740 ranu 718
			Map<String, Object> row = new HashMap<>();
719
			row.put("id", r.getId());
720
			row.put("authUserId", r.getAuthUserId());
721
			row.put("userName", u != null ? (u.getFirstName() + " " + u.getLastName()) : ("User #" + r.getAuthUserId()));
722
			row.put("fofoStoreId", r.getFofoId());
723
			row.put("name", r.getDisplayName() != null ? r.getDisplayName() : ("#" + r.getFofoId()));
36811 ranu 724
			row.put("type", isLead ? "Lead" : (isOffice ? "Office" : "Visit"));
36740 ranu 725
			row.put("deferredDate", r.getDeferredDate() != null ? r.getDeferredDate().toString() : null);
726
			row.put("reason", r.getReason());
727
			row.put("status", r.getStatus());
728
			LocalDate next = nextByRowId.get(r.getId());
729
			row.put("nextScheduledDate", next != null ? next.toString() : null);
730
			out.add(row);
731
		}
732
		out.sort((a, c) -> String.valueOf(a.get("deferredDate")).compareTo(String.valueOf(c.get("deferredDate"))));
733
 
734
		Map<String, Object> result = new HashMap<>();
735
		result.put("rows", out);
736
		result.put("startDate", start.toString());
737
		result.put("endDate", end.toString());
738
		return responseSender.ok(result);
739
	}
740
 
741
	// Head action on a deferral: reschedule (one-off visit, or into an existing
742
	// beat-day) or cancel. Never edits the beat template.
743
	@PostMapping(value = "/beatPlan/deferred/action")
744
	public ResponseEntity<?> deferredAction(
745
			HttpServletRequest request,
746
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
747
 
748
		Integer deferredId = body.get("deferredId") != null ? ((Number) body.get("deferredId")).intValue() : null;
749
		String action = (String) body.get("action");
750
		String toDateStr = (String) body.get("toDate");
751
		if (deferredId == null || action == null)
752
			return responseSender.badRequest("deferredId and action are required");
753
 
754
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
755
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
756
		if (me == null) return responseSender.unauthorized("Not logged in");
757
 
758
		BeatDeferredVisit d = beatDeferredVisitRepository.selectById(deferredId);
759
		if (d == null) return responseSender.badRequest("Deferred record not found");
760
 
761
		LocalDateTime now = LocalDateTime.now();
762
 
763
		if ("cancel".equalsIgnoreCase(action)) {
36763 ranu 764
			d.setStatus(String.valueOf(ProfitMandiConstants.MARK_TYPE.CANCELLED));
36740 ranu 765
			d.setActionBy(me.getId());
766
			d.setUpdatedTimestamp(now);
36792 ranu 767
			// Optional cancel reason — overlay onto the reason column. Original
768
			// deferred-reason is preserved as a suffix so we keep the audit trail.
769
			String cancelReason = body.get("reason") != null ? String.valueOf(body.get("reason")).trim() : "";
770
			if (!cancelReason.isEmpty()) {
771
				String prev = d.getReason() != null ? d.getReason() : "";
772
				d.setReason("Cancelled: " + cancelReason + (prev.isEmpty() ? "" : " | Original: " + prev));
773
			}
36740 ranu 774
			beatDeferredVisitRepository.persist(d);
775
			Map<String, Object> ok = new HashMap<>();
776
			ok.put("status", true);
777
			ok.put("message", "Deferred visit cancelled");
778
			return responseSender.ok(ok);
779
		}
780
 
781
		// reschedule_oneoff | reschedule_beat
782
		if (toDateStr == null || toDateStr.isEmpty())
783
			return responseSender.badRequest("toDate is required to reschedule");
784
		LocalDate toDate;
785
		try {
786
			toDate = LocalDate.parse(toDateStr);
787
		} catch (Exception e) {
788
			return responseSender.badRequest("Invalid toDate (yyyy-MM-dd)");
789
		}
36821 ranu 790
		// Reschedule must land on a STRICTLY future date — today is already in progress.
791
		if (!toDate.isAfter(LocalDate.now()))
792
			return responseSender.badRequest("Reschedule date must be in the future (today is already in progress).");
36740 ranu 793
 
794
		if ("reschedule_beat".equalsIgnoreCase(action)) {
795
			boolean hasBeat = beatRepository.selectActiveByAuthUserId(d.getAuthUserId()).stream()
796
					.flatMap(b -> beatScheduleRepository.selectByBeatId(b.getId()).stream())
797
					.anyMatch(s -> s.getStartDate() != null && s.getStartDate().equals(toDate));
798
			if (!hasBeat)
799
				return responseSender.badRequest("No beat is scheduled for this user on " + toDateStr + ". Pick another date or use a one-off visit.");
800
		}
801
 
802
		// Resolve dtr user, then create a PENDING task on toDate. Reuse the
803
		// denormalized name + type (works for both partner visits and leads — for
804
		// leads, looking up fofo_store would be the wrong id space). For visits we
805
		// still try to pull lat/lng for the visit location.
806
		Integer dtrId = resolveDtrId(d.getAuthUserId(), new HashMap<>());
807
		if (dtrId == null) return responseSender.badRequest("No dtr.users record for this sales person");
808
		boolean isLead = "lead".equalsIgnoreCase(d.getTaskType());
36811 ranu 809
		boolean isOffice = "office-visit".equalsIgnoreCase(d.getTaskType());
36740 ranu 810
		String visitLocation = "0.0000,0.0000";
36811 ranu 811
		if (isOffice) {
812
			// Office stops resolve lat/lng from logistics.company_office.
36740 ranu 813
			try {
36811 ranu 814
				com.spice.profitmandi.dao.entity.logistics.CompanyOffice o = companyOfficeRepository.selectById(d.getFofoId());
815
				if (o != null) visitLocation = o.getLat() + "," + o.getLng();
816
			} catch (Exception ignored) {
817
			}
818
		} else if (!isLead) {
819
			try {
36740 ranu 820
				List<FofoStore> ss = fofoStoreRepository.selectByRetailerIds(java.util.Collections.singletonList(d.getFofoId()));
821
				if (!ss.isEmpty()) {
822
					FofoStore fs = ss.get(0);
823
					if (fs.getLatitude() != null && fs.getLongitude() != null
824
							&& !fs.getLatitude().isEmpty() && !fs.getLongitude().isEmpty()) {
825
						visitLocation = fs.getLatitude() + "," + fs.getLongitude();
826
					}
827
				}
828
			} catch (Exception ignored) {
829
			}
830
		}
831
		String taskName = d.getDisplayName() != null ? d.getDisplayName()
832
				: ((d.getReason() != null ? d.getReason() : "Rescheduled") + " | #" + d.getFofoId());
833
 
834
		com.spice.profitmandi.dao.entity.auth.LocationTracking row = new com.spice.profitmandi.dao.entity.auth.LocationTracking();
835
		row.setUserId(dtrId);
836
		row.setDeviceId("0");
837
		row.setTaskId(d.getFofoId());
838
		row.setTaskDate(toDate);
839
		row.setTaskName(taskName);
840
		row.setTaskDescription("Rescheduled from " + d.getDeferredDate());
841
		row.setTaskType(d.getTaskType() != null ? d.getTaskType() : "franchisee-visit");
36763 ranu 842
		row.setMarkType(String.valueOf(ProfitMandiConstants.MARK_TYPE.PENDING));
36740 ranu 843
		row.setAddress("");
844
		row.setVisitLocation(visitLocation);
845
		row.setCheckInLatLng("0.0000,0.0000");
846
		row.setCheckOutLatLng("0.0000,0.0000");
847
		row.setCheckInTime(java.time.LocalTime.MIDNIGHT);
848
		row.setCheckOutTime(java.time.LocalTime.MIDNIGHT);
849
		row.setTransitTime(java.time.LocalTime.MIDNIGHT);
850
		row.setTimeSpent(java.time.LocalTime.MIDNIGHT);
851
		row.setEstimatedTime(java.time.LocalTime.MIDNIGHT);
852
		row.setSessionStartTime(java.time.LocalTime.MIDNIGHT);
853
		row.setSessionEndTime(java.time.LocalTime.MIDNIGHT);
854
		row.setTotalDistance("0.0");
855
		row.setStatus(false);
856
		row.setCreatedTimestamp(now);
857
		row.setUpdatedTimestamp(now);
858
		locationTrackingRepositoryAuto.persist(row);
859
 
36763 ranu 860
		d.setStatus(String.valueOf(ProfitMandiConstants.MARK_TYPE.RESCHEDULED));
36740 ranu 861
		d.setRescheduledToDate(toDate);
862
		d.setActionBy(me.getId());
863
		d.setUpdatedTimestamp(now);
864
		beatDeferredVisitRepository.persist(d);
865
 
866
		Map<String, Object> ok = new HashMap<>();
867
		ok.put("status", true);
868
		ok.put("message", "Visit rescheduled to " + toDateStr);
869
		return responseSender.ok(ok);
870
	}
871
 
872
	// Drop a deferred item into a specific upcoming BEAT run (chosen from the beat
873
	// calendar). Lead → a lead_route row on that beat/date (renders as a lead stop).
874
	// Partner visit → appended to that beat's route for the date's day_number.
875
	// The beat plan calendar then shows it. Marks the deferral RESCHEDULED.
876
	@PostMapping(value = "/beatPlan/deferred/assignToBeat")
877
	public ResponseEntity<?> deferredAssignToBeat(
878
			HttpServletRequest request,
879
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
880
 
881
		Integer deferredId = body.get("deferredId") != null ? ((Number) body.get("deferredId")).intValue() : null;
882
		Integer beatId = body.get("beatId") != null ? ((Number) body.get("beatId")).intValue() : null;
883
		String dateStr = (String) body.get("date");
884
		if (deferredId == null || beatId == null || dateStr == null)
885
			return responseSender.badRequest("deferredId, beatId and date are required");
886
 
887
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
888
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
889
		if (me == null) return responseSender.unauthorized("Not logged in");
890
 
891
		LocalDate date;
892
		try {
893
			date = LocalDate.parse(dateStr);
894
		} catch (Exception e) {
895
			return responseSender.badRequest("Invalid date (yyyy-MM-dd)");
896
		}
36821 ranu 897
		// Drop-onto-beat must land on a STRICTLY future date — today is already in progress.
898
		if (!date.isAfter(LocalDate.now()))
899
			return responseSender.badRequest("Pick a future date — today is already in progress.");
36740 ranu 900
 
901
		BeatDeferredVisit d = beatDeferredVisitRepository.selectById(deferredId);
902
		if (d == null) return responseSender.badRequest("Deferred record not found");
903
 
904
		// A deferral can only move FORWARD — never onto the day it was deferred or earlier.
905
		if (d.getDeferredDate() != null && !date.isAfter(d.getDeferredDate())) {
906
			return responseSender.badRequest("A deferred item can only be moved to a date after "
907
					+ d.getDeferredDate() + " (it was deferred that day).");
908
		}
909
 
910
		Beat beat = beatRepository.selectById(beatId);
911
		if (beat == null) return responseSender.badRequest("Beat not found");
912
 
913
		// The beat must actually run on the chosen date — get that run's day number.
914
		BeatSchedule sched = beatScheduleRepository.selectByBeatId(beatId).stream()
915
				.filter(s -> s.getStartDate() != null && s.getStartDate().equals(date))
916
				.findFirst().orElse(null);
917
		if (sched == null) return responseSender.badRequest("That beat is not scheduled on " + dateStr);
918
 
919
		LocalDateTime now = LocalDateTime.now();
920
		boolean isLead = "lead".equalsIgnoreCase(d.getTaskType());
921
 
922
		if (isLead) {
923
			// Avoid duplicating the same lead on the same beat/date
924
			boolean exists = leadRouteRepository.selectByBeatId(beatId).stream()
925
					.anyMatch(lr -> lr.getLeadId() == d.getFofoId()
926
							&& date.equals(lr.getScheduleDate())
927
							&& !"CANCELLED".equals(lr.getStatus()));
928
			if (!exists) {
929
				LeadRoute lr = new LeadRoute();
930
				lr.setBeatId(beatId);
931
				lr.setLeadId(d.getFofoId());
932
				lr.setScheduleDate(date);
933
				lr.setSequenceOrder(9999); // append; planner can reorder
934
				lr.setStatus("APPROVED");
935
				lr.setApprovedBy(me.getId());
936
				lr.setApprovedTimestamp(now);
937
				lr.setCreatedTimestamp(now);
938
				lr.setUpdatedTimestamp(now);
939
				leadRouteRepository.persist(lr);
940
			}
941
		} else {
942
			// Partner visit → append to that beat's route for the date's day number,
943
			// if not already present on that day.
944
			boolean exists = beatRouteRepository.selectByBeatId(beatId).stream()
945
					.anyMatch(r -> r.getFofoId() == d.getFofoId() && r.getDayNumber() == sched.getDayNumber() && r.isActive());
946
			if (!exists) {
947
				int nextSeq = beatRouteRepository.selectByBeatId(beatId).stream()
948
						.filter(r -> r.getDayNumber() == sched.getDayNumber())
949
						.mapToInt(BeatRoute::getSequenceOrder).max().orElse(-1) + 1;
950
				BeatRoute br = new BeatRoute();
951
				br.setBeatId(beatId);
952
				br.setFofoId(d.getFofoId());
36811 ranu 953
				br.setVisitType(com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.PARTNER);
36740 ranu 954
				br.setDayNumber(sched.getDayNumber());
955
				br.setSequenceOrder(nextSeq);
956
				br.setActive(true);
957
				beatRouteRepository.persist(br);
958
			}
959
		}
960
 
36763 ranu 961
		d.setStatus(String.valueOf(ProfitMandiConstants.MARK_TYPE.RESCHEDULED));
36740 ranu 962
		d.setRescheduledToDate(date);
963
		d.setActionBy(me.getId());
964
		d.setUpdatedTimestamp(now);
965
		beatDeferredVisitRepository.persist(d);
966
 
967
		Map<String, Object> ok = new HashMap<>();
968
		ok.put("status", true);
969
		ok.put("message", (isLead ? "Lead" : "Partner") + " added to beat '" + beat.getName() + "' on " + dateStr);
970
		return responseSender.ok(ok);
971
	}
972
 
37120 vikas 973
	// ==================== ASSIGN LEADS ONTO BEATS ====================
974
	// A rep's assigned leads can be routed onto a beat from two surfaces:
975
	//   • Route Planner "Assigned Leads" list → single lead, calendar-chip picks beat+date
976
	//   • Day View "Add Lead" modal           → bulk write onto a known beat+date
977
	// Both converge on the same dated, APPROVED lead_route write (writeLeadRoute),
978
	// mirroring VisitRequestController.approveSchedule and deferredAssignToBeat's
979
	// lead branch. Nothing downstream changes — getBeatVisits and the
980
	// /visit-approvals/beat-route feed already render lead_route rows for the run.
981
 
982
	// Active/open lead colours a manager can still route (matches getOpenLead's
983
	// All → yellow+green expansion). Red/other are dropped as not-worth-visiting.
984
	private static final Set<String> ROUTABLE_LEAD_COLORS =
985
			new HashSet<>(Arrays.asList("yellow", "green"));
986
 
987
	// Can the caller see the selected user's leads? Super-admin sees everyone;
988
	// otherwise the user must be the caller or in their downline.
989
	private boolean canViewUserLeads(AuthUser me, int authUserId) {
990
		if (me == null) return false;
991
		if (isSuperAdmin(me)) return true;
992
		if (me.getId() == authUserId) return true;
993
		return new HashSet<>(authService.getAllReportees(me.getId())).contains(authUserId);
994
	}
995
 
996
	// GET /beatPlan/assignedLeads?authUserId=&beatId=&date=
997
	// Lists the selected user's active/open leads (pending + follow-up, yellow/green).
998
	// When beatId+date are supplied (Day View), each lead is tagged alreadyOnBeat if
999
	// it already has a non-cancelled lead_route on that beat+date.
1000
	@GetMapping(value = "/beatPlan/assignedLeads")
1001
	public ResponseEntity<?> assignedLeads(
1002
			HttpServletRequest request,
1003
			@RequestParam int authUserId,
1004
			@RequestParam(required = false) Integer beatId,
1005
			@RequestParam(required = false) String date) throws ProfitMandiBusinessException {
1006
 
1007
		AuthUser me = currentUser(request);
1008
		if (me == null) return responseSender.unauthorized("Not logged in");
1009
		if (!canViewUserLeads(me, authUserId)) {
1010
			// Not visible to this manager → empty (mirrors VisitRequestController.list).
1011
			return responseSender.ok(Collections.singletonMap("rows", new ArrayList<>()));
1012
		}
1013
 
1014
		// Active/open only — pending + follow-up.
1015
		List<Lead> leads = new ArrayList<>();
1016
		leads.addAll(leadRepository.selectByAssignAuthIdAndStatus(
1017
				authUserId, com.spice.profitmandi.dao.enumuration.dtr.LeadStatus.pending));
1018
		leads.addAll(leadRepository.selectByAssignAuthIdAndStatus(
1019
				authUserId, com.spice.profitmandi.dao.enumuration.dtr.LeadStatus.followUp));
1020
 
1021
		// Leads already on this beat+date (Day View only), to flag dupes in the picker.
1022
		LocalDate onDate = (date != null && !date.isEmpty()) ? LocalDate.parse(date) : null;
1023
		Set<Integer> alreadyOnBeat = new HashSet<>();
1024
		if (beatId != null && onDate != null) {
1025
			for (LeadRoute lr : leadRouteRepository.selectByBeatId(beatId)) {
1026
				if (onDate.equals(lr.getScheduleDate()) && !"CANCELLED".equals(lr.getStatus())) {
1027
					alreadyOnBeat.add(lr.getLeadId());
1028
				}
1029
			}
1030
		}
1031
 
1032
		// Colour-filter + dedupe, then batch-resolve approved geo (avoids N+1).
1033
		List<Lead> routable = new ArrayList<>();
1034
		Set<Integer> seen = new HashSet<>();
1035
		for (Lead lead : leads) {
1036
			if (!seen.add(lead.getId())) continue;
1037
			String color = lead.getColor() != null ? lead.getColor().toLowerCase() : "";
1038
			if (!ROUTABLE_LEAD_COLORS.contains(color)) continue;
1039
			routable.add(lead);
1040
		}
1041
		Set<Integer> withGeo = new HashSet<>();
1042
		if (!routable.isEmpty()) {
1043
			List<Integer> ids = routable.stream().map(Lead::getId).collect(Collectors.toList());
1044
			for (com.spice.profitmandi.dao.entity.user.LeadLiveLocation loc :
1045
					leadLiveLocationRepositoryAuto.selectByLeadIds(ids)) {
1046
				if (loc.getStatus() != null && "APPROVED".equals(loc.getStatus().name())) {
1047
					withGeo.add(loc.getLeadId());
1048
				}
1049
			}
1050
		}
1051
 
1052
		List<Map<String, Object>> rows = new ArrayList<>();
1053
		for (Lead lead : routable) {
1054
			Map<String, Object> m = new HashMap<>();
1055
			m.put("leadId", lead.getId());
1056
			String name = ((lead.getFirstName() != null ? lead.getFirstName() : "") + " "
1057
					+ (lead.getLastName() != null ? lead.getLastName() : "")).trim();
1058
			m.put("leadName", name.isEmpty() ? ("Lead #" + lead.getId()) : name);
1059
			m.put("outletName", lead.getOutLetName());
1060
			m.put("mobile", lead.getLeadMobile());
1061
			m.put("city", lead.getCity());
1062
			m.put("state", lead.getState());
1063
			m.put("stage", lead.getEffectiveStage() != null ? lead.getEffectiveStage().name() : "");
1064
			m.put("color", lead.getColor());
1065
			m.put("hasGeo", withGeo.contains(lead.getId()));
1066
			m.put("alreadyOnBeat", alreadyOnBeat.contains(lead.getId()));
1067
			rows.add(m);
1068
		}
1069
 
1070
		return responseSender.ok(Collections.singletonMap("rows", rows));
1071
	}
1072
 
1073
	// Shared, idempotent lead_route write. Returns true when a new row is created,
1074
	// false when the lead is already on that (beat, date). Best-effort nudges the
1075
	// lead forward to BEAT_PLANNED. Callers are responsible for the beat-runs-on-date
1076
	// and future-date guards. Mirrors deferredAssignToBeat's lead branch.
1077
	private boolean writeLeadRoute(int beatId, int leadId, LocalDate date, int approverAuthId) {
37248 vikas 1078
		return writeLeadRoute(beatId, leadId, date, approverAuthId, 9999);
1079
	}
1080
 
1081
	// As above, but with an explicit route position — used when building a Lead beat
1082
	// where the leads carry a real ordering (vs 9999 "append" for one-off attaches).
1083
	private boolean writeLeadRoute(int beatId, int leadId, LocalDate date, int approverAuthId, int sequenceOrder) {
37120 vikas 1084
		boolean exists = leadRouteRepository.selectByBeatId(beatId).stream()
1085
				.anyMatch(lr -> lr.getLeadId() == leadId
1086
						&& date.equals(lr.getScheduleDate())
1087
						&& !"CANCELLED".equals(lr.getStatus()));
1088
		if (exists) return false;
1089
 
1090
		LocalDateTime now = LocalDateTime.now();
1091
		LeadRoute lr = new LeadRoute();
1092
		lr.setBeatId(beatId);
1093
		lr.setLeadId(leadId);
1094
		lr.setScheduleDate(date);
37248 vikas 1095
		lr.setSequenceOrder(sequenceOrder);
37120 vikas 1096
		lr.setStatus("APPROVED");
1097
		lr.setApprovedBy(approverAuthId);
1098
		lr.setApprovedTimestamp(now);
1099
		lr.setCreatedTimestamp(now);
1100
		lr.setUpdatedTimestamp(now);
1101
		leadRouteRepository.persist(lr);
1102
 
1103
		advanceLeadToBeatPlanned(leadId);
1104
		return true;
1105
	}
1106
 
1107
	// Best-effort: move a lead forward to BEAT_PLANNED when it's still in an earlier
1108
	// happy-path stage. Never regresses a VISITED+ lead and never aborts the caller's
1109
	// write on failure (the legacy status is kept in sync via toLegacyStatus()).
1110
	private void advanceLeadToBeatPlanned(int leadId) {
1111
		try {
1112
			Lead lead = leadRepository.selectById(leadId);
1113
			if (lead == null) return;
1114
			com.spice.profitmandi.dao.enumuration.dtr.LeadStage cur = lead.getEffectiveStage();
1115
			boolean beforeBeatPlanned =
1116
					cur == com.spice.profitmandi.dao.enumuration.dtr.LeadStage.NEW
1117
							|| cur == com.spice.profitmandi.dao.enumuration.dtr.LeadStage.ASSIGNED
1118
							|| cur == com.spice.profitmandi.dao.enumuration.dtr.LeadStage.CONTACTED
1119
							|| cur == com.spice.profitmandi.dao.enumuration.dtr.LeadStage.QUALIFIED;
1120
			if (!beforeBeatPlanned) return;
1121
			com.spice.profitmandi.dao.enumuration.dtr.LeadStage target =
1122
					com.spice.profitmandi.dao.enumuration.dtr.LeadStage.BEAT_PLANNED;
1123
			lead.setStage(target);
1124
			lead.setStatus(target.toLegacyStatus());
1125
			lead.setUpdatedTimestamp(LocalDateTime.now());
1126
			leadRepository.persist(lead);
1127
		} catch (Exception e) {
1128
			LOGGER.warn("Could not advance lead {} to BEAT_PLANNED", leadId, e);
1129
		}
1130
	}
1131
 
1132
	// Confirm a beat actually runs on the given date.
1133
	private boolean beatRunsOnDate(int beatId, LocalDate date) {
1134
		return beatScheduleRepository.selectByBeatId(beatId).stream()
1135
				.anyMatch(s -> date.equals(s.getStartDate()));
1136
	}
1137
 
1138
	// POST /beatPlan/lead/scheduleOnBeat  {leadId, beatId, date}
1139
	// Single-lead write for the Route Planner calendar-chip handoff. Strictly-future
1140
	// date only (matches the visit-request / deferred chip flow).
1141
	@PostMapping(value = "/beatPlan/lead/scheduleOnBeat")
1142
	public ResponseEntity<?> leadScheduleOnBeat(
1143
			HttpServletRequest request,
1144
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
1145
		AuthUser me = currentUser(request);
1146
		if (me == null) return responseSender.unauthorized("Not logged in");
1147
		if (!canEditBeat(me)) return responseSender.badRequest("Scheduling a lead is restricted to L2 and above.");
1148
 
1149
		Integer beatId = body.get("beatId") != null ? ((Number) body.get("beatId")).intValue() : null;
1150
		Integer leadId = body.get("leadId") != null ? ((Number) body.get("leadId")).intValue() : null;
1151
		String dateStr = (String) body.get("date");
1152
		if (beatId == null || leadId == null || dateStr == null)
1153
			return responseSender.badRequest("leadId, beatId and date are required");
1154
 
1155
		LocalDate date;
1156
		try {
1157
			date = LocalDate.parse(dateStr);
1158
		} catch (Exception e) {
1159
			return responseSender.badRequest("Invalid date (yyyy-MM-dd)");
1160
		}
1161
		if (!date.isAfter(LocalDate.now()))
1162
			return responseSender.badRequest("Pick a future date — today is already in progress.");
1163
 
1164
		Beat beat = beatRepository.selectById(beatId);
1165
		if (beat == null) return responseSender.badRequest("Beat not found");
1166
		if (!beatRunsOnDate(beatId, date))
1167
			return responseSender.badRequest("That beat is not scheduled on " + dateStr);
1168
		if (leadRepository.selectById(leadId) == null)
1169
			return responseSender.badRequest("Lead not found");
1170
 
1171
		boolean created = writeLeadRoute(beatId, leadId, date, me.getId());
1172
 
1173
		Map<String, Object> ok = new HashMap<>();
1174
		ok.put("status", true);
1175
		ok.put("created", created);
1176
		ok.put("beatId", beatId);
1177
		ok.put("scheduleDate", date.toString());
1178
		ok.put("message", created
1179
				? "Lead added to beat '" + beat.getName() + "' on " + dateStr
1180
				: "Lead is already on that beat for " + dateStr);
1181
		return responseSender.ok(ok);
1182
	}
1183
 
1184
	// POST /beatPlan/leadsForBeat/submit  {beatId, date, leadIds:[...]}
1185
	// Bulk write for the Day View "Add Lead" modal onto a known beat+date. Allows
1186
	// today or a future date (the row's scheduled run may be today).
1187
	@PostMapping(value = "/beatPlan/leadsForBeat/submit")
1188
	public ResponseEntity<?> leadsForBeatSubmit(
1189
			HttpServletRequest request,
1190
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
1191
		AuthUser me = currentUser(request);
1192
		if (me == null) return responseSender.unauthorized("Not logged in");
1193
		if (!canEditBeat(me)) return responseSender.badRequest("Adding a lead is restricted to L2 and above.");
1194
 
1195
		Integer beatId = body.get("beatId") != null ? ((Number) body.get("beatId")).intValue() : null;
1196
		String dateStr = (String) body.get("date");
1197
		List<?> leadIdsRaw = (List<?>) body.get("leadIds");
1198
		if (beatId == null || dateStr == null || leadIdsRaw == null || leadIdsRaw.isEmpty())
1199
			return responseSender.badRequest("beatId, date and leadIds are required");
1200
 
1201
		LocalDate date;
1202
		try {
1203
			date = LocalDate.parse(dateStr);
1204
		} catch (Exception e) {
1205
			return responseSender.badRequest("Invalid date (yyyy-MM-dd)");
1206
		}
1207
		if (date.isBefore(LocalDate.now()))
1208
			return responseSender.badRequest("Pick today or a future date.");
1209
 
1210
		Beat beat = beatRepository.selectById(beatId);
1211
		if (beat == null) return responseSender.badRequest("Beat not found");
1212
		if (!beatRunsOnDate(beatId, date))
1213
			return responseSender.badRequest("That beat is not scheduled on " + dateStr);
1214
 
1215
		int added = 0, skipped = 0;
1216
		for (Object idRaw : leadIdsRaw) {
1217
			int leadId = ((Number) idRaw).intValue();
1218
			if (leadRepository.selectById(leadId) == null) {
1219
				skipped++;
1220
				continue;
1221
			}
1222
			if (writeLeadRoute(beatId, leadId, date, me.getId())) added++;
1223
			else skipped++;
1224
		}
1225
 
1226
		Map<String, Object> ok = new HashMap<>();
1227
		ok.put("status", true);
1228
		ok.put("added", added);
1229
		ok.put("skipped", skipped);
1230
		ok.put("message", added + " lead(s) added to '" + beat.getName() + "' on " + dateStr
1231
				+ (skipped > 0 ? " (" + skipped + " already present or invalid)" : ""));
1232
		return responseSender.ok(ok);
1233
	}
1234
 
1235
	// POST /beatPlan/lead/createBeatAndSchedule  {authUserId, leadId, date, beatName?}
1236
	// The "+ New beat" action — a 1-day beat with this lead as the only Day-1 stop,
1237
	// for a rep who has no beat to land on. Mirrors VisitRequestController.createBeatAndSchedule.
1238
	@PostMapping(value = "/beatPlan/lead/createBeatAndSchedule")
1239
	public ResponseEntity<?> leadCreateBeatAndSchedule(
1240
			HttpServletRequest request,
1241
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
1242
		AuthUser me = currentUser(request);
1243
		if (me == null) return responseSender.unauthorized("Not logged in");
1244
		if (!canEditBeat(me)) return responseSender.badRequest("Creating a beat is restricted to L2 and above.");
1245
 
1246
		Integer authUserId = body.get("authUserId") != null ? ((Number) body.get("authUserId")).intValue() : null;
1247
		Integer leadId = body.get("leadId") != null ? ((Number) body.get("leadId")).intValue() : null;
1248
		String dateStr = (String) body.get("date");
1249
		if (authUserId == null || leadId == null || dateStr == null)
1250
			return responseSender.badRequest("authUserId, leadId and date are required");
1251
 
1252
		LocalDate date;
1253
		try {
1254
			date = LocalDate.parse(dateStr);
1255
		} catch (Exception e) {
1256
			return responseSender.badRequest("Invalid date (yyyy-MM-dd)");
1257
		}
1258
		if (!date.isAfter(LocalDate.now()))
1259
			return responseSender.badRequest("Pick a future date — today is already in progress.");
1260
 
1261
		Lead lead = leadRepository.selectById(leadId);
1262
		if (lead == null) return responseSender.badRequest("Lead not found");
1263
 
1264
		// One-beat-per-day guard for the rep.
1265
		for (Beat existing : beatRepository.selectActiveByAuthUserId(authUserId)) {
1266
			for (BeatSchedule s : beatScheduleRepository.selectByBeatId(existing.getId())) {
1267
				if (date.equals(s.getStartDate())) {
1268
					return responseSender.badRequest("This user already has '"
1269
							+ (existing.getName() != null ? existing.getName() : "Beat #" + existing.getId())
1270
							+ "' scheduled on " + date + " — use Schedule on a beat instead.");
1271
				}
1272
			}
1273
		}
1274
 
1275
		String leadLabel = ((lead.getFirstName() != null ? lead.getFirstName() : "") + " "
1276
				+ (lead.getLastName() != null ? lead.getLastName() : "")).trim();
1277
		if (leadLabel.isEmpty()) leadLabel = "Lead #" + leadId;
1278
		Object nameRaw = body.get("beatName");
1279
		String beatName = (nameRaw != null && !nameRaw.toString().trim().isEmpty())
1280
				? nameRaw.toString().trim()
1281
				: ("Lead - " + leadLabel + " - " + date);
1282
		if (beatName.length() > 100) beatName = beatName.substring(0, 100);
1283
 
1284
		LocalDateTime now = LocalDateTime.now();
1285
		Beat beat = new Beat();
1286
		beat.setName(beatName);
1287
		beat.setAuthUserId(authUserId);
1288
		beat.setBeatColor(BEAT_COLORS[Math.abs(beatName.hashCode()) % BEAT_COLORS.length]);
1289
		beat.setTotalDays(1);
1290
		beat.setActive(true);
1291
		beat.setCreatedBy(me.getId());
1292
		beat.setCreatedTimestamp(now);
1293
		beatRepository.persist(beat);
1294
 
1295
		BeatSchedule sched = new BeatSchedule();
1296
		sched.setBeatId(beat.getId());
1297
		sched.setStartDate(date);
1298
		sched.setEndDate(date);
1299
		sched.setDayNumber(1);
1300
		sched.setEndAction("HOME");
1301
		sched.setCreatedTimestamp(now);
1302
		beatScheduleRepository.persist(sched);
1303
 
1304
		writeLeadRoute(beat.getId(), leadId, date, me.getId());
1305
 
1306
		Map<String, Object> ok = new HashMap<>();
1307
		ok.put("status", true);
1308
		ok.put("beatId", beat.getId());
1309
		ok.put("beatName", beatName);
1310
		ok.put("scheduleDate", date.toString());
1311
		ok.put("message", "Beat '" + beatName + "' created on " + dateStr);
1312
		return responseSender.ok(ok);
1313
	}
1314
 
36740 ranu 1315
	// authUserId -> dtr.users id (via shared email), memoized in the passed cache.
1316
	// Used by the reschedule action to create the new PENDING location_tracking row.
1317
	private Integer resolveDtrId(int authUserId, Map<Integer, Integer> cache) {
1318
		if (cache.containsKey(authUserId)) return cache.get(authUserId);
1319
		Integer dtrId = null;
1320
		try {
1321
			AuthUser au = authRepository.selectById(authUserId);
1322
			if (au != null && au.getEmailId() != null) {
1323
				com.spice.profitmandi.dao.entity.dtr.User u = userRepositoryAuto.selectByEmailId(au.getEmailId());
1324
				if (u != null) dtrId = u.getId();
1325
			}
1326
		} catch (Exception ignored) {
1327
		}
1328
		cache.put(authUserId, dtrId);
1329
		return dtrId;
1330
	}
1331
 
1332
	// For an auth user: fofoId -> earliest upcoming (>= today) scheduled date where
1333
	// an active beat's route still includes that partner (the "Next Scheduled" hint).
1334
	private Map<Integer, LocalDate> computeFutureCover(int authUserId) {
1335
		LocalDate today = LocalDate.now();
1336
		Map<Integer, LocalDate> cover = new HashMap<>();
1337
		for (Beat b : beatRepository.selectActiveByAuthUserId(authUserId)) {
1338
			LocalDate earliest = null;
1339
			for (BeatSchedule s : beatScheduleRepository.selectByBeatId(b.getId())) {
1340
				LocalDate dt = s.getStartDate();
1341
				if (dt != null && dt.getYear() != 9999 && !dt.isBefore(today)) {
1342
					if (earliest == null || dt.isBefore(earliest)) earliest = dt;
1343
				}
1344
			}
1345
			if (earliest == null) continue;
1346
			for (BeatRoute rt : beatRouteRepository.selectByBeatId(b.getId())) {
1347
				if (!rt.isActive()) continue;
1348
				LocalDate cur = cover.get(rt.getFofoId());
1349
				if (cur == null || earliest.isBefore(cur)) cover.put(rt.getFofoId(), earliest);
1350
			}
1351
		}
1352
		return cover;
1353
	}
1354
 
36686 ranu 1355
	@GetMapping(value = "/beatPlanWindow")
1356
	public String beatPlanWindow(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1357
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
36962 vikas 1358
		model.addAttribute("canScheduleToday", canScheduleToday(currentUser(request)));
36686 ranu 1359
		return "beat-plan-window";
36655 ranu 1360
	}
1361
 
36668 ranu 1362
	// Helpers for XLSX bulk upload
1363
	private static String readCell(org.apache.poi.ss.usermodel.Cell cell) {
1364
		if (cell == null) return null;
1365
		switch (cell.getCellType()) {
1366
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
1367
				return cell.getStringCellValue();
1368
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
1369
				if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
1370
					return cell.getDateCellValue().toInstant()
1371
							.atZone(java.time.ZoneId.systemDefault()).toLocalDate().toString();
1372
				}
1373
				double n = cell.getNumericCellValue();
1374
				return (n == Math.floor(n)) ? String.valueOf((long) n) : String.valueOf(n);
1375
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
1376
				return String.valueOf(cell.getBooleanCellValue());
1377
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA:
1378
				return cell.getCellFormula();
1379
			default:
1380
				return null;
36655 ranu 1381
		}
1382
	}
1383
 
1384
	// ====================== ONE-TIME LAT/LNG MIGRATION ======================
1385
	// For each active fofo_store, compare its stored lat/lng with the geocoded
1386
	// address lat/lng (cached in Redis). If the gap is > thresholdKm (default 5)
1387
	// OR the store has no lat/lng yet, update the store with the geocoded
1388
	// coordinates. Otherwise keep the existing values.
1389
	//
1390
	// Usage:
1391
	//   GET /beatPlan/migrateStoreLatLng              -> dry run, default 5km, all
1392
	//   GET /beatPlan/migrateStoreLatLng?apply=true   -> actually update
1393
	//   ?thresholdKm=3      -> use a different threshold
1394
	//   ?limit=100          -> process only N stores (for staged runs)
1395
	@GetMapping(value = "/beatPlan/migrateStoreLatLng")
1396
	public ResponseEntity<?> migrateStoreLatLng(
1397
			@RequestParam(required = false, defaultValue = "false") boolean apply,
1398
			@RequestParam(required = false, defaultValue = "5") double thresholdKm,
36660 ranu 1399
			@RequestParam(required = false, defaultValue = "0") int limit,
36727 ranu 1400
			@RequestParam(required = false, defaultValue = "0") int offset,
1401
			@RequestParam(required = false, defaultValue = "40") int maxSeconds) throws ProfitMandiBusinessException {
36655 ranu 1402
 
36660 ranu 1403
		List<FofoStore> all = fofoStoreRepository.selectActiveStores();
1404
		int totalAvailable = all.size();
1405
		int from = Math.max(0, Math.min(offset, totalAvailable));
36655 ranu 1406
 
36727 ranu 1407
		// Hard cap (if limit given), else go to the end of the list.
1408
		int hardTo = limit > 0 ? Math.min(from + limit, totalAvailable) : totalAvailable;
1409
 
1410
		// Time budget: stop processing once we approach the gateway timeout and
1411
		// return nextOffset so the caller can resume. Geocoding is the slow part
1412
		// (network/cache), so a fixed batch size could still time out on a cache-miss
1413
		// run — a wall-clock budget is safer. maxSeconds defaults to 40 (< typical 60s gateway).
1414
		long deadlineMs = System.currentTimeMillis() + Math.max(5, maxSeconds) * 1000L;
1415
 
1416
		List<FofoStore> stores = all.subList(from, hardTo);
36655 ranu 1417
		List<Integer> ids = stores.stream().map(FofoStore::getId).collect(Collectors.toList());
1418
		Map<Integer, CustomRetailer> retailerMap = retailerService.getFofoRetailers(ids);
1419
 
36727 ranu 1420
		int total = 0;            // stores actually processed this call
36655 ranu 1421
		int updated = 0, kept = 0, noAddress = 0, noGeocode = 0, errored = 0;
36727 ranu 1422
		boolean stoppedOnTime = false;
1423
		int nextIndex = from;     // absolute index of next unprocessed store
36655 ranu 1424
		List<Map<String, Object>> changes = new ArrayList<>();
1425
 
1426
		for (FofoStore store : stores) {
36727 ranu 1427
			// Stop before doing more slow geocoding work if we've spent our budget.
1428
			if (System.currentTimeMillis() >= deadlineMs) {
1429
				stoppedOnTime = true;
1430
				break;
1431
			}
1432
			total++;
1433
			nextIndex++;
36655 ranu 1434
			try {
1435
				CustomRetailer retailer = retailerMap.get(store.getId());
1436
				if (retailer == null || retailer.getAddress() == null) {
1437
					noAddress++;
1438
					continue;
1439
				}
1440
 
1441
				String geoAddr = com.spice.profitmandi.service.GeocodingService.buildGeoAddress(
1442
						retailer.getAddress().getLine1(), retailer.getAddress().getCity(),
1443
						retailer.getAddress().getState(), retailer.getAddress().getPinCode());
1444
				if (geoAddr == null || geoAddr.isEmpty()) {
1445
					noAddress++;
1446
					continue;
1447
				}
1448
 
1449
				double[] coords = geocodingService.geocodeAddress(geoAddr);
1450
				if (coords == null) {
1451
					noGeocode++;
1452
					continue;
1453
				}
1454
 
1455
				Double existingLat = parseDoubleOrNull(store.getLatitude());
1456
				Double existingLng = parseDoubleOrNull(store.getLongitude());
1457
 
1458
				boolean shouldUpdate;
1459
				double distKm = -1;
1460
				String reason;
1461
				if (existingLat == null || existingLng == null) {
1462
					shouldUpdate = true;
1463
					reason = "missing existing lat/lng";
1464
				} else {
1465
					distKm = haversineKm(existingLat, existingLng, coords[0], coords[1]);
1466
					shouldUpdate = distKm > thresholdKm;
1467
					reason = shouldUpdate
1468
							? "gap " + Math.round(distKm * 10.0) / 10.0 + "km > " + thresholdKm + "km"
1469
							: "gap " + Math.round(distKm * 10.0) / 10.0 + "km within " + thresholdKm + "km";
1470
				}
1471
 
1472
				if (shouldUpdate) {
1473
					if (apply) {
1474
						store.setLatitude(String.valueOf(coords[0]));
1475
						store.setLongitude(String.valueOf(coords[1]));
36727 ranu 1476
						store.setLatLngUpdatedTimestamp(LocalDateTime.now());
36655 ranu 1477
						fofoStoreRepository.persist(store);
1478
					}
1479
					updated++;
1480
					Map<String, Object> ch = new HashMap<>();
1481
					ch.put("storeId", store.getId());
1482
					ch.put("code", store.getCode());
1483
					ch.put("oldLat", existingLat);
1484
					ch.put("oldLng", existingLng);
1485
					ch.put("newLat", coords[0]);
1486
					ch.put("newLng", coords[1]);
1487
					ch.put("distKm", distKm >= 0 ? Math.round(distKm * 10.0) / 10.0 : null);
1488
					ch.put("reason", reason);
1489
					changes.add(ch);
1490
				} else {
36727 ranu 1491
					// Verified-kept: lat/lng was already within threshold. Still stamp it
1492
					// so "processed vs pending" can be told from lat_lng_updated_timestamp.
1493
					if (apply) {
1494
						store.setLatLngUpdatedTimestamp(LocalDateTime.now());
1495
						fofoStoreRepository.persist(store);
1496
					}
36655 ranu 1497
					kept++;
1498
				}
1499
			} catch (Exception e) {
1500
				errored++;
1501
				LOGGER.warn("Geocode/migrate failed for fofoId={}: {}", store.getId(), e.getMessage());
1502
			}
1503
		}
1504
 
1505
		Map<String, Object> result = new HashMap<>();
1506
		result.put("mode", apply ? "APPLIED" : "DRY RUN — pass &apply=true to actually update");
1507
		result.put("thresholdKm", thresholdKm);
36727 ranu 1508
		result.put("totalAvailable", totalAvailable);   // total active stores in DB
36660 ranu 1509
		result.put("offset", from);
36727 ranu 1510
		result.put("processed", total);                  // stores processed this call
1511
		result.put("nextOffset", nextIndex);             // resume here next call
1512
		result.put("done", nextIndex >= totalAvailable); // true when nothing left
1513
		result.put("stoppedOnTimeBudget", stoppedOnTime);// true if we paused for time, not because we finished
36655 ranu 1514
		result.put("updated", updated);
1515
		result.put("kept", kept);
1516
		result.put("noAddress", noAddress);
1517
		result.put("noGeocode", noGeocode);
1518
		result.put("errored", errored);
1519
		// Limit changes preview to avoid huge responses
1520
		result.put("changes", changes.size() > 200 ? changes.subList(0, 200) : changes);
1521
		result.put("changesShownCount", Math.min(changes.size(), 200));
1522
		return responseSender.ok(result);
1523
	}
1524
 
36651 ranu 1525
	// ====================== EDIT BEAT ======================
1526
	// Update an existing beat — name + partner stops (routes).
1527
	// Schedules are NOT touched here; manage them via calendar drag-drop.
1528
	@PostMapping(value = "/beatPlan/updateBeat")
1529
	public ResponseEntity<?> updateBeat(
1530
			HttpServletRequest request,
1531
			@RequestParam int beatId,
1532
			@RequestParam String planData) throws Exception {
1533
 
1534
		Beat beat = beatRepository.selectById(beatId);
1535
		if (beat == null) return responseSender.badRequest("Beat not found");
1536
 
36821 ranu 1537
		// Refuse edits while the beat is "live" — i.e., a schedule row covers today.
1538
		// The salesperson is already on-route; mutating the plan mid-day would
1539
		// break their location_tracking timeline. Edits resume tomorrow.
1540
		LocalDate today = LocalDate.now();
1541
		boolean runningToday = beatScheduleRepository.selectByBeatId(beatId).stream()
1542
				.anyMatch(s -> s.getStartDate() != null && s.getStartDate().equals(today));
1543
		if (runningToday) {
1544
			return responseSender.badRequest(
1545
					"This beat is scheduled to run today — editing is locked until tomorrow. "
1546
							+ "Use the Deferred panel for today's adjustments.");
1547
		}
1548
 
36651 ranu 1549
		Gson gson = new Gson();
1550
		Type type = new TypeToken<Map<String, Object>>() {
1551
		}.getType();
1552
		Map<String, Object> plan = gson.fromJson(planData, type);
1553
 
1554
		List<Map<String, Object>> days = (List<Map<String, Object>>) plan.get("days");
1555
		if (days == null || days.isEmpty()) return responseSender.badRequest("No days provided");
1556
 
1557
		// Update name if changed (and not colliding with another beat)
1558
		String newName = plan.get("beatName") != null ? ((String) plan.get("beatName")).trim() : beat.getName();
1559
		if (newName != null && !newName.equalsIgnoreCase(beat.getName())) {
36698 ranu 1560
			// Make sure no other ACTIVE beat for this user already uses this name.
1561
			// Soft-deleted beats keep their name in the table; we don't want them
1562
			// to block a legitimate rename.
1563
			boolean collides = beatRepository.selectActiveByAuthUserId(beat.getAuthUserId()).stream()
36651 ranu 1564
					.anyMatch(b -> b.getId() != beat.getId()
1565
							&& b.getName() != null
1566
							&& newName.equalsIgnoreCase(b.getName().trim()));
1567
			if (collides) return responseSender.badRequest("Another beat with this name already exists");
1568
			beat.setName(newName);
1569
		}
1570
 
1571
		// Update start location from first day if present
1572
		Map<String, Object> firstDay = days.get(0);
1573
		if (firstDay.get("startLocationName") != null)
1574
			beat.setStartLocationName((String) firstDay.get("startLocationName"));
1575
		if (firstDay.get("startLatitude") != null) beat.setStartLatitude((String) firstDay.get("startLatitude"));
1576
		if (firstDay.get("startLongitude") != null) beat.setStartLongitude((String) firstDay.get("startLongitude"));
1577
 
36681 ranu 1578
		int oldTotalDays = beat.getTotalDays();
1579
		int newTotalDays = days.size();
1580
 
1581
		// Hard rule: you cannot grow the number of days on an existing beat.
1582
		// If you need more days, create a new beat. (Shrinking is allowed and
1583
		// the schedules for dropped day numbers are cleaned below.)
1584
		if (newTotalDays > oldTotalDays) {
1585
			return responseSender.badRequest(
1586
					"Cannot increase the number of days on an existing beat. "
1587
							+ "Original: " + oldTotalDays + " day(s), tried: " + newTotalDays + " day(s). "
1588
							+ "Please create a new beat for additional days.");
1589
		}
1590
		beat.setTotalDays(newTotalDays);
1591
 
1592
		// Replace routes (partner stops). Schedules stay intact (except for
36711 ranu 1593
        // dayNumber > newTotalDays cleanup + total km/min refresh below).
36651 ranu 1594
		beatRouteRepository.deleteByBeatId(beatId);
36681 ranu 1595
		// Collect lead IDs the user kept on the plan
36651 ranu 1596
		Set<Integer> keptLeadIds = new HashSet<>();
1597
		for (int d = 0; d < days.size(); d++) {
1598
			Map<String, Object> day = days.get(d);
1599
			int dayNumber = d + 1;
1600
			List<Map<String, Object>> visits = (List<Map<String, Object>>) day.get("visits");
1601
			if (visits == null) continue;
1602
			int partnerSeq = 0;
1603
			for (int i = 0; i < visits.size(); i++) {
1604
				Map<String, Object> v = visits.get(i);
1605
				if ("lead".equals(v.get("type"))) {
1606
					keptLeadIds.add(((Number) v.get("id")).intValue());
1607
					continue; // leads live in lead_route, handled below
1608
				}
1609
				BeatRoute route = new BeatRoute();
1610
				route.setBeatId(beatId);
1611
				route.setFofoId(((Number) v.get("id")).intValue());
36811 ranu 1612
				route.setVisitType("office".equals(v.get("type"))
1613
						? com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.OFFICE
1614
						: com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.PARTNER);
36651 ranu 1615
				route.setSequenceOrder(partnerSeq++);
1616
				route.setDayNumber(dayNumber);
1617
				route.setActive(true);
36711 ranu 1618
                if (v.get("distanceFromPrevKm") != null)
1619
                    route.setDistanceFromPrevKm(((Number) v.get("distanceFromPrevKm")).doubleValue());
1620
                if (v.get("timeFromPrevMins") != null)
1621
                    route.setTimeFromPrevMins(((Number) v.get("timeFromPrevMins")).intValue());
36651 ranu 1622
				beatRouteRepository.persist(route);
1623
			}
1624
		}
1625
 
36681 ranu 1626
		// If the beat shrank, drop schedule rows for day numbers that no longer exist
1627
		if (newTotalDays < oldTotalDays) {
1628
			List<BeatSchedule> currentSchedules = beatScheduleRepository.selectByBeatId(beatId);
1629
			for (BeatSchedule s : currentSchedules) {
1630
				if (s.getDayNumber() > newTotalDays) beatScheduleRepository.delete(s);
1631
			}
1632
		}
1633
 
36711 ranu 1634
        // Refresh the day-level totals on every remaining schedule row so they
1635
        // reflect the post-edit route. Previously updateBeat left these stale
1636
        // (or NULL, for beats created before this fix), which is what the user
1637
        // reported. Keyed by dayNumber so multi-instance beats all get updated.
1638
        Map<Integer, Map<String, Object>> dayByNumber = new HashMap<>();
1639
        for (int d = 0; d < days.size(); d++) {
1640
            dayByNumber.put(d + 1, days.get(d));
1641
        }
1642
        List<BeatSchedule> allSchedules = beatScheduleRepository.selectByBeatId(beatId);
1643
        for (BeatSchedule s : allSchedules) {
1644
            Map<String, Object> day = dayByNumber.get(s.getDayNumber());
1645
            if (day == null) continue;
1646
            if (day.get("totalDistanceKm") != null)
1647
                s.setTotalDistanceKm(((Number) day.get("totalDistanceKm")).doubleValue());
1648
            if (day.get("totalTimeMins") != null)
1649
                s.setTotalTimeMins(((Number) day.get("totalTimeMins")).intValue());
1650
        }
1651
 
36681 ranu 1652
		// Process per-lead actions sent from the editor's removed-leads popup.
1653
		// Each entry: {leadId, action: "cancel"|"reschedule", toDate?: "yyyy-MM-dd"}.
1654
		// - cancel: mark the lead's current APPROVED row for this beat as CANCELLED.
1655
		// - reschedule: cancel here, then create a fresh APPROVED LeadRoute on
1656
		//   whichever beat this user has scheduled on toDate. If no beat exists
1657
		//   on toDate, the whole update fails (so the caller can prompt again).
1658
		int leadsCancelled = 0, leadsRescheduled = 0;
1659
		List<String> leadFailures = new ArrayList<>();
1660
		String removedLeadActionsJson = (String) plan.get("removedLeadActions");
1661
		if (removedLeadActionsJson != null && !removedLeadActionsJson.isEmpty()) {
1662
			Type listType = new TypeToken<List<Map<String, Object>>>() {
1663
			}.getType();
1664
			List<Map<String, Object>> actions = gson.fromJson(removedLeadActionsJson, listType);
1665
 
1666
			List<LeadRoute> beatLeads = leadRouteRepository.selectByBeatId(beatId);
1667
 
1668
			for (Map<String, Object> act : actions) {
1669
				int leadId = ((Number) act.get("leadId")).intValue();
1670
				String mode = (String) act.get("action");
1671
 
1672
				// Find this lead's most-recent APPROVED row on this beat
1673
				LeadRoute current = beatLeads.stream()
1674
						.filter(r -> r.getLeadId() == leadId && "APPROVED".equals(r.getStatus()))
1675
						.findFirst().orElse(null);
1676
				if (current == null) continue; // already removed/cancelled; nothing to do
1677
 
1678
				if ("reschedule".equalsIgnoreCase(mode)) {
1679
					String toDateStr = (String) act.get("toDate");
1680
					if (toDateStr == null || toDateStr.isEmpty()) {
1681
						leadFailures.add("Lead " + leadId + ": reschedule date missing");
1682
						continue;
1683
					}
1684
					LocalDate toDate = LocalDate.parse(toDateStr);
1685
 
1686
					// Find ANY beat this user has scheduled on toDate
1687
					Beat targetBeat = null;
1688
					Integer targetDayNumber = null;
1689
					List<Beat> userBeats = beatRepository.selectActiveByAuthUserId(beat.getAuthUserId());
1690
					for (Beat b : userBeats) {
1691
						List<BeatSchedule> sl = beatScheduleRepository.selectByBeatId(b.getId());
1692
						for (BeatSchedule s : sl) {
1693
							if (s.getStartDate() != null && s.getStartDate().equals(toDate)) {
1694
								targetBeat = b;
1695
								targetDayNumber = s.getDayNumber();
1696
								break;
1697
							}
1698
						}
1699
						if (targetBeat != null) break;
1700
					}
1701
					if (targetBeat == null) {
1702
						return responseSender.badRequest(
1703
								"No beat is scheduled for this user on " + toDateStr
1704
										+ ". Pick a different date for lead " + leadId
1705
										+ ", or choose Cancel for it.");
1706
					}
1707
 
1708
					// Cancel the current attachment to this beat
1709
					current.setStatus("CANCELLED");
1710
					current.setUpdatedTimestamp(LocalDateTime.now());
1711
 
1712
					// Create the new attachment on the target beat/date
1713
					LeadRoute fresh = new LeadRoute();
1714
					fresh.setBeatId(targetBeat.getId());
1715
					fresh.setLeadId(leadId);
1716
					fresh.setNearestStoreId(current.getNearestStoreId());
1717
					fresh.setScheduleDate(toDate);
1718
					fresh.setSequenceOrder(9999); // append; the planner can reorder
1719
					fresh.setStatus("APPROVED");
1720
					fresh.setRequestedBy(current.getRequestedBy());
1721
					fresh.setApprovedBy(current.getApprovedBy());
1722
					fresh.setApprovedTimestamp(LocalDateTime.now());
1723
					fresh.setCreatedTimestamp(LocalDateTime.now());
1724
					fresh.setUpdatedTimestamp(LocalDateTime.now());
1725
					leadRouteRepository.persist(fresh);
1726
 
1727
					LeadActivity la = new LeadActivity();
1728
					la.setLeadId(leadId);
1729
					la.setRemark("Rescheduled from beat '" + beat.getName() + "' to '"
1730
							+ targetBeat.getName() + "' on " + toDateStr + " (day " + targetDayNumber + ")");
1731
					la.setAuthId(0);
1732
					la.setCreatedTimestamp(LocalDateTime.now());
1733
					leadActivityRepositoryAuto.persist(la);
1734
					leadsRescheduled++;
1735
				} else {
1736
					// cancel (default)
1737
					current.setStatus("CANCELLED");
1738
					current.setUpdatedTimestamp(LocalDateTime.now());
1739
 
1740
					LeadActivity la = new LeadActivity();
1741
					la.setLeadId(leadId);
1742
					la.setRemark("Cancelled from beat '" + beat.getName() + "' during edit");
1743
					la.setAuthId(0);
1744
					la.setCreatedTimestamp(LocalDateTime.now());
1745
					leadActivityRepositoryAuto.persist(la);
1746
					leadsCancelled++;
36651 ranu 1747
				}
1748
			}
1749
		}
1750
 
1751
		Map<String, Object> response = new HashMap<>();
1752
		response.put("status", true);
1753
		response.put("planGroupId", String.valueOf(beat.getId()));
36681 ranu 1754
		response.put("leadsCancelled", leadsCancelled);
1755
		response.put("leadsRescheduled", leadsRescheduled);
1756
		response.put("leadFailures", leadFailures);
1757
		response.put("message", "Beat updated successfully"
1758
				+ (leadsCancelled > 0 ? " (" + leadsCancelled + " lead(s) cancelled)" : "")
1759
				+ (leadsRescheduled > 0 ? " (" + leadsRescheduled + " lead(s) rescheduled)" : ""));
36651 ranu 1760
		return responseSender.ok(response);
1761
	}
1762
 
36681 ranu 1763
	// Used by the edit-mode "removed leads" popup so the date picker can warn
1764
	// upfront when the user picks a date that has no beat for them.
1765
	@GetMapping(value = "/beatPlan/userBeatsOnDate")
1766
	public ResponseEntity<?> userBeatsOnDate(
1767
			@RequestParam int authUserId,
1768
			@RequestParam String date) {
1769
		LocalDate target;
1770
		try {
1771
			target = LocalDate.parse(date);
1772
		} catch (Exception e) {
1773
			return responseSender.badRequest("Invalid date");
1774
		}
1775
 
1776
		List<Map<String, Object>> hits = new ArrayList<>();
1777
		List<Beat> userBeats = beatRepository.selectActiveByAuthUserId(authUserId);
1778
		for (Beat b : userBeats) {
1779
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(b.getId());
1780
			for (BeatSchedule s : schedules) {
1781
				if (s.getStartDate() != null && s.getStartDate().equals(target)) {
1782
					Map<String, Object> m = new HashMap<>();
1783
					m.put("beatId", b.getId());
1784
					m.put("beatName", b.getName());
1785
					m.put("dayNumber", s.getDayNumber());
1786
					hits.add(m);
1787
				}
1788
			}
1789
		}
1790
		Map<String, Object> result = new HashMap<>();
1791
		result.put("date", date);
1792
		result.put("authUserId", authUserId);
1793
		result.put("beats", hits);
1794
		return responseSender.ok(result);
1795
	}
1796
 
36686 ranu 1797
	// ====================== BASE LOCATION MANAGEMENT ======================
1798
	// Inline page that lets Sales L3+ pick a user and set their base (home)
1799
	// location via map. Reads use the existing /beatPlan/getBaseLocation, writes
1800
	// go through the L3+-guarded endpoint below.
1801
	@GetMapping(value = "/beatPlan/baseLocationPage")
1802
	public String baseLocationPage(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1803
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
1804
		return "beat-plan-base-location";
36650 ranu 1805
	}
1806
 
1807
	// Tabular JSON: one row per (beat, scheduled date) in [startDate, endDate].
36821 ranu 1808
	// Hierarchy-scoped: a manager sees only their downline + self; super-admins see all.
1809
	// Optional categoryId + escalationType further narrow the listing to users at
1810
	// a specific level (e.g. all Sales L1 in scope).
36650 ranu 1811
	@GetMapping(value = "/beatPlan/scheduledList")
1812
	public ResponseEntity<?> scheduledList(
36821 ranu 1813
			HttpServletRequest request,
36650 ranu 1814
			@RequestParam(required = false) String startDate,
36821 ranu 1815
			@RequestParam(required = false) String endDate,
1816
			@RequestParam(required = false) Integer categoryId,
1817
			@RequestParam(required = false) com.spice.profitmandi.dao.enumuration.cs.EscalationType escalationType) throws ProfitMandiBusinessException {
36650 ranu 1818
 
1819
		LocalDate start, end;
1820
		try {
1821
			start = (startDate == null || startDate.isEmpty()) ? LocalDate.now() : LocalDate.parse(startDate);
1822
			end = (endDate == null || endDate.isEmpty()) ? start.plusDays(7) : LocalDate.parse(endDate);
1823
		} catch (Exception e) {
1824
			return responseSender.badRequest("Invalid date — expected yyyy-MM-dd");
1825
		}
1826
 
36821 ranu 1827
		// ---- Scope: which auth users does the caller get to see ----
1828
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
1829
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
1830
		Set<Integer> visible = null;
1831
		if (me != null && !isSuperAdmin(me)) {
1832
			visible = new HashSet<>(authService.getAllReportees(me.getId()));
1833
			visible.add(me.getId());
1834
		}
1835
		// If a (category, level) was picked, further restrict to that population.
1836
		Set<Integer> levelFilter = null;
1837
		if (categoryId != null && escalationType != null) {
1838
			levelFilter = csService.getAuthUserByCategoryId(categoryId, escalationType).stream()
1839
					.filter(AuthUser::getActive)
1840
					.map(AuthUser::getId)
1841
					.collect(java.util.stream.Collectors.toSet());
1842
		}
1843
 
36650 ranu 1844
		List<com.spice.profitmandi.dao.model.BeatDayDetails> beats =
1845
				beatPlanQueryService.getAllScheduledBeats(start, end);
1846
 
36821 ranu 1847
		final Set<Integer> visibleF = visible;
1848
		final Set<Integer> levelF = levelFilter;
1849
		beats = beats.stream()
1850
				.filter(b -> visibleF == null || visibleF.contains(b.getAuthUserId()))
1851
				.filter(b -> levelF == null || levelF.contains(b.getAuthUserId()))
1852
				.collect(java.util.stream.Collectors.toList());
1853
 
36650 ranu 1854
		// Resolve user names in bulk
1855
		Set<Integer> userIds = beats.stream()
1856
				.map(com.spice.profitmandi.dao.model.BeatDayDetails::getAuthUserId)
1857
				.collect(java.util.stream.Collectors.toSet());
1858
		Map<Integer, AuthUser> userMap = new HashMap<>();
1859
		if (!userIds.isEmpty()) {
1860
			authRepository.selectByIds(new ArrayList<>(userIds))
1861
					.forEach(u -> userMap.put(u.getId(), u));
1862
		}
1863
 
1864
		List<Map<String, Object>> rows = new ArrayList<>();
1865
		for (com.spice.profitmandi.dao.model.BeatDayDetails b : beats) {
1866
			AuthUser u = userMap.get(b.getAuthUserId());
1867
			Map<String, Object> row = new HashMap<>();
1868
			row.put("authUserId", b.getAuthUserId());
1869
			row.put("userName", u != null ? (u.getFirstName() + " " + u.getLastName()) : "User #" + b.getAuthUserId());
1870
			row.put("scheduleDate", b.getScheduleDate().toString());
1871
			row.put("dayNumber", b.getDayNumber());
1872
			row.put("beatId", b.getBeatId());
1873
			row.put("beatName", b.getBeatName());
1874
			row.put("beatColor", b.getBeatColor());
1875
			row.put("partnerCount", b.getPartnerStops().size());
1876
			row.put("leadCount", b.getLeadStops().size());
1877
			row.put("visitCount", b.getPartnerStops().size() + b.getLeadStops().size());
1878
			rows.add(row);
1879
		}
1880
 
1881
		Map<String, Object> result = new HashMap<>();
1882
		result.put("rows", rows);
1883
		result.put("startDate", start.toString());
1884
		result.put("endDate", end.toString());
1885
		return responseSender.ok(result);
1886
	}
1887
 
1888
	// JSON: beats running for (authUserId, date) — enriched with partner/lead names & coords
1889
	@GetMapping(value = "/beatPlan/dayViewData")
1890
	public ResponseEntity<?> beatPlanDayViewData(
1891
			@RequestParam int authUserId,
1892
			@RequestParam String date) throws ProfitMandiBusinessException {
1893
 
1894
		LocalDate localDate;
1895
		try {
1896
			localDate = LocalDate.parse(date);
1897
		} catch (Exception e) {
1898
			return responseSender.badRequest("Invalid date — expected yyyy-MM-dd");
1899
		}
1900
 
1901
		List<com.spice.profitmandi.dao.model.BeatDayDetails> beats =
1902
				beatPlanQueryService.getBeatsForUserOnDate(authUserId, localDate);
1903
 
1904
		// Collect all partner & lead IDs to fetch metadata in bulk
1905
		Set<Integer> partnerIds = new HashSet<>();
1906
		Set<Integer> leadIds = new HashSet<>();
1907
		for (com.spice.profitmandi.dao.model.BeatDayDetails b : beats) {
1908
			b.getPartnerStops().forEach(s -> partnerIds.add((Integer) s.get("fofoId")));
1909
			b.getLeadStops().forEach(s -> leadIds.add((Integer) s.get("leadId")));
1910
		}
1911
 
1912
		// Partners: name + geocoded lat/lng (geocoder is cached in Redis)
1913
		Map<Integer, CustomRetailer> retailerMap = partnerIds.isEmpty()
1914
				? new HashMap<>()
1915
				: retailerService.getFofoRetailers(new ArrayList<>(partnerIds));
1916
		Map<Integer, FofoStore> storeMap = new HashMap<>();
1917
		if (!partnerIds.isEmpty()) {
1918
			fofoStoreRepository.selectByRetailerIds(new ArrayList<>(partnerIds))
1919
					.forEach(fs -> storeMap.put(fs.getId(), fs));
1920
		}
1921
 
1922
		// Leads: name + geo
1923
		Map<Integer, com.spice.profitmandi.dao.entity.user.Lead> leadMap = new HashMap<>();
1924
		Map<Integer, com.spice.profitmandi.dao.entity.user.LeadLiveLocation> leadGeoMap = new HashMap<>();
1925
		for (int leadId : leadIds) {
1926
			com.spice.profitmandi.dao.entity.user.Lead l = leadRepository.selectById(leadId);
1927
			if (l != null) leadMap.put(leadId, l);
1928
			com.spice.profitmandi.dao.entity.user.LeadLiveLocation lg =
1929
					leadLiveLocationRepositoryAuto.selectApprovedByLeadId(leadId);
1930
			if (lg != null) leadGeoMap.put(leadId, lg);
1931
		}
1932
 
1933
		// Enrich each stop
1934
		List<Map<String, Object>> out = new ArrayList<>();
1935
		for (com.spice.profitmandi.dao.model.BeatDayDetails b : beats) {
1936
			Map<String, Object> beatJson = new HashMap<>();
1937
			beatJson.put("beatId", b.getBeatId());
1938
			beatJson.put("beatName", b.getBeatName());
1939
			beatJson.put("beatColor", b.getBeatColor());
1940
			beatJson.put("dayNumber", b.getDayNumber());
1941
			beatJson.put("scheduleDate", b.getScheduleDate().toString());
1942
			beatJson.put("endAction", b.getEndAction());
1943
			beatJson.put("totalDistanceKm", b.getTotalDistanceKm());
1944
			beatJson.put("totalTimeMins", b.getTotalTimeMins());
1945
			beatJson.put("startLocationName", b.getStartLocationName());
1946
			beatJson.put("startLatitude", b.getStartLatitude());
1947
			beatJson.put("startLongitude", b.getStartLongitude());
1948
 
1949
			List<Map<String, Object>> stops = new ArrayList<>();
1950
			// Partners
1951
			for (Map<String, Object> ps : b.getPartnerStops()) {
1952
				int fofoId = (Integer) ps.get("fofoId");
1953
				Map<String, Object> stop = new HashMap<>();
1954
				stop.put("type", "partner");
1955
				stop.put("id", fofoId);
1956
				stop.put("sequenceOrder", ps.get("sequenceOrder"));
1957
				FofoStore fs = storeMap.get(fofoId);
1958
				CustomRetailer cr = retailerMap.get(fofoId);
1959
				stop.put("code", fs != null ? fs.getCode() : null);
1960
				stop.put("name", fs != null && fs.getOutletName() != null ? fs.getOutletName()
1961
						: (cr != null ? cr.getBusinessName() : "Store #" + fofoId));
36655 ranu 1962
				// Use FofoStore lat/lng directly (no geocoding needed after migration)
1963
				if (fs != null && fs.getLatitude() != null && fs.getLongitude() != null
1964
						&& !fs.getLatitude().isEmpty() && !fs.getLongitude().isEmpty()) {
36650 ranu 1965
					try {
36655 ranu 1966
						stop.put("lat", Double.parseDouble(fs.getLatitude()));
1967
						stop.put("lng", Double.parseDouble(fs.getLongitude()));
1968
					} catch (NumberFormatException ignored) {
36650 ranu 1969
					}
1970
				}
36655 ranu 1971
				if (cr != null && cr.getAddress() != null) {
1972
					stop.put("address", cr.getAddress().getAddressString());
1973
				}
36650 ranu 1974
				stops.add(stop);
1975
			}
1976
			// Leads
1977
			for (Map<String, Object> ls : b.getLeadStops()) {
1978
				int leadId = (Integer) ls.get("leadId");
1979
				Map<String, Object> stop = new HashMap<>();
1980
				stop.put("type", "lead");
1981
				stop.put("id", leadId);
1982
				stop.put("sequenceOrder", ls.get("sequenceOrder"));
1983
				stop.put("nearestStoreId", ls.get("nearestStoreId"));
1984
				com.spice.profitmandi.dao.entity.user.Lead l = leadMap.get(leadId);
1985
				stop.put("name", l != null ? l.getFirstName() + " " + l.getLastName() : "Lead #" + leadId);
1986
				stop.put("mobile", l != null ? l.getLeadMobile() : null);
1987
				stop.put("city", l != null ? l.getCity() : null);
1988
				com.spice.profitmandi.dao.entity.user.LeadLiveLocation lg = leadGeoMap.get(leadId);
1989
				if (lg != null) {
1990
					stop.put("lat", lg.getLatitude());
1991
					stop.put("lng", lg.getLongitude());
1992
				}
1993
				stops.add(stop);
1994
			}
1995
			beatJson.put("stops", stops);
1996
			beatJson.put("partnerCount", b.getPartnerStops().size());
1997
			beatJson.put("leadCount", b.getLeadStops().size());
1998
			out.add(beatJson);
1999
		}
2000
 
2001
		Map<String, Object> result = new HashMap<>();
2002
		result.put("beats", out);
2003
		return responseSender.ok(result);
2004
	}
2005
 
36686 ranu 2006
	// ====================== DAY VIEW ======================
2007
	// Inline page (loaded into dashboard #main-content): tabular list of all beats
2008
	// scheduled in a date range across all users. Each row has a View button that
2009
	// opens that user's calendar in a modal.
2010
	@GetMapping(value = "/beatPlan/dayView")
2011
	public String beatPlanDayView(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
2012
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
36821 ranu 2013
		// Matches /beatPlan/getAuthUsers and the Beat Report — default Sales category.
2014
		model.addAttribute("categoryId", com.spice.profitmandi.common.model.ProfitMandiConstants.TICKET_CATEGORY_SALES);
36962 vikas 2015
		model.addAttribute("canEditBeat", canEditBeat(currentUser(request)));
36686 ranu 2016
		return "beat-plan-day-view";
36618 ranu 2017
	}
2018
 
36644 ranu 2019
	// Returns visits for a beat.
2020
	// - Partner stops (beat_route) belong to the beat template — always returned.
2021
	// - Lead stops (lead_route) belong to a specific run — returned ONLY when planDate
2022
	//   is given and matches the lead's schedule_date. (No planDate = template view.)
36632 ranu 2023
	@GetMapping(value = "/beatPlan/getBeatVisits")
36644 ranu 2024
	public ResponseEntity<?> getBeatVisits(
2025
			@RequestParam String planGroupId,
2026
			@RequestParam(required = false) String planDate) {
2027
 
2028
		int beatId;
2029
		try {
2030
			beatId = Integer.parseInt(planGroupId);
2031
		} catch (NumberFormatException e) {
2032
			return responseSender.ok(new ArrayList<>());
2033
		}
2034
 
2035
		List<BeatRoute> routes = beatRouteRepository.selectByBeatId(beatId);
2036
		List<Map<String, Object>> result = new ArrayList<>();
2037
 
36811 ranu 2038
		// Stops — partner OR office, dispatched by visit_type. Partners are
2039
		// enriched on the client from the partner map (already in scope);
2040
		// offices are enriched here because the client has no office map.
36644 ranu 2041
		for (BeatRoute r : routes) {
36632 ranu 2042
			Map<String, Object> map = new HashMap<>();
36644 ranu 2043
			map.put("fofoId", r.getFofoId());
2044
			map.put("dayNumber", r.getDayNumber());
2045
			map.put("sequenceOrder", r.getSequenceOrder());
36811 ranu 2046
			if (r.getVisitType() == com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.OFFICE) {
2047
				map.put("visitType", "office");
2048
				try {
2049
					com.spice.profitmandi.dao.entity.logistics.CompanyOffice o =
2050
							companyOfficeRepository.selectById(r.getFofoId());
2051
					if (o != null) {
2052
						map.put("code", o.getCode());
2053
						map.put("name", o.getName());
2054
						map.put("latitude", String.valueOf(o.getLat()));
2055
						map.put("longitude", String.valueOf(o.getLng()));
2056
					}
2057
				} catch (Exception ignored) {
2058
				}
2059
			} else {
2060
				map.put("visitType", "partner");
2061
			}
36644 ranu 2062
			result.add(map);
2063
		}
2064
 
2065
		// Lead stops — only for the requested run date
2066
		if (planDate != null && !planDate.isEmpty()) {
2067
			LocalDate date = LocalDate.parse(planDate);
2068
			List<LeadRoute> leads = leadRouteRepository.selectByBeatId(beatId);
2069
			for (LeadRoute lr : leads) {
2070
				if ("APPROVED".equals(lr.getStatus())
2071
						&& lr.getScheduleDate() != null
2072
						&& lr.getScheduleDate().equals(date)) {
2073
					Map<String, Object> map = new HashMap<>();
2074
					map.put("fofoId", lr.getLeadId());
2075
					map.put("dayNumber", 1);
2076
					map.put("sequenceOrder", lr.getSequenceOrder() != null ? lr.getSequenceOrder() : 999);
2077
					map.put("visitType", "lead");
2078
					result.add(map);
2079
				}
2080
			}
2081
		}
2082
 
2083
		// Sort by dayNumber then sequenceOrder
2084
		result.sort((a, b) -> {
2085
			int cmp = Integer.compare((int) a.get("dayNumber"), (int) b.get("dayNumber"));
2086
			return cmp != 0 ? cmp : Integer.compare((int) a.get("sequenceOrder"), (int) b.get("sequenceOrder"));
2087
		});
2088
 
36632 ranu 2089
		return responseSender.ok(result);
2090
	}
2091
 
36681 ranu 2092
	// Returns the user's DEFAULT base location. Falls back to most-recent for
2093
	// legacy users who pre-date the is_default column.
36618 ranu 2094
	@GetMapping(value = "/beatPlan/getBaseLocation")
2095
	public ResponseEntity<?> getBaseLocation(@RequestParam int authUserId) {
36681 ranu 2096
		AuthUserLocation baseLoc = authUserLocationRepository.selectDefaultByAuthUserIdAndType(authUserId, "BASE");
36618 ranu 2097
		if (baseLoc == null) {
2098
			return responseSender.ok(new HashMap<>());
2099
		}
2100
		Map<String, Object> result = new HashMap<>();
2101
		result.put("id", baseLoc.getId());
2102
		result.put("locationName", baseLoc.getLocationName());
2103
		result.put("latitude", baseLoc.getLatitude());
2104
		result.put("longitude", baseLoc.getLongitude());
2105
		result.put("address", baseLoc.getAddress());
36681 ranu 2106
		result.put("isDefault", baseLoc.isDefault());
36618 ranu 2107
		return responseSender.ok(result);
2108
	}
2109
 
36681 ranu 2110
	// Returns ALL BASE locations for a user, default first.
2111
	@GetMapping(value = "/beatPlan/listBaseLocations")
2112
	public ResponseEntity<?> listBaseLocations(@RequestParam int authUserId) {
2113
		List<AuthUserLocation> all = authUserLocationRepository.selectAllByAuthUserIdAndType(authUserId, "BASE");
2114
		// Default at the top, then by created desc (the repo already returns desc).
2115
		all.sort((a, b) -> {
2116
			if (a.isDefault() && !b.isDefault()) return -1;
2117
			if (!a.isDefault() && b.isDefault()) return 1;
2118
			return 0;
2119
		});
2120
		List<Map<String, Object>> rows = new ArrayList<>();
2121
		for (AuthUserLocation l : all) {
2122
			Map<String, Object> row = new HashMap<>();
2123
			row.put("id", l.getId());
2124
			row.put("locationName", l.getLocationName());
2125
			row.put("latitude", l.getLatitude());
2126
			row.put("longitude", l.getLongitude());
2127
			row.put("address", l.getAddress());
2128
			row.put("isDefault", l.isDefault());
2129
			row.put("createdTimestamp", l.getCreatedTimestamp() != null ? l.getCreatedTimestamp().toString() : null);
2130
			rows.add(row);
2131
		}
2132
		Map<String, Object> result = new HashMap<>();
2133
		result.put("authUserId", authUserId);
2134
		result.put("locations", rows);
2135
		return responseSender.ok(result);
2136
	}
2137
 
2138
	// Flip the default flag — set this id default, clear all others.
2139
	@PostMapping(value = "/beatPlan/setDefaultBaseLocation")
2140
	public ResponseEntity<?> setDefaultBaseLocation(
2141
			HttpServletRequest request,
2142
			@RequestParam int id) throws ProfitMandiBusinessException {
2143
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
2144
		AuthUser me = authRepository.selectByEmailOrMobile(ld.getEmailId());
2145
		if (me == null) return responseSender.unauthorized("Not logged in");
2146
		if (!isBaseLocationManager(me)) {
2147
			return responseSender.forbidden("You are not authorized for this action. Only Sales L3 and above can manage base locations.");
2148
		}
2149
 
2150
		AuthUserLocation target = authUserLocationRepository.selectById(id);
2151
		if (target == null) return responseSender.badRequest("Location not found");
2152
 
2153
		List<AuthUserLocation> all = authUserLocationRepository.selectAllByAuthUserIdAndType(target.getAuthUserId(), "BASE");
2154
		for (AuthUserLocation l : all) {
2155
			boolean shouldBeDefault = (l.getId() == id);
2156
			if (l.isDefault() != shouldBeDefault) {
2157
				l.setDefault(shouldBeDefault);
2158
				authUserLocationRepository.persist(l); // saveOrUpdate
2159
			}
2160
		}
2161
 
2162
		Map<String, Object> result = new HashMap<>();
2163
		result.put("status", true);
2164
		result.put("id", id);
2165
		result.put("message", "Default base location updated");
2166
		return responseSender.ok(result);
2167
	}
2168
 
2169
	// Delete a base location. The DEFAULT one cannot be deleted — user must
2170
	// first pick another row as default.
2171
	@PostMapping(value = "/beatPlan/deleteBaseLocation")
2172
	public ResponseEntity<?> deleteBaseLocation(
2173
			HttpServletRequest request,
2174
			@RequestParam int id) throws ProfitMandiBusinessException {
2175
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
2176
		AuthUser me = authRepository.selectByEmailOrMobile(ld.getEmailId());
2177
		if (me == null) return responseSender.unauthorized("Not logged in");
2178
		if (!isBaseLocationManager(me)) {
2179
			return responseSender.forbidden("You are not authorized for this action. Only Sales L3 and above can manage base locations.");
2180
		}
2181
 
2182
		AuthUserLocation target = authUserLocationRepository.selectById(id);
2183
		if (target == null) return responseSender.badRequest("Location not found");
2184
		if (target.isDefault()) {
2185
			return responseSender.badRequest("Default base location cannot be removed. Set another location as default first.");
2186
		}
2187
 
2188
		authUserLocationRepository.delete(target);
2189
 
2190
		Map<String, Object> result = new HashMap<>();
2191
		result.put("status", true);
2192
		result.put("message", "Base location removed");
2193
		return responseSender.ok(result);
2194
	}
2195
 
36686 ranu 2196
	@GetMapping(value = "/beatPlan/getAuthUsers")
2197
	public ResponseEntity<?> getAuthUsers(
2198
			HttpServletRequest request,
2199
			@RequestParam int categoryId,
2200
			@RequestParam EscalationType escalationType) throws ProfitMandiBusinessException {
2201
 
2202
		// Hierarchy filter: a manager only sees users in their downline
2203
		// (themselves + every reportee under them, recursively). Super-admin
2204
		// emails bypass the filter and see everyone. Downline is computed by
2205
		// AuthService.getAllReportees (existing recursive walker).
2206
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
2207
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
2208
 
2209
		final Set<Integer> visible;
2210
		if (me == null || isSuperAdmin(me)) {
2211
			visible = null; // null = no filter
2212
		} else {
2213
			visible = new HashSet<>(authService.getAllReportees(me.getId()));
2214
			visible.add(me.getId()); // include self
2215
		}
2216
 
2217
		List<AuthUser> authUsers = csService.getAuthUserByCategoryId(categoryId, escalationType);
2218
		List<Map<String, Object>> result = authUsers.stream()
2219
				.filter(au -> au.getActive())
2220
				.filter(au -> visible == null || visible.contains(au.getId()))
2221
				.map(au -> {
2222
					Map<String, Object> map = new HashMap<>();
2223
					map.put("id", au.getId());
2224
					map.put("name", au.getFirstName() + " " + au.getLastName());
2225
					return map;
2226
				})
2227
				.collect(Collectors.toList());
2228
		return responseSender.ok(result);
2229
	}
2230
 
2231
	private boolean isSuperAdmin(AuthUser me) {
36681 ranu 2232
		String myEmail = me.getEmailId() != null ? me.getEmailId().toLowerCase() : "";
36686 ranu 2233
		return SUPER_ADMIN_EMAILS.contains(myEmail);
2234
	}
36681 ranu 2235
 
36686 ranu 2236
	// Returns the user's highest escalation level across all positions.
2237
	// Mirrors OrderController.getSalesEscalationLevel but category-agnostic.
2238
	private EscalationType getHighestEscalation(int authUserId) {
2239
		EscalationType highest = null;
2240
		List<com.spice.profitmandi.dao.entity.cs.Position> positions = positionRepository.selectPositionByAuthId(authUserId);
2241
		for (com.spice.profitmandi.dao.entity.cs.Position p : positions) {
2242
			if (highest == null || p.getEscalationType().isGreaterThanEqualTo(highest)) {
2243
				highest = p.getEscalationType();
2244
			}
2245
		}
2246
		return highest;
2247
	}
2248
 
2249
	// Returns the escalation levels a user can manage — strictly below their own.
2250
	// L3 → [L1, L2]; L4 → [L1, L2, L3]; Final → all levels. Super-admin → all levels.
2251
	private List<EscalationType> getVisibleEscalationLevels(AuthUser me) {
2252
		if (isSuperAdmin(me)) return EscalationType.escalations;
2253
		EscalationType mine = getHighestEscalation(me.getId());
2254
		if (mine == null) return java.util.Collections.emptyList();
2255
		List<EscalationType> below = new ArrayList<>();
2256
		for (EscalationType e : EscalationType.escalations) {
2257
			if (mine.isGreaterThanEqualTo(e) && !e.equals(mine)) below.add(e);
2258
		}
2259
		return below;
2260
	}
2261
 
36962 vikas 2262
	private AuthUser currentUser(HttpServletRequest request) throws ProfitMandiBusinessException {
2263
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
2264
		return (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
2265
	}
2266
 
36686 ranu 2267
	private List<EscalationType> visibleLevelsFor(HttpServletRequest request) throws ProfitMandiBusinessException {
36962 vikas 2268
		AuthUser me = currentUser(request);
36686 ranu 2269
		return me == null ? java.util.Collections.emptyList() : getVisibleEscalationLevels(me);
2270
	}
2271
 
36962 vikas 2272
	// Same-day scheduling is restricted to L4+ operators (or super-admin). Everyone
2273
	// else can only schedule beats for future dates.
2274
	private boolean canScheduleToday(AuthUser me) {
2275
		if (me == null) return false;
2276
		if (isSuperAdmin(me)) return true;
2277
		EscalationType lvl = getHighestEscalation(me.getId());
2278
		return lvl != null && lvl.isGreaterThanEqualTo(EscalationType.L4);
2279
	}
2280
 
2281
	// Editing a beat / assigning a visit from the day-view is restricted to L2 and
2282
	// above (or super-admin). L1 executives can view but not edit.
2283
	private boolean canEditBeat(AuthUser me) {
2284
		if (me == null) return false;
2285
		if (isSuperAdmin(me)) return true;
2286
		EscalationType lvl = getHighestEscalation(me.getId());
2287
		return lvl != null && lvl.isGreaterThanEqualTo(EscalationType.L2);
2288
	}
2289
 
36686 ranu 2290
	// Shared permission check for base-location admin actions: Sales L3+ OR super-admin.
2291
	private boolean isBaseLocationManager(AuthUser me) {
2292
		if (isSuperAdmin(me)) return true;
36681 ranu 2293
		return csService.getAuthUserIds(
2294
						com.spice.profitmandi.common.model.ProfitMandiConstants.TICKET_CATEGORY_SALES,
2295
						Arrays.asList(EscalationType.L3, EscalationType.L4))
2296
				.stream().anyMatch(u -> u.getId() == me.getId());
2297
	}
2298
 
36618 ranu 2299
	@PostMapping(value = "/beatPlan/saveBaseLocation")
2300
	public ResponseEntity<?> saveBaseLocation(
2301
			@RequestParam int authUserId,
2302
			@RequestParam String locationName,
2303
			@RequestParam String latitude,
2304
			@RequestParam String longitude,
2305
			@RequestParam(required = false) String address) {
2306
		AuthUserLocation loc = new AuthUserLocation();
2307
		loc.setAuthUserId(authUserId);
2308
		loc.setLocationType("BASE");
2309
		loc.setLocationName(locationName);
2310
		loc.setLatitude(latitude);
2311
		loc.setLongitude(longitude);
2312
		loc.setAddress(address);
2313
		loc.setCreatedTimestamp(LocalDateTime.now());
36681 ranu 2314
 
2315
		// First BASE for this user → auto-default so every user always has one.
2316
		List<AuthUserLocation> existing = authUserLocationRepository.selectAllByAuthUserIdAndType(authUserId, "BASE");
2317
		boolean noExistingDefault = existing.stream().noneMatch(AuthUserLocation::isDefault);
2318
		loc.setDefault(existing.isEmpty() || noExistingDefault);
36618 ranu 2319
		authUserLocationRepository.persist(loc);
2320
 
2321
		Map<String, Object> result = new HashMap<>();
2322
		result.put("status", true);
2323
		result.put("id", loc.getId());
36681 ranu 2324
		result.put("isDefault", loc.isDefault());
36618 ranu 2325
		return responseSender.ok(result);
2326
	}
2327
 
2328
	@GetMapping(value = "/beatPlan/getPartners")
2329
	public ResponseEntity<?> getPartners(
2330
			@RequestParam int authUserId,
2331
			@RequestParam int categoryId,
2332
			@RequestParam(required = false) String startLat,
2333
			@RequestParam(required = false) String startLng) throws ProfitMandiBusinessException {
2334
 
36802 ranu 2335
		// Beat planning needs every partner ever assigned — inactive ones included —
2336
		// so the planner can keep building beats around a partner that was paused
2337
		// after the assignment was made. The closed-store skip happens below per row.
2338
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdAllPartnerIdMapping();
36618 ranu 2339
		List<Integer> fofoIds = pp.get(authUserId);
2340
 
36644 ranu 2341
		if (fofoIds == null || fofoIds.isEmpty()) {
36618 ranu 2342
			Map<String, Object> empty = new HashMap<>();
2343
			empty.put("partners", new ArrayList<>());
2344
			return responseSender.ok(empty);
2345
		}
2346
 
2347
		List<FofoStore> fofoStores = fofoStoreRepository.selectByRetailerIds(fofoIds);
2348
		Map<Integer, CustomRetailer> retailerMap = retailerService.getFofoRetailers(fofoIds);
2349
 
2350
		List<Map<String, Object>> partners = new ArrayList<>();
2351
 
2352
		for (FofoStore store : fofoStores) {
36802 ranu 2353
			// Closed partners are gone for good — skip. Inactive ones are kept
2354
			// so the planner can still drop a beat onto them (the assignment
2355
			// pre-dates the deactivation); the UI tags them visually.
2356
			if (store.isClosed()) continue;
36618 ranu 2357
			CustomRetailer retailer = retailerMap.get(store.getId());
2358
 
2359
			Map<String, Object> partnerData = new HashMap<>();
2360
			partnerData.put("fofoId", store.getId());
2361
			partnerData.put("code", store.getCode());
2362
			partnerData.put("outletName", store.getOutletName());
36802 ranu 2363
			partnerData.put("active", store.isActive());
36618 ranu 2364
			partnerData.put("type", "partner");
2365
 
36655 ranu 2366
			// Use FofoStore lat/lng directly (migrated from address geocode)
2367
			if (store.getLatitude() != null && !store.getLatitude().isEmpty()
2368
					&& store.getLongitude() != null && !store.getLongitude().isEmpty()) {
2369
				partnerData.put("latitude", store.getLatitude());
2370
				partnerData.put("longitude", store.getLongitude());
2371
			}
2372
 
36618 ranu 2373
			if (retailer != null) {
2374
				partnerData.put("businessName", retailer.getBusinessName());
2375
				if (retailer.getAddress() != null) {
36644 ranu 2376
					partnerData.put("address", retailer.getAddress().getAddressString());
36618 ranu 2377
				}
2378
			}
2379
			partners.add(partnerData);
2380
		}
2381
 
2382
		if (startLat != null && startLng != null && !startLat.isEmpty() && !startLng.isEmpty()) {
2383
			partners = sortByNearestNeighborFromStart(partners, Double.parseDouble(startLat), Double.parseDouble(startLng));
2384
		} else {
2385
			partners = sortByNearestNeighbor(partners);
2386
		}
2387
 
2388
		Map<String, Object> response = new HashMap<>();
2389
		response.put("partners", partners);
2390
		return responseSender.ok(response);
2391
	}
2392
 
2393
	@PostMapping(value = "/beatPlan/submitPlan")
2394
	public ResponseEntity<?> submitPlan(
2395
			HttpServletRequest request,
2396
			@RequestParam int authUserId,
2397
			@RequestParam String planData) throws Exception {
2398
 
2399
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2400
		AuthUser currentUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
2401
 
2402
		Gson gson = new Gson();
2403
		Type type = new TypeToken<Map<String, Object>>() {
2404
		}.getType();
2405
		Map<String, Object> plan = gson.fromJson(planData, type);
2406
 
2407
		List<Map<String, Object>> days = (List<Map<String, Object>>) plan.get("days");
2408
		List<String> dates = (List<String>) plan.get("dates");
2409
 
36644 ranu 2410
		String beatName = (plan.get("beatName") != null ? (String) plan.get("beatName") : "Beat").trim();
36618 ranu 2411
 
36698 ranu 2412
		// Duplicate check — same name + same authUserId among ACTIVE beats only.
2413
		// Soft-deleted beats keep the name in the table; we don't want them to
2414
		// block the user from reusing a name they "deleted".
2415
		List<Beat> existingBeats = beatRepository.selectActiveByAuthUserId(authUserId);
36644 ranu 2416
		for (Beat existing : existingBeats) {
2417
			if (existing.getName() != null && beatName.equalsIgnoreCase(existing.getName().trim())) {
2418
				LOGGER.info("Duplicate beat blocked: name='{}' authUserId={} existingId={}", beatName, authUserId, existing.getId());
36618 ranu 2419
				Map<String, Object> response = new HashMap<>();
2420
				response.put("status", true);
36644 ranu 2421
				response.put("planGroupId", String.valueOf(existing.getId()));
36618 ranu 2422
				response.put("duplicate", true);
36644 ranu 2423
				response.put("message", "Beat '" + beatName + "' already exists");
36618 ranu 2424
				return responseSender.ok(response);
2425
			}
2426
		}
2427
 
36644 ranu 2428
		String beatColor = BEAT_COLORS[Math.abs(beatName.hashCode()) % BEAT_COLORS.length];
2429
		int totalDays = days.size();
36618 ranu 2430
 
36785 ranu 2431
		// One-beat-per-day guard: reject if any of the requested dates already
2432
		// has a beat scheduled for this user.
2433
		if (dates != null) {
2434
			List<LocalDate> candidateDates = new ArrayList<>();
2435
			for (String dStr : dates) {
2436
				if (dStr != null && !dStr.isEmpty()) {
2437
					try {
2438
						candidateDates.add(LocalDate.parse(dStr, DateTimeFormatter.ISO_DATE));
2439
					} catch (Exception ignored) {
2440
					}
2441
				}
2442
			}
2443
			Map<String, Object> conflict = findScheduleConflict(authUserId, candidateDates, 0);
2444
			if (conflict != null) return responseSender.badRequest(scheduleConflictMessage(conflict));
2445
		}
2446
 
36644 ranu 2447
		// Create Beat master
2448
		Beat beat = new Beat();
2449
		beat.setName(beatName);
2450
		beat.setAuthUserId(authUserId);
2451
		beat.setBeatColor(beatColor);
2452
		beat.setTotalDays(totalDays);
2453
		beat.setActive(true);
2454
		beat.setCreatedBy(currentUser.getId());
2455
		beat.setCreatedTimestamp(LocalDateTime.now());
2456
 
2457
		// Set start location from first day
2458
		if (!days.isEmpty()) {
2459
			Map<String, Object> firstDay = days.get(0);
2460
			beat.setStartLocationName((String) firstDay.get("startLocationName"));
2461
			beat.setStartLatitude((String) firstDay.get("startLatitude"));
2462
			beat.setStartLongitude((String) firstDay.get("startLongitude"));
2463
		}
2464
		beatRepository.persist(beat);
2465
 
2466
		// End date of the whole beat = last scheduled day's date
2467
		LocalDate beatEndDate = null;
2468
		if (dates != null) {
2469
			for (int d = dates.size() - 1; d >= 0; d--) {
2470
				if (dates.get(d) != null) {
2471
					beatEndDate = LocalDate.parse(dates.get(d), DateTimeFormatter.ISO_DATE);
2472
					break;
2473
				}
2474
			}
2475
		}
2476
 
2477
		// Create routes and schedules for each day
36618 ranu 2478
		for (int d = 0; d < days.size(); d++) {
2479
			Map<String, Object> day = days.get(d);
2480
			int dayNumber = d + 1;
2481
			LocalDate planDate = (dates != null && d < dates.size() && dates.get(d) != null)
36644 ranu 2482
					? LocalDate.parse(dates.get(d), DateTimeFormatter.ISO_DATE) : null;
36618 ranu 2483
 
36644 ranu 2484
			// Auto-determine end action: last day = HOME, others = DAYBREAK
2485
			String endAction = (String) day.get("endAction");
2486
			if (endAction == null || endAction.isEmpty()) {
2487
				endAction = (dayNumber == totalDays) ? "HOME" : "DAYBREAK";
36618 ranu 2488
			}
2489
 
36644 ranu 2490
			// Always create schedule (even if planDate is null — unscheduled beat)
2491
			BeatSchedule schedule = new BeatSchedule();
2492
			schedule.setBeatId(beat.getId());
2493
			schedule.setStartDate(planDate != null ? planDate : LocalDate.of(9999, 12, 31)); // placeholder for unscheduled
2494
			schedule.setEndDate(beatEndDate);
2495
			schedule.setDayNumber(dayNumber);
2496
			schedule.setEndAction(endAction);
2497
			schedule.setStayLocationName((String) day.get("stayLocationName"));
2498
			schedule.setStayLatitude((String) day.get("stayLatitude"));
2499
			schedule.setStayLongitude((String) day.get("stayLongitude"));
2500
			if (day.get("totalDistanceKm") != null)
2501
				schedule.setTotalDistanceKm(((Number) day.get("totalDistanceKm")).doubleValue());
2502
			if (day.get("totalTimeMins") != null)
2503
				schedule.setTotalTimeMins(((Number) day.get("totalTimeMins")).intValue());
2504
			schedule.setCreatedTimestamp(LocalDateTime.now());
2505
			beatScheduleRepository.persist(schedule);
2506
 
36711 ranu 2507
            // Routes (stops) — also persist per-leg distance/time supplied by the
2508
            // client so reports/dashboards don't have to recompute from lat/lng.
36618 ranu 2509
			List<Map<String, Object>> visits = (List<Map<String, Object>>) day.get("visits");
2510
			if (visits != null) {
2511
				for (int i = 0; i < visits.size(); i++) {
2512
					Map<String, Object> visit = visits.get(i);
37248 vikas 2513
					// Lead stop → lead_route (separate table, keyed by scheduleDate).
2514
					// planDate is guaranteed non-null for lead visits (validated above).
2515
					if ("lead".equals(visit.get("type"))) {
2516
						int leadId = ((Number) visit.get("id")).intValue();
2517
						writeLeadRoute(beat.getId(), leadId, planDate, currentUser.getId(), i);
2518
						continue;
2519
					}
36644 ranu 2520
					BeatRoute route = new BeatRoute();
2521
					route.setBeatId(beat.getId());
2522
					route.setFofoId(((Number) visit.get("id")).intValue());
36811 ranu 2523
					route.setVisitType("office".equals(visit.get("type"))
2524
							? com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.OFFICE
2525
							: com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.PARTNER);
36644 ranu 2526
					route.setSequenceOrder(i);
2527
					route.setDayNumber(dayNumber);
2528
					route.setActive(true);
36711 ranu 2529
                    if (visit.get("distanceFromPrevKm") != null)
2530
                        route.setDistanceFromPrevKm(((Number) visit.get("distanceFromPrevKm")).doubleValue());
2531
                    if (visit.get("timeFromPrevMins") != null)
2532
                        route.setTimeFromPrevMins(((Number) visit.get("timeFromPrevMins")).intValue());
36644 ranu 2533
					beatRouteRepository.persist(route);
36618 ranu 2534
				}
2535
			}
2536
		}
2537
 
2538
		Map<String, Object> response = new HashMap<>();
2539
		response.put("status", true);
36644 ranu 2540
		response.put("planGroupId", String.valueOf(beat.getId()));
36618 ranu 2541
		response.put("message", "Beat plan submitted successfully");
2542
		return responseSender.ok(response);
2543
	}
2544
 
36632 ranu 2545
	// ============ BULK UPLOAD ============
2546
 
2547
	@GetMapping(value = "/beatPlan/bulkUpload")
2548
	public String bulkUploadPage(HttpServletRequest request, Model model) {
2549
		return "beat-plan-bulk";
2550
	}
2551
 
36681 ranu 2552
	// Adds a new base location for the user. Caller can request this new row
2553
	// becomes the default. If the user has NO base locations yet, the new row
2554
	// is auto-defaulted (so every user always has exactly one default).
36668 ranu 2555
	@PostMapping(value = "/beatPlan/updateBaseLocation")
2556
	public ResponseEntity<?> updateBaseLocation(
2557
			HttpServletRequest request,
2558
			@RequestParam int authUserId,
2559
			@RequestParam String locationName,
2560
			@RequestParam String latitude,
2561
			@RequestParam String longitude,
36681 ranu 2562
			@RequestParam(required = false) String address,
2563
			@RequestParam(required = false, defaultValue = "false") boolean isDefault) throws Exception {
36668 ranu 2564
 
2565
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
2566
		AuthUser me = authRepository.selectByEmailOrMobile(ld.getEmailId());
2567
		if (me == null) return responseSender.unauthorized("Not logged in");
36681 ranu 2568
		if (!isBaseLocationManager(me)) {
2569
			return responseSender.forbidden("You are not authorized for this action. Only Sales L3 and above can update base location.");
2570
		}
36668 ranu 2571
 
36681 ranu 2572
		List<AuthUserLocation> existing = authUserLocationRepository.selectAllByAuthUserIdAndType(authUserId, "BASE");
2573
		boolean noExistingDefault = existing.stream().noneMatch(AuthUserLocation::isDefault);
2574
		boolean makeDefault = isDefault || existing.isEmpty() || noExistingDefault;
36668 ranu 2575
 
36681 ranu 2576
		// If this new row becomes the default, clear any existing default.
2577
		if (makeDefault) {
2578
			for (AuthUserLocation e : existing) {
2579
				if (e.isDefault()) {
2580
					e.setDefault(false);
2581
					authUserLocationRepository.persist(e);
2582
				}
2583
			}
36668 ranu 2584
		}
2585
 
2586
		AuthUserLocation loc = new AuthUserLocation();
2587
		loc.setAuthUserId(authUserId);
2588
		loc.setLocationType("BASE");
2589
		loc.setLocationName(locationName);
2590
		loc.setLatitude(latitude);
2591
		loc.setLongitude(longitude);
2592
		loc.setAddress(address);
36681 ranu 2593
		loc.setDefault(makeDefault);
36668 ranu 2594
		loc.setCreatedTimestamp(LocalDateTime.now());
2595
		authUserLocationRepository.persist(loc);
2596
 
2597
		Map<String, Object> result = new HashMap<>();
2598
		result.put("status", true);
2599
		result.put("id", loc.getId());
36681 ranu 2600
		result.put("isDefault", loc.isDefault());
2601
		result.put("message", makeDefault ? "Base location added and set as default" : "Base location added");
36668 ranu 2602
		return responseSender.ok(result);
2603
	}
2604
 
36814 ranu 2605
	// Read-only list of company offices — gives BMs a quick lookup of the codes
2606
	// they'll need to drop into the bulk-upload sheet for OFFICE stops.
2607
	// Two URL mappings: /companyOffice/list (canonical) + /company-office-list
2608
	// (matches the menu's action_class so the sidebar link works without an extra
2609
	// auth.menu update).
2610
	@GetMapping(value = {"/companyOffice/list", "/company-office-list"})
2611
	public String companyOfficeList(Model model) {
2612
		List<com.spice.profitmandi.dao.entity.logistics.CompanyOffice> offices = companyOfficeRepository.selectAll();
2613
		// Active first, then sort by code so the bulk-upload reference is stable across page loads.
2614
		offices.sort((a, b) -> {
2615
			int aa = a.isActive() ? 0 : 1;
2616
			int bb = b.isActive() ? 0 : 1;
2617
			if (aa != bb) return Integer.compare(aa, bb);
2618
			String ac = a.getCode() != null ? a.getCode() : "";
2619
			String bc = b.getCode() != null ? b.getCode() : "";
2620
			return ac.compareToIgnoreCase(bc);
2621
		});
2622
		model.addAttribute("offices", offices);
2623
		return "company-office-list";
2624
	}
2625
 
36632 ranu 2626
	@GetMapping(value = "/beatPlan/downloadTemplate")
36668 ranu 2627
	public ResponseEntity<?> downloadTemplate() throws java.io.IOException {
2628
		org.apache.poi.xssf.usermodel.XSSFWorkbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
2629
		org.apache.poi.xssf.usermodel.XSSFSheet sheet = wb.createSheet("beat-plan");
36632 ranu 2630
 
36668 ranu 2631
		String[] cols = {"beat_name", "auth_user_id", "start_date", "day_number", "sequence_order", "partner_code"};
2632
 
2633
		// Header style
2634
		org.apache.poi.xssf.usermodel.XSSFCellStyle headerStyle = wb.createCellStyle();
2635
		org.apache.poi.xssf.usermodel.XSSFFont headerFont = wb.createFont();
2636
		headerFont.setBold(true);
2637
		headerStyle.setFont(headerFont);
2638
		headerStyle.setFillForegroundColor(new org.apache.poi.xssf.usermodel.XSSFColor(new java.awt.Color(230, 230, 230)));
2639
		headerStyle.setFillPattern(org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND);
2640
 
2641
		org.apache.poi.xssf.usermodel.XSSFRow header = sheet.createRow(0);
2642
		for (int i = 0; i < cols.length; i++) {
2643
			org.apache.poi.xssf.usermodel.XSSFCell c = header.createCell(i);
2644
			c.setCellValue(cols[i]);
2645
			c.setCellStyle(headerStyle);
2646
		}
2647
 
2648
		// Example rows — one partner per row. Inheritable columns blank after first row of a beat.
2649
		Object[][] sample = {
2650
				{"Jaipur East Route", "280", "2026-06-02", "1", "1", "RJKAI1478"},
2651
				{"", "", "", "1", "2", "RJBUN1449"},
2652
				{"", "", "", "1", "3", "RJDEG1443"},
2653
				{"", "", "", "2", "1", "RJALR1362"},
2654
				{"", "", "", "2", "2", "RJBTR1388"},
2655
				{"", "", "", "3", "1", "RJRSD1518"},
2656
				{"", "", "", "3", "2", "RJSML356"},
2657
				{"Agra Circuit", "145", "2026-06-05", "1", "1", "UPAGR101"},
2658
				{"", "", "", "1", "2", "UPAGR102"},
2659
		};
2660
		for (int r = 0; r < sample.length; r++) {
2661
			org.apache.poi.xssf.usermodel.XSSFRow row = sheet.createRow(r + 1);
2662
			for (int c = 0; c < cols.length; c++) {
2663
				row.createCell(c).setCellValue(sample[r][c].toString());
2664
			}
2665
		}
2666
		for (int i = 0; i < cols.length; i++) sheet.autoSizeColumn(i);
2667
 
2668
		java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
2669
		wb.write(out);
2670
		wb.close();
2671
 
36632 ranu 2672
		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
36668 ranu 2673
		headers.add("Content-Disposition", "attachment; filename=beat_plan_template.xlsx");
2674
		headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
2675
		return new ResponseEntity<>(out.toByteArray(), headers, org.springframework.http.HttpStatus.OK);
36632 ranu 2676
	}
2677
 
2678
	@PostMapping(value = "/beatPlan/bulkUploadProcess")
2679
	public ResponseEntity<?> bulkUploadProcess(
2680
			HttpServletRequest request,
2681
			@RequestParam("file") org.springframework.web.multipart.MultipartFile file,
2682
			@RequestParam(value = "includeSundays", defaultValue = "false") boolean includeSundays) throws Exception {
2683
 
2684
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2685
		AuthUser currentUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
2686
 
36668 ranu 2687
		// Read .xlsx — one partner per row. beat_name / auth_user_id / start_date
2688
		// appear ONLY on the first row of a beat; subsequent rows inherit them.
2689
		org.apache.poi.ss.usermodel.Workbook workbook =
2690
				new org.apache.poi.xssf.usermodel.XSSFWorkbook(file.getInputStream());
2691
		org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
36632 ranu 2692
 
36668 ranu 2693
		// Header → column index map
2694
		org.apache.poi.ss.usermodel.Row headerRow = sheet.getRow(0);
2695
		if (headerRow == null) {
2696
			workbook.close();
2697
			return responseSender.badRequest("Empty file");
2698
		}
2699
		Map<String, Integer> colIdx = new HashMap<>();
2700
		for (int i = 0; i < headerRow.getLastCellNum(); i++) {
2701
			String h = readCell(headerRow.getCell(i));
2702
			if (h != null) colIdx.put(h.trim().toLowerCase(), i);
2703
		}
2704
		for (String required : new String[]{"beat_name", "auth_user_id", "day_number", "partner_code"}) {
2705
			if (!colIdx.containsKey(required)) {
2706
				workbook.close();
2707
				return responseSender.badRequest("Missing required column: " + required);
2708
			}
2709
		}
36632 ranu 2710
 
36668 ranu 2711
		// Walk rows, group partners by (beat_name + auth_user_id) → day_number → sequence_order
2712
		Map<String, BulkBeatGroup> beatGroups = new LinkedHashMap<>();
2713
		String currentKey = null;
2714
		String currentBeatName = null;
2715
		String currentAuthId = null;
2716
		String currentStartDate = null;
2717
 
2718
		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
2719
			org.apache.poi.ss.usermodel.Row row = sheet.getRow(r);
2720
			if (row == null) continue;
2721
 
2722
			String beatName = readCell(row.getCell(colIdx.get("beat_name")));
2723
			String authId = readCell(row.getCell(colIdx.get("auth_user_id")));
2724
			String startDate = colIdx.containsKey("start_date") ? readCell(row.getCell(colIdx.get("start_date"))) : null;
2725
			String dayNumber = readCell(row.getCell(colIdx.get("day_number")));
2726
			String seqOrder = colIdx.containsKey("sequence_order") ? readCell(row.getCell(colIdx.get("sequence_order"))) : null;
2727
			String code = readCell(row.getCell(colIdx.get("partner_code")));
2728
 
2729
			if (beatName != null && !beatName.trim().isEmpty()) {
2730
				// Start of a new beat — capture inheritable fields
2731
				currentBeatName = beatName.trim().replaceAll("\\s+", " ");
2732
				currentAuthId = authId != null ? authId.trim() : null;
2733
				currentStartDate = (startDate != null && !startDate.trim().isEmpty()) ? startDate.trim() : null;
2734
				currentKey = currentBeatName + "|" + currentAuthId;
2735
			}
2736
			if (currentKey == null) continue; // partner row before any beat header — skip
2737
			if (code == null || code.trim().isEmpty()) continue;
2738
 
2739
			final String beatNameF = currentBeatName;
2740
			final String authIdF = currentAuthId;
2741
			final String startDateF = currentStartDate;
2742
			BulkBeatGroup g = beatGroups.computeIfAbsent(currentKey, k -> new BulkBeatGroup(beatNameF, authIdF, startDateF));
2743
 
2744
			int day;
2745
			try {
2746
				day = Integer.parseInt(dayNumber.trim());
2747
			} catch (Exception e) {
2748
				continue;
2749
			} // bad day → skip row
2750
 
2751
			int seq = -1;
2752
			if (seqOrder != null && !seqOrder.trim().isEmpty()) {
2753
				try {
2754
					seq = Integer.parseInt(seqOrder.trim());
2755
				} catch (Exception ignore) {
2756
				}
2757
			}
2758
			g.addPartner(day, seq, code.trim(), r + 1);
36632 ranu 2759
		}
36668 ranu 2760
		workbook.close();
36632 ranu 2761
 
36811 ranu 2762
		// Partner-code lookup (legacy).
36632 ranu 2763
		List<FofoStore> allStores = fofoStoreRepository.selectAll();
2764
		Map<String, Integer> codeToId = new HashMap<>();
37060 vikas 2765
		Map<String, double[]> codeToLatLng = new HashMap<>();
2766
		for (FofoStore store : allStores) {
2767
			codeToId.put(store.getCode(), store.getId());
2768
			Double la = parseDoubleOrNull(store.getLatitude());
2769
			Double lo = parseDoubleOrNull(store.getLongitude());
2770
			if (la != null && lo != null) codeToLatLng.put(store.getCode(), new double[]{la, lo});
2771
		}
36632 ranu 2772
 
36811 ranu 2773
		// Office-code lookup — office stops share the same `partner_code` column in the bulk
2774
		// sheet; resolution dispatches by which catalogue the code belongs to. A code present
2775
		// in BOTH catalogues is treated as an error so the planner fixes the collision.
2776
		Map<String, Integer> officeCodeToId = new HashMap<>();
2777
		for (com.spice.profitmandi.dao.entity.logistics.CompanyOffice o : companyOfficeRepository.selectAll()) {
2778
			if (o.getCode() != null && !o.getCode().isEmpty()) officeCodeToId.put(o.getCode(), o.getId());
2779
		}
2780
 
36632 ranu 2781
		LocalDate holidayStart = LocalDate.now();
36644 ranu 2782
		List<PublicHolidays> holidays = publicHolidaysRepository.selectAllBetweenDates(holidayStart, holidayStart.plusMonths(6));
36632 ranu 2783
		Set<LocalDate> holidayDates = holidays.stream().map(PublicHolidays::getDate).collect(Collectors.toSet());
2784
 
36785 ranu 2785
		// =====================================================================
2786
		// All-or-nothing import: validate every group first; only persist if
2787
		// the entire file passes. A single bad row blocks the whole upload
2788
		// so the user can fix and re-upload without partial creations.
2789
		// =====================================================================
2790
 
36632 ranu 2791
		List<String> errorMessages = new ArrayList<>();
36785 ranu 2792
		List<ValidatedBulkBeat> ready = new ArrayList<>();
36632 ranu 2793
 
36785 ranu 2794
		// ----- Phase 1: validate every group, collect ALL errors -----
36668 ranu 2795
		for (BulkBeatGroup g : beatGroups.values()) {
36785 ranu 2796
			String beatName = g.beatName;
2797
 
2798
			int authUserId;
36632 ranu 2799
			try {
36785 ranu 2800
				authUserId = Integer.parseInt(g.authUserId);
2801
			} catch (Exception e) {
2802
				errorMessages.add("Beat '" + beatName + "': invalid auth_user_id '" + g.authUserId + "'.");
2803
				continue;
2804
			}
36632 ranu 2805
 
36785 ranu 2806
			LocalDate startDate;
2807
			try {
2808
				startDate = (g.startDate == null || g.startDate.isEmpty())
2809
						? null : LocalDate.parse(g.startDate, DateTimeFormatter.ISO_DATE);
2810
			} catch (Exception e) {
2811
				errorMessages.add("Beat '" + beatName + "': invalid start_date '" + g.startDate + "'.");
2812
				continue;
2813
			}
2814
			if (startDate != null && startDate.isBefore(LocalDate.now())) {
2815
				errorMessages.add("Beat '" + beatName + "': start_date in past.");
2816
				continue;
2817
			}
36632 ranu 2818
 
36785 ranu 2819
			List<Integer> sortedDays = new ArrayList<>(g.dayToPartners.keySet());
2820
			Collections.sort(sortedDays);
36668 ranu 2821
 
36785 ranu 2822
			List<LocalDate> scheduleDates = new ArrayList<>();
2823
			if (startDate != null) {
2824
				LocalDate d = startDate;
2825
				while (scheduleDates.size() < sortedDays.size()) {
2826
					if (holidayDates.contains(d) || (d.getDayOfWeek() == DayOfWeek.SUNDAY && !includeSundays)) {
36632 ranu 2827
						d = d.plusDays(1);
36785 ranu 2828
						continue;
36632 ranu 2829
					}
36785 ranu 2830
					scheduleDates.add(d);
2831
					d = d.plusDays(1);
36632 ranu 2832
				}
36785 ranu 2833
			}
36632 ranu 2834
 
36785 ranu 2835
			// Duplicate beat-name check (ACTIVE only; soft-deleted names are reusable).
2836
			boolean isDuplicate = beatRepository.selectActiveByAuthUserId(authUserId).stream()
2837
					.anyMatch(b -> b.getName() != null && beatName.equalsIgnoreCase(b.getName().trim()));
2838
			if (isDuplicate) {
2839
				errorMessages.add("Beat '" + beatName + "': already exists for user " + authUserId + ".");
2840
				continue;
2841
			}
2842
 
2843
			// One-beat-per-day guard (against existing beats).
2844
			Map<String, Object> bulkConflict = findScheduleConflict(authUserId, scheduleDates, 0);
2845
			if (bulkConflict != null) {
2846
				errorMessages.add("Beat '" + beatName + "': " + scheduleConflictMessage(bulkConflict));
2847
				continue;
2848
			}
2849
 
36811 ranu 2850
			// Validate codes upfront so we don't half-persist. A code may belong to
2851
			// fofo_store (PARTNER) or company_office (OFFICE) but not both.
36785 ranu 2852
			List<String> badCodes = new ArrayList<>();
36811 ranu 2853
			List<String> ambiguousCodes = new ArrayList<>();
36785 ranu 2854
			for (List<BulkPartner> ps : g.dayToPartners.values()) {
2855
				for (BulkPartner p : ps) {
36811 ranu 2856
					boolean inPartner = codeToId.containsKey(p.code);
2857
					boolean inOffice = officeCodeToId.containsKey(p.code);
2858
					if (inPartner && inOffice) {
2859
						ambiguousCodes.add(p.code + " (row " + p.rowNum + ")");
2860
					} else if (!inPartner && !inOffice) {
36785 ranu 2861
						badCodes.add(p.code + " (row " + p.rowNum + ")");
2862
					}
36644 ranu 2863
				}
36785 ranu 2864
			}
2865
			if (!badCodes.isEmpty()) {
36811 ranu 2866
				errorMessages.add("Beat '" + beatName + "': unknown code(s) — " + String.join(", ", badCodes) + ".");
36785 ranu 2867
				continue;
2868
			}
36811 ranu 2869
			if (!ambiguousCodes.isEmpty()) {
2870
				errorMessages.add("Beat '" + beatName + "': code(s) exist in both partner and office catalogues — " + String.join(", ", ambiguousCodes) + ".");
2871
				continue;
2872
			}
36632 ranu 2873
 
36785 ranu 2874
			ready.add(new ValidatedBulkBeat(g, authUserId, sortedDays, scheduleDates));
2875
		}
36632 ranu 2876
 
36785 ranu 2877
		// Intra-file conflict: two beats in the same upload requesting the same
2878
		// user + date. Caught here so the user fixes the file before re-uploading.
2879
		Set<String> seenUserDates = new HashSet<>();
2880
		for (ValidatedBulkBeat v : ready) {
2881
			for (LocalDate sd : v.scheduleDates) {
2882
				String key = v.authUserId + "|" + sd;
2883
				if (!seenUserDates.add(key)) {
2884
					errorMessages.add("Beat '" + v.g.beatName + "': date " + sd + " is also claimed by another beat in this file for the same user.");
2885
					break;
2886
				}
2887
			}
2888
		}
36632 ranu 2889
 
36785 ranu 2890
		// All-or-nothing: any error → return without persisting anything.
2891
		if (!errorMessages.isEmpty()) {
2892
			Map<String, Object> response = new HashMap<>();
2893
			response.put("status", false);
2894
			response.put("beatsCreated", 0);
2895
			response.put("errors", errorMessages.size());
2896
			response.put("errorMessages", errorMessages);
2897
			response.put("message", "No beats created. Fix the issues below and re-upload the file.");
2898
			return responseSender.ok(response);
2899
		}
36632 ranu 2900
 
36785 ranu 2901
		// ----- Phase 2: persist (only reached when every row was clean) -----
2902
		int beatsCreated = 0;
2903
		for (ValidatedBulkBeat v : ready) {
2904
			BulkBeatGroup g = v.g;
2905
			String beatName = g.beatName;
2906
			int authUserId = v.authUserId;
2907
			List<Integer> sortedDays = v.sortedDays;
2908
			List<LocalDate> scheduleDates = v.scheduleDates;
36668 ranu 2909
 
36785 ranu 2910
			String beatColor = BEAT_COLORS[Math.abs(beatName.hashCode()) % BEAT_COLORS.length];
2911
			AuthUserLocation homeLoc = authUserLocationRepository.selectDefaultByAuthUserIdAndType(authUserId, "BASE");
36632 ranu 2912
 
36785 ranu 2913
			Beat beat = new Beat();
2914
			beat.setName(beatName);
2915
			beat.setAuthUserId(authUserId);
2916
			beat.setBeatColor(beatColor);
2917
			beat.setTotalDays(sortedDays.size());
2918
			beat.setStartLocationName(homeLoc != null ? homeLoc.getLocationName() : "Home");
2919
			beat.setStartLatitude(homeLoc != null ? homeLoc.getLatitude() : null);
2920
			beat.setStartLongitude(homeLoc != null ? homeLoc.getLongitude() : null);
2921
			beat.setActive(true);
2922
			beat.setCreatedBy(currentUser.getId());
2923
			beat.setCreatedTimestamp(LocalDateTime.now());
2924
			beatRepository.persist(beat);
36668 ranu 2925
 
36785 ranu 2926
			LocalDate bulkEndDate = scheduleDates.isEmpty() ? null : scheduleDates.get(scheduleDates.size() - 1);
2927
 
2928
			for (int dayIdx = 0; dayIdx < sortedDays.size(); dayIdx++) {
2929
				int dayNumber = sortedDays.get(dayIdx);
2930
				LocalDate planDate = (dayIdx < scheduleDates.size()) ? scheduleDates.get(dayIdx) : null;
2931
 
2932
				BeatSchedule schedule = new BeatSchedule();
2933
				schedule.setBeatId(beat.getId());
2934
				schedule.setStartDate(planDate != null ? planDate : LocalDate.of(9999, 12, 31));
2935
				schedule.setEndDate(bulkEndDate);
2936
				schedule.setDayNumber(dayNumber);
2937
				schedule.setEndAction(dayIdx == sortedDays.size() - 1 ? "HOME" : "DAYBREAK");
2938
				schedule.setCreatedTimestamp(LocalDateTime.now());
2939
				beatScheduleRepository.persist(schedule);
2940
 
2941
				List<BulkPartner> partners = g.dayToPartners.get(dayNumber);
37060 vikas 2942
				// Auto-order the day into a nearest-neighbor route from the beat's
2943
				// start location, matching the interactive planner. The sheet's
2944
				// sequence_order column is intentionally ignored.
2945
				sortPartnersByNearestNeighbor(partners,
2946
						parseDoubleOrNull(beat.getStartLatitude()),
2947
						parseDoubleOrNull(beat.getStartLongitude()),
2948
						codeToLatLng);
36785 ranu 2949
 
2950
				int autoSeq = 0;
2951
				for (BulkPartner p : partners) {
36811 ranu 2952
					Integer partnerId = codeToId.get(p.code);
2953
					Integer officeId = officeCodeToId.get(p.code);
36785 ranu 2954
					// Codes were validated in Phase 1, this is just a safety net.
36811 ranu 2955
					if (partnerId == null && officeId == null) continue;
36785 ranu 2956
					BeatRoute route = new BeatRoute();
2957
					route.setBeatId(beat.getId());
36811 ranu 2958
					if (partnerId != null) {
2959
						route.setFofoId(partnerId);
2960
						route.setVisitType(com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.PARTNER);
2961
					} else {
2962
						route.setFofoId(officeId);
2963
						route.setVisitType(com.spice.profitmandi.dao.enumuration.dtr.BeatVisitType.OFFICE);
2964
					}
37060 vikas 2965
					// Sequence follows the nearest-neighbor ordering above, not the sheet.
2966
					route.setSequenceOrder(autoSeq);
36785 ranu 2967
					route.setDayNumber(dayNumber);
2968
					route.setActive(true);
2969
					beatRouteRepository.persist(route);
2970
					autoSeq++;
36632 ranu 2971
				}
2972
			}
36785 ranu 2973
			beatsCreated++;
36632 ranu 2974
		}
2975
 
2976
		Map<String, Object> response = new HashMap<>();
2977
		response.put("status", true);
2978
		response.put("beatsCreated", beatsCreated);
36785 ranu 2979
		response.put("errors", 0);
36632 ranu 2980
		response.put("errorMessages", errorMessages);
36785 ranu 2981
		response.put("message", beatsCreated + " beat(s) created.");
36632 ranu 2982
		return responseSender.ok(response);
2983
	}
2984
 
36785 ranu 2985
	// Move a beat from one date to another — used by calendar drag-and-drop.
2986
	// Behaviour: if the target date already has ANOTHER beat scheduled (for the
2987
	// same sales user), the two schedules swap — the other beat slides onto
2988
	// the source date. If the target date is empty, the source date becomes empty.
2989
	@PostMapping(value = "/beatPlan/moveScheduleDate")
2990
	public ResponseEntity<?> moveScheduleDate(
2991
			@RequestParam String planGroupId,
2992
			@RequestParam String fromDate,
2993
			@RequestParam String toDate) {
2994
		int beatId = Integer.parseInt(planGroupId);
2995
		LocalDate from = LocalDate.parse(fromDate);
2996
		LocalDate to = LocalDate.parse(toDate);
2997
 
2998
		if (from.equals(to)) {
2999
			Map<String, Object> ok = new HashMap<>();
3000
			ok.put("status", true);
3001
			ok.put("message", "Same date — no change");
3002
			return responseSender.ok(ok);
3003
		}
3004
 
3005
		// Today is the live/running slot — a beat already running today can't be
3006
		// bumped, and a future beat can't be moved onto today.
3007
		LocalDate today = LocalDate.now();
3008
		if (to.equals(today) || from.equals(today) || from.isBefore(today) || to.isBefore(today)) {
3009
			return responseSender.badRequest("Cannot move to or from today / a past date — today's beat is live. Use future dates only.");
3010
		}
3011
 
3012
		Beat beat = beatRepository.selectById(beatId);
3013
		if (beat == null) return responseSender.badRequest("Beat not found");
3014
 
3015
		List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beatId);
3016
 
3017
		// Reject if THIS beat already has a different schedule row on the target date
3018
		// (it would create two schedule rows of the same beat on one day).
3019
		boolean selfConflict = schedules.stream()
3020
				.anyMatch(s -> s.getStartDate() != null && s.getStartDate().equals(to));
3021
		if (selfConflict) return responseSender.badRequest("Beat is already scheduled on " + toDate);
3022
 
3023
		BeatSchedule match = schedules.stream()
3024
				.filter(s -> s.getStartDate() != null && s.getStartDate().equals(from))
3025
				.findFirst().orElse(null);
3026
		if (match == null) return responseSender.badRequest("No schedule found for " + fromDate);
3027
 
3028
		// Look for ANY OTHER beat (same sales user) whose schedule sits on the target
3029
		// date — if found we'll swap it onto the source date.
3030
		BeatSchedule otherSchedule = null;
3031
		List<BeatSchedule> otherSchedules = null;
3032
		Beat otherBeat = null;
3033
		for (Beat ub : beatRepository.selectActiveByAuthUserId(beat.getAuthUserId())) {
3034
			if (ub.getId() == beatId) continue;
3035
			List<BeatSchedule> ubSchedules = beatScheduleRepository.selectByBeatId(ub.getId());
3036
			BeatSchedule hit = ubSchedules.stream()
3037
					.filter(s -> s.getStartDate() != null && s.getStartDate().equals(to))
3038
					.findFirst().orElse(null);
3039
			if (hit != null) {
3040
				otherSchedule = hit;
3041
				otherSchedules = ubSchedules;
3042
				otherBeat = ub;
3043
				break;
3044
			}
3045
		}
3046
 
36840 ranu 3047
		// Multi-day beats can't be drag-swapped — moving one of their day_numbers
3048
		// in isolation would leave the other days behind and break the
3049
		// Day 1 → Day 2 → … chronological contiguity of the plan. Block both
3050
		// sides of the swap, point the BM at the Reschedule flow which moves
3051
		// every day together.
3052
		if (beat.getTotalDays() > 1) {
3053
			return responseSender.badRequest(
3054
					"\"" + (beat.getName() != null ? beat.getName() : "Beat #" + beat.getId())
3055
							+ "\" is a multi-day beat (" + beat.getTotalDays()
3056
							+ " days). Drag-swap is only allowed for single-day beats. Use Reschedule to move the whole plan together.");
3057
		}
3058
		if (otherBeat != null && otherBeat.getTotalDays() > 1) {
3059
			return responseSender.badRequest(
3060
					"Target date already has \"" + (otherBeat.getName() != null ? otherBeat.getName() : "Beat #" + otherBeat.getId())
3061
							+ "\", a multi-day beat (" + otherBeat.getTotalDays()
3062
							+ " days). Drag-swap is only allowed when both beats are single-day. Use Reschedule on one of them first.");
3063
		}
3064
 
3065
		// Move the dragged beat onto the target date. Per-row invariant:
3066
		// each schedule row's end_date == its own start_date (single-day shape).
3067
		// We touch ONLY the two rows being swapped — other schedule rows for the
3068
		// same beat (e.g. older dates) are left exactly as they were.
36785 ranu 3069
		match.setStartDate(to);
36840 ranu 3070
		match.setEndDate(to);
36785 ranu 3071
		if (otherSchedule != null) {
3072
			otherSchedule.setStartDate(from);
36840 ranu 3073
			otherSchedule.setEndDate(from);
36785 ranu 3074
		}
3075
 
3076
		Map<String, Object> response = new HashMap<>();
3077
		response.put("status", true);
3078
		response.put("message", otherBeat != null
3079
				? "Swapped with \"" + (otherBeat.getName() != null ? otherBeat.getName() : "beat") + "\" on " + toDate
3080
				: "Moved from " + fromDate + " to " + toDate);
3081
		response.put("swapped", otherBeat != null);
3082
		return responseSender.ok(response);
3083
	}
3084
 
36668 ranu 3085
	private static class BulkBeatGroup {
3086
		final String beatName;
3087
		final String authUserId;
3088
		final String startDate;
3089
		final Map<Integer, List<BulkPartner>> dayToPartners = new LinkedHashMap<>();
3090
 
3091
		BulkBeatGroup(String beatName, String authUserId, String startDate) {
3092
			this.beatName = beatName;
3093
			this.authUserId = authUserId;
3094
			this.startDate = startDate;
3095
		}
3096
 
3097
		void addPartner(int day, int seq, String code, int rowNum) {
3098
			dayToPartners.computeIfAbsent(day, k -> new ArrayList<>()).add(new BulkPartner(seq, code, rowNum));
3099
		}
3100
	}
3101
 
3102
	private static class BulkPartner {
3103
		final int seq;
3104
		final String code;
3105
		final int rowNum;
3106
 
3107
		BulkPartner(int seq, String code, int rowNum) {
3108
			this.seq = seq;
3109
			this.code = code;
3110
			this.rowNum = rowNum;
3111
		}
3112
	}
3113
 
36644 ranu 3114
	// ============ CALENDAR ============
36618 ranu 3115
 
3116
	@PostMapping(value = "/beatPlan/delete")
3117
	public ResponseEntity<?> deleteBeat(@RequestParam String planGroupId) {
36644 ranu 3118
		int beatId = Integer.parseInt(planGroupId);
36698 ranu 3119
		// Hard delete — wipe all child rows first, then the beat itself.
3120
		// The name slot is freed naturally because the row is gone.
36644 ranu 3121
		beatRouteRepository.deleteByBeatId(beatId);
3122
		beatScheduleRepository.deleteByBeatId(beatId);
36698 ranu 3123
		leadRouteRepository.deleteByBeatId(beatId);
36644 ranu 3124
		Beat beat = beatRepository.selectById(beatId);
3125
		if (beat != null) {
36698 ranu 3126
			beatRepository.delete(beat);
36644 ranu 3127
		}
36618 ranu 3128
 
3129
		Map<String, Object> response = new HashMap<>();
3130
		response.put("status", true);
3131
		response.put("message", "Beat deleted");
3132
		return responseSender.ok(response);
3133
	}
3134
 
36670 ranu 3135
	// Unschedule the beat from ONE specific date — does NOT delete the beat.
3136
	// The beat (and its route template) stays; only the matching beat_schedule
3137
	// row is removed. If no real-date schedules remain, a placeholder
3138
	// (9999-12-31) row is added so the beat still shows up as "unscheduled".
3139
	@PostMapping(value = "/beatPlan/unscheduleDate")
3140
	public ResponseEntity<?> unscheduleDate(
3141
			@RequestParam String planGroupId,
3142
			@RequestParam String date) {
3143
		int beatId = Integer.parseInt(planGroupId);
3144
		LocalDate target = LocalDate.parse(date);
3145
 
3146
		Beat beat = beatRepository.selectById(beatId);
3147
		if (beat == null) return responseSender.badRequest("Beat not found");
3148
 
3149
		List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beatId);
3150
		int removed = 0;
3151
		for (BeatSchedule s : schedules) {
3152
			if (s.getStartDate() != null && s.getStartDate().equals(target)) {
3153
				beatScheduleRepository.delete(s);
3154
				removed++;
3155
			}
3156
		}
3157
		if (removed == 0) return responseSender.badRequest("No schedule found for that date");
3158
 
3159
		// If no real-date schedules left, drop in a placeholder so the beat
3160
		// remains visible in the unscheduled bucket.
3161
		boolean hasReal = schedules.stream()
3162
				.filter(s -> !s.getStartDate().equals(target))
3163
				.anyMatch(s -> s.getStartDate() != null && s.getStartDate().getYear() != 9999);
3164
		if (!hasReal) {
3165
			boolean hasPlaceholder = schedules.stream()
3166
					.filter(s -> !s.getStartDate().equals(target))
3167
					.anyMatch(s -> s.getStartDate() != null && s.getStartDate().getYear() == 9999);
3168
			if (!hasPlaceholder) {
3169
				BeatSchedule ph = new BeatSchedule();
3170
				ph.setBeatId(beatId);
3171
				ph.setStartDate(LocalDate.of(9999, 12, 31));
3172
				ph.setDayNumber(1);
3173
				ph.setEndAction("HOME");
3174
				ph.setCreatedTimestamp(LocalDateTime.now());
3175
				beatScheduleRepository.persist(ph);
3176
			}
3177
		}
3178
 
3179
		Map<String, Object> response = new HashMap<>();
3180
		response.put("status", true);
3181
		response.put("message", "Unscheduled from " + date);
3182
		return responseSender.ok(response);
3183
	}
3184
 
36785 ranu 3185
	/**
3186
	 * Per-user one-beat-per-day guard. Walks every active beat the sales user
3187
	 * already has and looks for a schedule row on any of the candidate dates.
3188
	 * Returns null if the candidate dates are clear, otherwise a {date,beatName}
3189
	 * map describing the first collision so the caller can surface a clean error.
3190
	 * Pass `excludeBeatId` so callers that are re-scheduling an existing beat
3191
	 * don't trip on their own pre-existing schedule rows; pass 0 for new beats.
3192
	 */
3193
	private Map<String, Object> findScheduleConflict(int authUserId, java.util.Collection<LocalDate> candidates, int excludeBeatId) {
3194
		if (candidates == null || candidates.isEmpty()) return null;
3195
		Set<LocalDate> ds = new HashSet<>();
3196
		for (LocalDate d : candidates) {
3197
			if (d != null && d.getYear() != 9999) ds.add(d);
3198
		}
3199
		if (ds.isEmpty()) return null;
3200
		for (Beat ub : beatRepository.selectActiveByAuthUserId(authUserId)) {
3201
			if (ub.getId() == excludeBeatId) continue;
3202
			for (BeatSchedule s : beatScheduleRepository.selectByBeatId(ub.getId())) {
3203
				if (s.getStartDate() != null && ds.contains(s.getStartDate())) {
3204
					Map<String, Object> conflict = new HashMap<>();
3205
					conflict.put("date", s.getStartDate().toString());
3206
					conflict.put("beatName", ub.getName() != null ? ub.getName() : "Beat #" + ub.getId());
3207
					return conflict;
3208
				}
3209
			}
3210
		}
3211
		return null;
3212
	}
3213
 
3214
	private String scheduleConflictMessage(Map<String, Object> conflict) {
3215
		return "Cannot schedule on " + conflict.get("date")
3216
				+ " — \"" + conflict.get("beatName") + "\" is already scheduled for this user on that day.";
3217
	}
3218
 
3219
	@PostMapping(value = "/beatPlan/scheduleOnCalendar")
3220
	public ResponseEntity<?> scheduleOnCalendar(
3221
			HttpServletRequest request,
36670 ranu 3222
			@RequestParam String planGroupId,
36785 ranu 3223
			@RequestParam String dates,
3224
			@RequestParam(required = false) String beatName,
3225
			@RequestParam(required = false) String beatColor) throws Exception {
3226
 
36670 ranu 3227
		int beatId = Integer.parseInt(planGroupId);
36785 ranu 3228
		Gson gson = new Gson();
3229
		List<String> dateList = gson.fromJson(dates, new TypeToken<List<String>>() {
3230
		}.getType());
36670 ranu 3231
 
3232
		Beat beat = beatRepository.selectById(beatId);
3233
		if (beat == null) return responseSender.badRequest("Beat not found");
3234
 
36785 ranu 3235
		if (beatName != null) beat.setName(beatName);
3236
		if (beatColor != null && !beatColor.isEmpty()) beat.setBeatColor(beatColor);
36670 ranu 3237
 
36785 ranu 3238
		// One-beat-per-day guard: reject if any of the requested dates already
3239
		// has another beat scheduled for this user (excluding this beat itself).
3240
		List<LocalDate> requested = new ArrayList<>();
3241
		for (String s : dateList) {
3242
			try {
3243
				requested.add(LocalDate.parse(s));
3244
			} catch (Exception ignored) {
36670 ranu 3245
			}
3246
		}
36962 vikas 3247
		// Same-day scheduling is restricted to L4+ operators.
3248
		if (requested.contains(LocalDate.now()) && !canScheduleToday(currentUser(request))) {
3249
			return responseSender.badRequest("Scheduling a beat for today is restricted to L4 and above.");
3250
		}
36785 ranu 3251
		Map<String, Object> conflict = findScheduleConflict(beat.getAuthUserId(), requested, beatId);
3252
		if (conflict != null) return responseSender.badRequest(scheduleConflictMessage(conflict));
36670 ranu 3253
 
36785 ranu 3254
		// Delete old schedules and create new
3255
		beatScheduleRepository.deleteByBeatId(beatId);
3256
		LocalDate schEndDate = dateList.isEmpty() ? null : LocalDate.parse(dateList.get(dateList.size() - 1));
3257
		for (int i = 0; i < dateList.size() && i < beat.getTotalDays(); i++) {
3258
            int dayNumber = i + 1;
3259
            String endAction = (i == dateList.size() - 1) ? "HOME" : "DAYBREAK";
3260
			BeatSchedule schedule = new BeatSchedule();
3261
			schedule.setBeatId(beatId);
3262
			schedule.setStartDate(LocalDate.parse(dateList.get(i)));
3263
			schedule.setEndDate(schEndDate);
3264
            schedule.setDayNumber(dayNumber);
3265
            schedule.setEndAction(endAction);
3266
            // Fill total_distance_km / total_time_mins from beat_route so the new
3267
            // schedule row isn't NULL (this was the bug — these were left unset).
3268
            double[] totals = computeDayTotals(beatId, dayNumber, endAction);
3269
            schedule.setTotalDistanceKm(totals[0]);
3270
            schedule.setTotalTimeMins((int) totals[1]);
3271
			schedule.setCreatedTimestamp(LocalDateTime.now());
3272
			beatScheduleRepository.persist(schedule);
3273
		}
3274
 
36670 ranu 3275
		Map<String, Object> response = new HashMap<>();
3276
		response.put("status", true);
36785 ranu 3277
		response.put("message", "Beat scheduled successfully");
36670 ranu 3278
		return responseSender.ok(response);
3279
	}
3280
 
36618 ranu 3281
	@GetMapping(value = "/beatPlan/calendar")
3282
	public ResponseEntity<?> getCalendar(
3283
			@RequestParam int authUserId,
3284
			@RequestParam String month) {
3285
 
3286
		YearMonth ym = YearMonth.parse(month);
3287
		LocalDate startDate = ym.atDay(1);
3288
		LocalDate endDate = ym.atEndOfMonth();
3289
 
3290
		List<PublicHolidays> holidays = publicHolidaysRepository.selectAllBetweenDates(startDate, endDate);
3291
		List<Map<String, String>> holidayList = holidays.stream().map(h -> {
3292
			Map<String, String> m = new HashMap<>();
3293
			m.put("date", h.getDate().toString());
3294
			m.put("occasion", h.getOccasion());
3295
			return m;
3296
		}).collect(Collectors.toList());
3297
 
36644 ranu 3298
		List<Beat> allBeats = beatRepository.selectActiveByAuthUserId(authUserId);
36618 ranu 3299
		LocalDate today = LocalDate.now();
3300
		List<Map<String, Object>> scheduledBeats = new ArrayList<>();
3301
 
36644 ranu 3302
		for (Beat beat : allBeats) {
3303
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beat.getId());
3304
			List<BeatRoute> routes = beatRouteRepository.selectByBeatId(beat.getId());
36618 ranu 3305
 
36644 ranu 3306
			boolean allNullDates = schedules.isEmpty() || schedules.stream().allMatch(s -> s.getStartDate().getYear() == 9999);
3307
			boolean hasToday = !allNullDates && schedules.stream().anyMatch(s -> s.getStartDate().equals(today));
3308
			boolean allPast = !allNullDates && schedules.stream().filter(s -> s.getStartDate().getYear() != 9999).allMatch(s -> s.getStartDate().isBefore(today));
3309
			boolean allFuture = !allNullDates && schedules.stream().filter(s -> s.getStartDate().getYear() != 9999).allMatch(s -> s.getStartDate().isAfter(today));
36618 ranu 3310
 
3311
			String status;
3312
			if (allNullDates) status = "unscheduled";
3313
			else if (hasToday) status = "running";
3314
			else if (allPast) status = "completed";
36644 ranu 3315
			else status = "scheduled";
36618 ranu 3316
 
36644 ranu 3317
			Map<String, Object> beatInfo = new HashMap<>();
3318
			beatInfo.put("planGroupId", String.valueOf(beat.getId()));
3319
			beatInfo.put("beatName", beat.getName() != null ? beat.getName() : "Beat");
3320
			beatInfo.put("beatColor", beat.getBeatColor() != null ? beat.getBeatColor() : "#3498DB");
3321
			beatInfo.put("status", status);
36728 vikas 3322
			beatInfo.put("totalDays", beat.getTotalDays());
36618 ranu 3323
 
3324
			List<Map<String, Object>> dayInfoList = new ArrayList<>();
36644 ranu 3325
			for (BeatSchedule s : schedules) {
36618 ranu 3326
				Map<String, Object> dayInfo = new HashMap<>();
36644 ranu 3327
				dayInfo.put("dayNumber", s.getDayNumber());
3328
				boolean isUnscheduled = s.getStartDate().getYear() == 9999;
3329
				dayInfo.put("planDate", isUnscheduled ? null : s.getStartDate().toString());
3330
				dayInfo.put("totalKm", s.getTotalDistanceKm());
3331
				dayInfo.put("totalMins", s.getTotalTimeMins());
36711 ranu 3332
                // endAction tells the planner whether to draw the return-to-home line
3333
                // for this day (HOME) or end at the last stop (DAYBREAK).
3334
                dayInfo.put("endAction", s.getEndAction());
36644 ranu 3335
				long visitCount = routes.stream().filter(r -> r.getDayNumber() == s.getDayNumber()).count();
3336
				dayInfo.put("visitCount", (int) visitCount);
36618 ranu 3337
				dayInfoList.add(dayInfo);
3338
			}
36644 ranu 3339
			if (schedules.isEmpty()) {
3340
				// No schedule at all — show from routes
3341
				Map<Integer, Long> dayCounts = routes.stream()
3342
						.collect(Collectors.groupingBy(BeatRoute::getDayNumber, Collectors.counting()));
3343
				for (int d = 1; d <= beat.getTotalDays(); d++) {
3344
					Map<String, Object> dayInfo = new HashMap<>();
3345
					dayInfo.put("dayNumber", d);
3346
					dayInfo.put("planDate", null);
3347
					dayInfo.put("totalKm", null);
3348
					dayInfo.put("totalMins", null);
3349
					dayInfo.put("visitCount", dayCounts.getOrDefault(d, 0L).intValue());
3350
					dayInfoList.add(dayInfo);
3351
				}
3352
			}
3353
			beatInfo.put("days", dayInfoList);
3354
			scheduledBeats.add(beatInfo);
36618 ranu 3355
		}
3356
 
3357
		Set<String> blockedDates = new HashSet<>();
3358
		for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
36644 ranu 3359
			if (d.getDayOfWeek() == DayOfWeek.SUNDAY) blockedDates.add(d.toString());
36618 ranu 3360
		}
36644 ranu 3361
		for (PublicHolidays h : holidays) blockedDates.add(h.getDate().toString());
36618 ranu 3362
 
3363
		Map<String, Object> response = new HashMap<>();
3364
		response.put("holidays", holidayList);
3365
		response.put("scheduledBeats", scheduledBeats);
3366
		response.put("blockedDates", blockedDates);
3367
		return responseSender.ok(response);
3368
	}
3369
 
36644 ranu 3370
	// Drag-drop scheduling — adds schedule dates to the EXISTING beat (no new beat created)
36618 ranu 3371
	@PostMapping(value = "/beatPlan/repeatBeat")
3372
	public ResponseEntity<?> repeatBeat(
3373
			HttpServletRequest request,
3374
			@RequestParam String sourcePlanGroupId,
3375
			@RequestParam int authUserId,
3376
			@RequestParam String dates) throws Exception {
3377
 
36644 ranu 3378
		int beatId = Integer.parseInt(sourcePlanGroupId);
36618 ranu 3379
		Gson gson = new Gson();
3380
		List<String> dateList = gson.fromJson(dates, new TypeToken<List<String>>() {
3381
		}.getType());
3382
 
36644 ranu 3383
		Beat beat = beatRepository.selectById(beatId);
3384
		if (beat == null) return responseSender.badRequest("Beat not found");
36618 ranu 3385
 
36785 ranu 3386
		// One-beat-per-day guard: reject if any of the new dates already has
3387
		// another beat scheduled for this user (excluding this beat itself).
3388
		List<LocalDate> repeatDates = new ArrayList<>();
3389
		for (String s : dateList) {
3390
			try {
3391
				repeatDates.add(LocalDate.parse(s));
3392
			} catch (Exception ignored) {
3393
			}
3394
		}
3395
		Map<String, Object> repeatConflict = findScheduleConflict(beat.getAuthUserId(), repeatDates, beatId);
3396
		if (repeatConflict != null) return responseSender.badRequest(scheduleConflictMessage(repeatConflict));
3397
 
36644 ranu 3398
		// Remove placeholder (unscheduled) schedule rows
3399
		List<BeatSchedule> existing = beatScheduleRepository.selectByBeatId(beatId);
3400
		for (BeatSchedule s : existing) {
3401
			if (s.getStartDate() != null && s.getStartDate().getYear() == 9999) {
3402
				beatScheduleRepository.delete(s);
3403
			}
36618 ranu 3404
		}
3405
 
36711 ranu 3406
        // Add new real-date schedule rows for the existing beat — fill totals
3407
        // from beat_route so total_distance_km / total_time_mins aren't NULL.
36644 ranu 3408
		LocalDate repeatEndDate = dateList.isEmpty() ? null : LocalDate.parse(dateList.get(dateList.size() - 1));
3409
		for (int i = 0; i < dateList.size(); i++) {
36711 ranu 3410
            int dayNumber = i + 1;
3411
            String endAction = (i == dateList.size() - 1) ? "HOME" : "DAYBREAK";
36644 ranu 3412
			BeatSchedule schedule = new BeatSchedule();
3413
			schedule.setBeatId(beatId);
3414
			schedule.setStartDate(LocalDate.parse(dateList.get(i)));
3415
			schedule.setEndDate(repeatEndDate);
36711 ranu 3416
            schedule.setDayNumber(dayNumber);
3417
            schedule.setEndAction(endAction);
3418
            double[] totals = computeDayTotals(beatId, dayNumber, endAction);
3419
            schedule.setTotalDistanceKm(totals[0]);
3420
            schedule.setTotalTimeMins((int) totals[1]);
36644 ranu 3421
			schedule.setCreatedTimestamp(LocalDateTime.now());
3422
			beatScheduleRepository.persist(schedule);
36618 ranu 3423
		}
3424
 
3425
		Map<String, Object> response = new HashMap<>();
3426
		response.put("status", true);
36644 ranu 3427
		response.put("planGroupId", String.valueOf(beatId));
3428
		response.put("message", "Beat scheduled successfully");
36618 ranu 3429
		return responseSender.ok(response);
3430
	}
3431
 
36785 ranu 3432
	private static class ValidatedBulkBeat {
3433
		final BulkBeatGroup g;
3434
		final int authUserId;
3435
		final List<Integer> sortedDays;
3436
		final List<LocalDate> scheduleDates;
3437
 
3438
		ValidatedBulkBeat(BulkBeatGroup g, int authUserId, List<Integer> sortedDays, List<LocalDate> scheduleDates) {
3439
			this.g = g;
3440
			this.authUserId = authUserId;
3441
			this.sortedDays = sortedDays;
3442
			this.scheduleDates = scheduleDates;
3443
		}
3444
	}
3445
 
36618 ranu 3446
	@GetMapping(value = "/beatPlan/availableSlots")
3447
	public ResponseEntity<?> getAvailableSlots(
3448
			@RequestParam int authUserId,
3449
			@RequestParam String month,
3450
			@RequestParam int daysNeeded) {
3451
 
3452
		YearMonth ym = YearMonth.parse(month);
3453
		LocalDate startDate = ym.atDay(1);
3454
		LocalDate endDate = ym.atEndOfMonth();
3455
		LocalDate today = LocalDate.now();
3456
 
3457
		Set<LocalDate> blocked = new HashSet<>();
3458
		for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
3459
			if (d.getDayOfWeek() == DayOfWeek.SUNDAY) blocked.add(d);
36644 ranu 3460
			if (!d.isAfter(today)) blocked.add(d);
36618 ranu 3461
		}
3462
 
3463
		List<PublicHolidays> holidays = publicHolidaysRepository.selectAllBetweenDates(startDate, endDate);
3464
		for (PublicHolidays h : holidays) blocked.add(h.getDate());
3465
 
36644 ranu 3466
		// Get all scheduled dates for this user
3467
		List<Beat> userBeats = beatRepository.selectActiveByAuthUserId(authUserId);
3468
		for (Beat b : userBeats) {
3469
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(b.getId());
3470
			for (BeatSchedule s : schedules) blocked.add(s.getStartDate());
36618 ranu 3471
		}
3472
 
3473
		List<String> available = new ArrayList<>();
3474
		for (LocalDate d = startDate.isAfter(today) ? startDate : today.plusDays(1);
3475
			 !d.isAfter(endDate) && available.size() < daysNeeded;
3476
			 d = d.plusDays(1)) {
36644 ranu 3477
			if (!blocked.contains(d)) available.add(d.toString());
36618 ranu 3478
		}
3479
 
3480
		Map<String, Object> response = new HashMap<>();
3481
		response.put("suggestedDates", available);
3482
		response.put("totalAvailable", available.size());
3483
		return responseSender.ok(response);
3484
	}
3485
 
3486
	// --- Sorting helpers ---
3487
 
3488
	private List<Map<String, Object>> sortByNearestNeighborFromStart(
3489
			List<Map<String, Object>> partners, double startLat, double startLng) {
3490
		List<Map<String, Object>> withCoords = new ArrayList<>();
3491
		List<Map<String, Object>> withoutCoords = new ArrayList<>();
3492
		for (Map<String, Object> p : partners) {
36644 ranu 3493
			if (hasValidCoords(p)) withCoords.add(p);
3494
			else withoutCoords.add(p);
36618 ranu 3495
		}
3496
		List<Map<String, Object>> sorted = new ArrayList<>();
36644 ranu 3497
		double currentLat = startLat, currentLng = startLng;
36618 ranu 3498
		while (!withCoords.isEmpty()) {
3499
			int nearestIdx = 0;
3500
			double nearestDist = Double.MAX_VALUE;
3501
			for (int i = 0; i < withCoords.size(); i++) {
36644 ranu 3502
				double dist = haversine(currentLat, currentLng,
3503
						Double.parseDouble(withCoords.get(i).get("latitude").toString()),
3504
						Double.parseDouble(withCoords.get(i).get("longitude").toString()));
36618 ranu 3505
				if (dist < nearestDist) {
3506
					nearestDist = dist;
3507
					nearestIdx = i;
3508
				}
3509
			}
3510
			Map<String, Object> nearest = withCoords.remove(nearestIdx);
3511
			sorted.add(nearest);
3512
			currentLat = Double.parseDouble(nearest.get("latitude").toString());
3513
			currentLng = Double.parseDouble(nearest.get("longitude").toString());
3514
		}
3515
		sorted.addAll(withoutCoords);
3516
		return sorted;
3517
	}
3518
 
3519
	private List<Map<String, Object>> sortByNearestNeighbor(List<Map<String, Object>> partners) {
3520
		List<Map<String, Object>> withCoords = new ArrayList<>();
3521
		List<Map<String, Object>> withoutCoords = new ArrayList<>();
3522
		for (Map<String, Object> p : partners) {
36644 ranu 3523
			if (hasValidCoords(p)) withCoords.add(p);
3524
			else withoutCoords.add(p);
36618 ranu 3525
		}
3526
		List<Map<String, Object>> sorted = new ArrayList<>();
3527
		if (!withCoords.isEmpty()) {
3528
			sorted.add(withCoords.remove(0));
3529
			while (!withCoords.isEmpty()) {
3530
				Map<String, Object> last = sorted.get(sorted.size() - 1);
3531
				double lastLat = Double.parseDouble(last.get("latitude").toString());
3532
				double lastLng = Double.parseDouble(last.get("longitude").toString());
3533
				int nearestIdx = 0;
3534
				double nearestDist = Double.MAX_VALUE;
3535
				for (int i = 0; i < withCoords.size(); i++) {
36644 ranu 3536
					double dist = haversine(lastLat, lastLng,
3537
							Double.parseDouble(withCoords.get(i).get("latitude").toString()),
3538
							Double.parseDouble(withCoords.get(i).get("longitude").toString()));
36618 ranu 3539
					if (dist < nearestDist) {
3540
						nearestDist = dist;
3541
						nearestIdx = i;
3542
					}
3543
				}
3544
				sorted.add(withCoords.remove(nearestIdx));
3545
			}
3546
		}
3547
		sorted.addAll(withoutCoords);
3548
		return sorted;
3549
	}
3550
 
3551
	private boolean hasValidCoords(Map<String, Object> p) {
3552
		Object lat = p.get("latitude");
3553
		Object lng = p.get("longitude");
36644 ranu 3554
		return lat != null && lng != null && !lat.toString().isEmpty() && !lng.toString().isEmpty();
36618 ranu 3555
	}
3556
 
3557
	private double haversine(double lat1, double lng1, double lat2, double lng2) {
3558
		double R = 6371;
3559
		double dLat = Math.toRadians(lat2 - lat1);
3560
		double dLng = Math.toRadians(lng2 - lng1);
3561
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
3562
				+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
3563
				* Math.sin(dLng / 2) * Math.sin(dLng / 2);
3564
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
3565
		return R * c;
3566
	}
3567
}