Subversion Repositories SmartDukaan

Rev

Rev 36711 | Rev 36727 | 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;
7
import com.spice.profitmandi.common.web.util.ResponseSender;
8
import com.spice.profitmandi.dao.entity.auth.AuthUser;
9
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
10
import com.spice.profitmandi.dao.entity.logistics.PublicHolidays;
36644 ranu 11
import com.spice.profitmandi.dao.entity.user.*;
36618 ranu 12
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
13
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
14
import com.spice.profitmandi.dao.repository.cs.CsService;
15
import com.spice.profitmandi.dao.repository.dtr.*;
16
import com.spice.profitmandi.dao.repository.logistics.PublicHolidaysRepository;
17
import com.spice.profitmandi.service.user.RetailerService;
18
import com.spice.profitmandi.web.model.LoginDetails;
19
import com.spice.profitmandi.web.util.CookiesProcessor;
20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
22
import org.springframework.beans.factory.annotation.Autowired;
23
import org.springframework.http.ResponseEntity;
24
import org.springframework.stereotype.Controller;
25
import org.springframework.transaction.annotation.Transactional;
26
import org.springframework.ui.Model;
27
import org.springframework.web.bind.annotation.GetMapping;
28
import org.springframework.web.bind.annotation.PostMapping;
29
import org.springframework.web.bind.annotation.RequestParam;
30
 
31
import javax.servlet.http.HttpServletRequest;
32
import java.lang.reflect.Type;
33
import java.time.DayOfWeek;
34
import java.time.LocalDate;
35
import java.time.LocalDateTime;
36
import java.time.YearMonth;
37
import java.time.format.DateTimeFormatter;
38
import java.util.*;
39
import java.util.stream.Collectors;
40
 
41
@Controller
42
@Transactional(rollbackFor = Throwable.class)
43
public class BeatPlanController {
44
	private static final Logger LOGGER = LogManager.getLogger(BeatPlanController.class);
45
	private static final String[] BEAT_COLORS = {
46
			"#3498DB", "#E74C3C", "#2ECC71", "#9B59B6", "#F39C12",
47
			"#1ABC9C", "#E67E22", "#34495E", "#16A085", "#C0392B"
48
	};
49
	@Autowired
50
	private CsService csService;
51
	@Autowired
52
	private AuthRepository authRepository;
36686 ranu 53
	// Emails that bypass hierarchy and role gates — single source of truth.
54
	private static final Set<String> SUPER_ADMIN_EMAILS = new HashSet<>(Arrays.asList(
55
			"tarun.verma@smartdukaan.com"
56
	));
36618 ranu 57
	@Autowired
36686 ranu 58
	private com.spice.profitmandi.service.AuthService authService;
36618 ranu 59
	@Autowired
36686 ranu 60
	private com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
61
	@Autowired
36618 ranu 62
	private RetailerService retailerService;
63
	@Autowired
36644 ranu 64
	private BeatRepository beatRepository;
36618 ranu 65
	@Autowired
36644 ranu 66
	private BeatRouteRepository beatRouteRepository;
36618 ranu 67
	@Autowired
36644 ranu 68
	private BeatScheduleRepository beatScheduleRepository;
69
	@Autowired
70
	private LeadRouteRepository leadRouteRepository;
71
	@Autowired
36650 ranu 72
	private com.spice.profitmandi.dao.service.BeatPlanQueryService beatPlanQueryService;
73
	@Autowired
36618 ranu 74
	private AuthUserLocationRepository authUserLocationRepository;
75
	@Autowired
76
	private LeadRepository leadRepository;
77
	@Autowired
78
	private PublicHolidaysRepository publicHolidaysRepository;
79
	@Autowired
80
	private com.spice.profitmandi.service.GeocodingService geocodingService;
81
	@Autowired
82
	private CookiesProcessor cookiesProcessor;
83
	@Autowired
84
	private ResponseSender responseSender;
36686 ranu 85
	@Autowired
86
	private FofoStoreRepository fofoStoreRepository;
36618 ranu 87
 
88
	@GetMapping(value = "/beatPlan")
36686 ranu 89
	public String beatPlan(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
90
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
36618 ranu 91
		return "beat-plan";
92
	}
93
 
36650 ranu 94
	@Autowired
95
	private com.spice.profitmandi.dao.repository.dtr.LeadLiveLocationRepository leadLiveLocationRepositoryAuto;
36651 ranu 96
	@Autowired
97
	private com.spice.profitmandi.dao.repository.dtr.LeadActivityRepository leadActivityRepositoryAuto;
36663 ranu 98
	@Autowired
99
	private com.spice.profitmandi.dao.repository.dtr.UserRepository userRepositoryAuto;
100
	@Autowired
101
	private com.spice.profitmandi.common.web.client.RestClient restClientAuto;
102
	@Autowired
103
	private com.spice.profitmandi.dao.repository.auth.LocationTrackingRepository locationTrackingRepositoryAuto;
36650 ranu 104
 
36655 ranu 105
	private static Double parseDoubleOrNull(String s) {
106
		if (s == null || s.trim().isEmpty()) return null;
107
		try {
108
			return Double.parseDouble(s.trim());
109
		} catch (NumberFormatException e) {
110
			return null;
111
		}
112
	}
113
 
114
	private static double haversineKm(double lat1, double lng1, double lat2, double lng2) {
115
		double R = 6371;
116
		double dLat = Math.toRadians(lat2 - lat1);
117
		double dLng = Math.toRadians(lng2 - lng1);
118
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
119
				+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
120
				* Math.sin(dLng / 2) * Math.sin(dLng / 2);
121
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
122
		return R * c;
123
	}
124
 
36711 ranu 125
    // Mirrors the JS recalcDay() formula. Used by schedule/repeat endpoints
126
    // which create fresh BeatSchedule rows — they need to fill totals from the
127
    // existing beat_route table, not from anything the client posted.
128
    // Returns {totalKm, totalMins}.
129
    private double[] computeDayTotals(int beatId, int dayNumber, String endAction) {
130
        Beat beat = beatRepository.selectById(beatId);
131
        if (beat == null) return new double[]{0d, 0d};
132
 
133
        List<BeatRoute> dayRoutes = beatRouteRepository.selectByBeatId(beatId).stream()
134
                .filter(r -> r.getDayNumber() == dayNumber)
135
                .sorted(java.util.Comparator.comparingInt(BeatRoute::getSequenceOrder))
136
                .collect(Collectors.toList());
137
        if (dayRoutes.isEmpty()) return new double[]{0d, 0d};
138
 
139
        List<Integer> fofoIds = dayRoutes.stream().map(BeatRoute::getFofoId).distinct().collect(Collectors.toList());
140
        Map<Integer, FofoStore> storeMap = new HashMap<>();
141
        try {
142
            for (FofoStore fs : fofoStoreRepository.selectByRetailerIds(fofoIds)) {
143
                storeMap.put(fs.getId(), fs);
144
            }
145
        } catch (Exception ignored) { /* fall through with empty map */ }
146
 
147
        double ROAD_FACTOR = 1.3;
148
        double AVG_SPEED = 30.0; // km/h
149
        int VISIT_MINS = 30;
150
 
151
        Double prevLat = parseDoubleOrNull(beat.getStartLatitude());
152
        Double prevLng = parseDoubleOrNull(beat.getStartLongitude());
153
 
154
        double totalKm = 0d;
155
        for (BeatRoute r : dayRoutes) {
156
            FofoStore fs = storeMap.get(r.getFofoId());
157
            if (fs == null) continue;
158
            Double curLat = parseDoubleOrNull(fs.getLatitude());
159
            Double curLng = parseDoubleOrNull(fs.getLongitude());
160
            if (prevLat != null && prevLng != null && curLat != null && curLng != null) {
161
                totalKm += haversineKm(prevLat, prevLng, curLat, curLng) * ROAD_FACTOR;
162
            }
163
            if (curLat != null && curLng != null) {
164
                prevLat = curLat;
165
                prevLng = curLng;
166
            }
167
        }
168
 
169
        // Return-home leg only when end_action='HOME'
170
        if ("HOME".equalsIgnoreCase(endAction)) {
171
            Double homeLat = parseDoubleOrNull(beat.getStartLatitude());
172
            Double homeLng = parseDoubleOrNull(beat.getStartLongitude());
173
            if (prevLat != null && prevLng != null && homeLat != null && homeLng != null) {
174
                totalKm += haversineKm(prevLat, prevLng, homeLat, homeLng) * ROAD_FACTOR;
175
            }
176
        }
177
 
178
        double totalMins = (totalKm / AVG_SPEED) * 60.0 + dayRoutes.size() * VISIT_MINS;
179
        return new double[]{Math.round(totalKm * 1000d) / 1000d, Math.round(totalMins)};
180
    }
181
 
36663 ranu 182
	// ====================== ASSIGN VISIT ======================
183
	// Day View "Assign Visit" — lets an admin pick parties (stores) for a specific
184
	// auth user on a specific date and pushes them as visit tasks to the v2
185
	// /profitmandi-web/v2/beat-tracking/batch endpoint.
186
 
36716 ranu 187
	// List of parties (stores) assigned to this auth user + their dtr.users.id.
188
	// When date+beatId are passed, each party is also tagged with:
189
	//   inBeat        = is this store part of the scheduled beat's route on that date
190
	//   existingAgendas[] = agendas already saved for this store on that date (so the
191
	//                       modal can pre-fill them and let the user refill rather than re-assign)
36663 ranu 192
	@GetMapping(value = "/beatPlan/assignVisit/parties")
36716 ranu 193
	public ResponseEntity<?> assignVisitParties(
194
			@RequestParam int authUserId,
195
			@RequestParam(required = false) String date,
196
			@RequestParam(required = false) Integer beatId) throws Exception {
36663 ranu 197
		AuthUser au = authRepository.selectById(authUserId);
198
		if (au == null) return responseSender.badRequest("Auth user not found");
199
 
200
		// Map auth_user → dtr.users via email
201
		Integer dtrUserId = null;
202
		try {
203
			com.spice.profitmandi.dao.entity.dtr.User dtrUser =
204
					userRepositoryAuto.selectByEmailId(au.getEmailId());
205
			if (dtrUser != null) dtrUserId = dtrUser.getId();
206
		} catch (Exception ignored) {
207
		}
208
 
36716 ranu 209
		// Parse optional date
210
		LocalDate parsedDate = null;
211
		if (date != null && !date.isEmpty()) {
212
			try {
213
				parsedDate = LocalDate.parse(date);
214
			} catch (Exception ignored) {
215
			}
216
		}
217
 
218
		// Build (fofoId → dayNumber) of partners already in the beat's scheduled route for this date
219
		Set<Integer> inBeatFofoIds = new HashSet<>();
220
		if (beatId != null && parsedDate != null) {
221
			final LocalDate dateF = parsedDate; // capture for lambda (parsedDate is reassigned earlier so not effectively final)
222
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beatId);
223
			BeatSchedule match = schedules.stream()
224
					.filter(s -> s.getStartDate() != null && s.getStartDate().equals(dateF))
225
					.findFirst().orElse(null);
226
			if (match != null) {
227
				List<BeatRoute> routes = beatRouteRepository.selectByBeatId(beatId);
228
				routes.stream()
229
						.filter(r -> r.getDayNumber() == match.getDayNumber() && r.isActive())
230
						.forEach(r -> inBeatFofoIds.add(r.getFofoId()));
231
			}
232
		}
233
 
234
		// Build (fofoId → existingAgendas) and (fofoId → existingDescription) from
235
		// any already-saved location_tracking rows for this user on this date.
236
		// Agenda is stored as task_name = "agenda1, agenda2 | OutletName"
237
		// so we split on " | " to peel the outlet suffix off, then split agendas by ", ".
238
		// Description is stored on task_description (free text).
239
		Map<Integer, List<String>> existingAgendaByFofo = new HashMap<>();
240
		Map<Integer, String> existingDescByFofo = new HashMap<>();
241
		Map<Integer, Integer> existingTrackingIdByFofo = new HashMap<>();
242
		if (dtrUserId != null && parsedDate != null) {
243
			List<com.spice.profitmandi.dao.entity.auth.LocationTracking> existing =
244
					locationTrackingRepositoryAuto.findByUserAndDate(dtrUserId, parsedDate);
245
			for (com.spice.profitmandi.dao.entity.auth.LocationTracking lt : existing) {
246
				if (!"franchisee-visit".equals(lt.getTaskType())) continue;
247
				if (existingAgendaByFofo.containsKey(lt.getTaskId())) continue; // first wins
248
				String taskName = lt.getTaskName() == null ? "" : lt.getTaskName();
249
				String agendaPart = taskName;
250
				int pipeIdx = taskName.lastIndexOf(" | ");
251
				if (pipeIdx > 0) agendaPart = taskName.substring(0, pipeIdx);
252
				List<String> agendas = new ArrayList<>();
253
				for (String a : agendaPart.split(",")) {
254
					String trimmed = a.trim();
255
					if (!trimmed.isEmpty()) agendas.add(trimmed);
256
				}
257
				existingAgendaByFofo.put(lt.getTaskId(), agendas);
258
				existingDescByFofo.put(lt.getTaskId(), lt.getTaskDescription() != null ? lt.getTaskDescription() : "");
259
				existingTrackingIdByFofo.put(lt.getTaskId(), lt.getId());
260
			}
261
		}
262
 
36663 ranu 263
		Map<Integer, List<Integer>> mapping = csService.getAuthUserIdPartnerIdMapping();
264
		List<Integer> fofoIds = mapping.get(authUserId);
265
 
266
		List<Map<String, Object>> parties = new ArrayList<>();
267
		if (fofoIds != null && !fofoIds.isEmpty()) {
268
			List<FofoStore> stores = fofoStoreRepository.selectByRetailerIds(fofoIds);
269
			Map<Integer, CustomRetailer> retailerMap = retailerService.getFofoRetailers(fofoIds);
270
			for (FofoStore store : stores) {
271
				if (!store.isActive() || store.isClosed()) continue;
272
				CustomRetailer retailer = retailerMap.get(store.getId());
273
				Map<String, Object> p = new HashMap<>();
274
				p.put("fofoStoreId", store.getId());
275
				p.put("code", store.getCode());
276
				p.put("outletName", store.getOutletName() != null ? store.getOutletName()
277
						: (retailer != null ? retailer.getBusinessName() : "Store #" + store.getId()));
278
				p.put("latitude", store.getLatitude());
279
				p.put("longitude", store.getLongitude());
280
				p.put("city", retailer != null && retailer.getAddress() != null ? retailer.getAddress().getCity() : null);
36716 ranu 281
				p.put("inBeat", inBeatFofoIds.contains(store.getId()));
282
				p.put("existingAgendas", existingAgendaByFofo.getOrDefault(store.getId(), new ArrayList<>()));
283
				p.put("existingDescription", existingDescByFofo.getOrDefault(store.getId(), ""));
284
				p.put("existingTrackingId", existingTrackingIdByFofo.get(store.getId()));
36663 ranu 285
				parties.add(p);
286
			}
36716 ranu 287
			// In-beat first, then by code
288
			parties.sort((a, b) -> {
289
				boolean ai = Boolean.TRUE.equals(a.get("inBeat"));
290
				boolean bi = Boolean.TRUE.equals(b.get("inBeat"));
291
				if (ai != bi) return ai ? -1 : 1;
292
				return String.valueOf(a.get("code")).compareToIgnoreCase(String.valueOf(b.get("code")));
293
			});
36663 ranu 294
		}
295
 
296
		Map<String, Object> result = new HashMap<>();
297
		result.put("dtrUserId", dtrUserId);
298
		result.put("authUserId", authUserId);
299
		result.put("userName", au.getFirstName() + " " + au.getLastName());
300
		result.put("parties", parties);
36716 ranu 301
		result.put("agendaOptions", com.spice.profitmandi.dao.enumuration.dtr.VisitAgenda.labels());
36663 ranu 302
		return responseSender.ok(result);
303
	}
304
 
305
	// Submit assignment — accepts a JSON body, builds the v2 payload, posts it
306
	@PostMapping(value = "/beatPlan/assignVisit/submit")
307
	public ResponseEntity<?> assignVisitSubmit(
308
			HttpServletRequest request,
309
			@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) throws Exception {
310
 
311
		Integer authUserId = body.get("authUserId") != null ? ((Number) body.get("authUserId")).intValue() : null;
312
		String planDate = (String) body.get("planDate");
313
		List<Map<String, Object>> selected = (List<Map<String, Object>>) body.get("parties");
314
		if (authUserId == null || planDate == null || selected == null || selected.isEmpty()) {
315
			return responseSender.badRequest("authUserId, planDate and parties are required");
316
		}
317
 
318
		AuthUser au = authRepository.selectById(authUserId);
319
		if (au == null) return responseSender.badRequest("Auth user not found");
320
 
321
		// Map auth → dtr.users.id (this is the userId the v2 endpoint expects)
322
		com.spice.profitmandi.dao.entity.dtr.User dtrUser;
323
		try {
324
			dtrUser = userRepositoryAuto.selectByEmailId(au.getEmailId());
325
		} catch (Exception e) {
326
			return responseSender.badRequest("Failed to look up dtr.users for this auth user");
327
		}
328
		if (dtrUser == null) {
329
			return responseSender.badRequest("No dtr.users record found for auth user " + authUserId);
330
		}
331
		int dtrUserId = dtrUser.getId();
332
 
333
		// Persist directly via the shared DAO — mirrors BeatTrackingController.createBatch
334
		// in profitmandi-web. We can't autowire a controller across WARs, but
335
		// LocationTrackingRepository lives in profitmandi-dao and is shared.
336
		LocalDate taskDate;
337
		try {
338
			taskDate = LocalDate.parse(planDate);
339
		} catch (Exception e) {
340
			return responseSender.badRequest("Invalid planDate (expected yyyy-MM-dd): " + planDate);
341
		}
342
 
36716 ranu 343
		// Existing rows for this user on this date — keyed by fofoStoreId.
344
		// If a row already exists for a party, we UPDATE its agenda instead of
345
		// creating a duplicate (this is the "refill agenda" path for already-
346
		// assigned parties).
347
		Map<Integer, com.spice.profitmandi.dao.entity.auth.LocationTracking> existingByFofo = new HashMap<>();
348
		for (com.spice.profitmandi.dao.entity.auth.LocationTracking lt :
349
				locationTrackingRepositoryAuto.findByUserAndDate(dtrUserId, taskDate)) {
350
			if (!"franchisee-visit".equals(lt.getTaskType())) continue;
351
			existingByFofo.putIfAbsent(lt.getTaskId(), lt);
352
		}
353
 
354
		// Defence-in-depth: Assign Visit is only valid for today's run. Hiding the
355
		// button on the UI isn't enough — block at the API too.
356
		if (!taskDate.equals(LocalDate.now())) {
357
			return responseSender.badRequest("Visits can only be assigned for today's date (" + LocalDate.now() + ")");
358
		}
359
 
36663 ranu 360
		LocalDateTime now = LocalDateTime.now();
36716 ranu 361
		int createdCount = 0, updatedCount = 0;
36663 ranu 362
 
363
		for (Map<String, Object> p : selected) {
364
			Integer fofoStoreId = ((Number) p.get("fofoStoreId")).intValue();
365
			String outletName = (String) p.get("outletName");
366
			String lat = (String) p.get("latitude");
367
			String lng = (String) p.get("longitude");
36716 ranu 368
			String description = (String) p.get("description");
369
			if (description != null) description = description.trim();
370
			if (description == null) description = "";
36663 ranu 371
 
36716 ranu 372
			// Multi-agenda: accept agendas[] (new format) or fall back to agenda (legacy single)
373
			List<String> agendas = new ArrayList<>();
374
			Object rawAgendas = p.get("agendas");
375
			if (rawAgendas instanceof List) {
376
				for (Object o : (List<?>) rawAgendas) {
377
					if (o != null) {
378
						String s = String.valueOf(o).trim();
379
						if (!s.isEmpty()) agendas.add(s);
380
					}
381
				}
382
			}
383
			if (agendas.isEmpty()) {
384
				String single = (String) p.get("agenda");
385
				if (single != null && !single.trim().isEmpty()) agendas.add(single.trim());
386
			}
387
			if (agendas.isEmpty()) agendas.add("Visit");
388
			String agendaJoined = String.join(", ", agendas);
389
 
36663 ranu 390
			String visitLocation = (lat != null && lng != null && !lat.isEmpty() && !lng.isEmpty())
391
					? (lat + "," + lng) : "0.0000,0.0000";
392
 
393
			String displayName = (outletName != null && !outletName.isEmpty()) ? outletName : ("Store #" + fofoStoreId);
36716 ranu 394
			String newTaskName = agendaJoined + " | " + displayName;
36663 ranu 395
 
36716 ranu 396
			com.spice.profitmandi.dao.entity.auth.LocationTracking existing = existingByFofo.get(fofoStoreId);
397
			if (existing != null) {
398
				// Refill — agenda (task_name), description, and visit location change
399
				existing.setTaskName(newTaskName);
400
				existing.setTaskDescription(description);
401
				existing.setVisitLocation(visitLocation);
402
				existing.setUpdatedTimestamp(now);
403
				locationTrackingRepositoryAuto.persist(existing);
404
				updatedCount++;
405
				continue;
406
			}
407
 
36663 ranu 408
			com.spice.profitmandi.dao.entity.auth.LocationTracking row =
409
					new com.spice.profitmandi.dao.entity.auth.LocationTracking();
410
			row.setUserId(dtrUserId);
411
			row.setDeviceId("0");
412
			row.setTaskId(fofoStoreId);
413
			row.setTaskDate(taskDate);
36716 ranu 414
			row.setTaskName(newTaskName);
415
			row.setTaskDescription(description);
36663 ranu 416
			row.setTaskType("franchisee-visit");
417
			row.setMarkType("PENDING");
418
			row.setAddress("");
419
			row.setVisitLocation(visitLocation);
420
			row.setCheckInLatLng("0.0000,0.0000");
421
			row.setCheckOutLatLng("0.0000,0.0000");
422
			row.setCheckInTime(java.time.LocalTime.MIDNIGHT);
423
			row.setCheckOutTime(java.time.LocalTime.MIDNIGHT);
424
			row.setTransitTime(java.time.LocalTime.MIDNIGHT);
425
			row.setTimeSpent(java.time.LocalTime.MIDNIGHT);
426
			row.setEstimatedTime(java.time.LocalTime.MIDNIGHT);
427
			row.setSessionStartTime(java.time.LocalTime.MIDNIGHT);
428
			row.setSessionEndTime(java.time.LocalTime.MIDNIGHT);
429
			row.setTotalDistance("0.0");
430
			row.setStatus(false);
431
			row.setCreatedTimestamp(now);
432
			row.setUpdatedTimestamp(now);
433
 
434
			// Do NOT try/catch this — if persist throws, let it propagate so
435
			// @Transactional(rollbackFor = Throwable.class) rolls back cleanly.
436
			locationTrackingRepositoryAuto.persist(row);
36716 ranu 437
			createdCount++;
36663 ranu 438
		}
36716 ranu 439
		LOGGER.info("assignVisit dtrUserId={} created={} updated={}", dtrUserId, createdCount, updatedCount);
36663 ranu 440
 
441
		Map<String, Object> result = new HashMap<>();
442
		result.put("status", true);
36716 ranu 443
		result.put("createdCount", createdCount);
444
		result.put("updatedCount", updatedCount);
36663 ranu 445
		result.put("dtrUserId", dtrUserId);
36716 ranu 446
		StringBuilder msg = new StringBuilder();
447
		if (createdCount > 0)
448
			msg.append(createdCount).append(" new visit").append(createdCount == 1 ? "" : "s").append(" assigned");
449
		if (updatedCount > 0) {
450
			if (msg.length() > 0) msg.append(", ");
451
			msg.append(updatedCount).append(" existing agenda").append(updatedCount == 1 ? "" : "s").append(" refilled");
452
		}
453
		msg.append(" for ").append(au.getFirstName()).append(" ").append(au.getLastName());
454
		result.put("message", msg.toString());
36663 ranu 455
		return responseSender.ok(result);
456
	}
457
 
36686 ranu 458
	@GetMapping(value = "/beatPlanWindow")
459
	public String beatPlanWindow(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
460
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
461
		return "beat-plan-window";
36655 ranu 462
	}
463
 
36668 ranu 464
	// Helpers for XLSX bulk upload
465
	private static String readCell(org.apache.poi.ss.usermodel.Cell cell) {
466
		if (cell == null) return null;
467
		switch (cell.getCellType()) {
468
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
469
				return cell.getStringCellValue();
470
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
471
				if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
472
					return cell.getDateCellValue().toInstant()
473
							.atZone(java.time.ZoneId.systemDefault()).toLocalDate().toString();
474
				}
475
				double n = cell.getNumericCellValue();
476
				return (n == Math.floor(n)) ? String.valueOf((long) n) : String.valueOf(n);
477
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN:
478
				return String.valueOf(cell.getBooleanCellValue());
479
			case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA:
480
				return cell.getCellFormula();
481
			default:
482
				return null;
36655 ranu 483
		}
484
	}
485
 
486
	// ====================== ONE-TIME LAT/LNG MIGRATION ======================
487
	// For each active fofo_store, compare its stored lat/lng with the geocoded
488
	// address lat/lng (cached in Redis). If the gap is > thresholdKm (default 5)
489
	// OR the store has no lat/lng yet, update the store with the geocoded
490
	// coordinates. Otherwise keep the existing values.
491
	//
492
	// Usage:
493
	//   GET /beatPlan/migrateStoreLatLng              -> dry run, default 5km, all
494
	//   GET /beatPlan/migrateStoreLatLng?apply=true   -> actually update
495
	//   ?thresholdKm=3      -> use a different threshold
496
	//   ?limit=100          -> process only N stores (for staged runs)
497
	@GetMapping(value = "/beatPlan/migrateStoreLatLng")
498
	public ResponseEntity<?> migrateStoreLatLng(
499
			@RequestParam(required = false, defaultValue = "false") boolean apply,
500
			@RequestParam(required = false, defaultValue = "5") double thresholdKm,
36660 ranu 501
			@RequestParam(required = false, defaultValue = "0") int limit,
502
			@RequestParam(required = false, defaultValue = "0") int offset) throws ProfitMandiBusinessException {
36655 ranu 503
 
36660 ranu 504
		List<FofoStore> all = fofoStoreRepository.selectActiveStores();
505
		int totalAvailable = all.size();
506
		// offset + limit so this can be run in batches against large datasets
507
		int from = Math.max(0, Math.min(offset, totalAvailable));
508
		int to = limit > 0 ? Math.min(from + limit, totalAvailable) : totalAvailable;
509
		List<FofoStore> stores = all.subList(from, to);
36655 ranu 510
 
511
		List<Integer> ids = stores.stream().map(FofoStore::getId).collect(Collectors.toList());
512
		Map<Integer, CustomRetailer> retailerMap = retailerService.getFofoRetailers(ids);
513
 
514
		int total = stores.size();
515
		int updated = 0, kept = 0, noAddress = 0, noGeocode = 0, errored = 0;
516
		List<Map<String, Object>> changes = new ArrayList<>();
517
 
518
		for (FofoStore store : stores) {
519
			try {
520
				CustomRetailer retailer = retailerMap.get(store.getId());
521
				if (retailer == null || retailer.getAddress() == null) {
522
					noAddress++;
523
					continue;
524
				}
525
 
526
				String geoAddr = com.spice.profitmandi.service.GeocodingService.buildGeoAddress(
527
						retailer.getAddress().getLine1(), retailer.getAddress().getCity(),
528
						retailer.getAddress().getState(), retailer.getAddress().getPinCode());
529
				if (geoAddr == null || geoAddr.isEmpty()) {
530
					noAddress++;
531
					continue;
532
				}
533
 
534
				double[] coords = geocodingService.geocodeAddress(geoAddr);
535
				if (coords == null) {
536
					noGeocode++;
537
					continue;
538
				}
539
 
540
				Double existingLat = parseDoubleOrNull(store.getLatitude());
541
				Double existingLng = parseDoubleOrNull(store.getLongitude());
542
 
543
				boolean shouldUpdate;
544
				double distKm = -1;
545
				String reason;
546
				if (existingLat == null || existingLng == null) {
547
					shouldUpdate = true;
548
					reason = "missing existing lat/lng";
549
				} else {
550
					distKm = haversineKm(existingLat, existingLng, coords[0], coords[1]);
551
					shouldUpdate = distKm > thresholdKm;
552
					reason = shouldUpdate
553
							? "gap " + Math.round(distKm * 10.0) / 10.0 + "km > " + thresholdKm + "km"
554
							: "gap " + Math.round(distKm * 10.0) / 10.0 + "km within " + thresholdKm + "km";
555
				}
556
 
557
				if (shouldUpdate) {
558
					if (apply) {
559
						store.setLatitude(String.valueOf(coords[0]));
560
						store.setLongitude(String.valueOf(coords[1]));
561
						fofoStoreRepository.persist(store);
562
					}
563
					updated++;
564
					Map<String, Object> ch = new HashMap<>();
565
					ch.put("storeId", store.getId());
566
					ch.put("code", store.getCode());
567
					ch.put("oldLat", existingLat);
568
					ch.put("oldLng", existingLng);
569
					ch.put("newLat", coords[0]);
570
					ch.put("newLng", coords[1]);
571
					ch.put("distKm", distKm >= 0 ? Math.round(distKm * 10.0) / 10.0 : null);
572
					ch.put("reason", reason);
573
					changes.add(ch);
574
				} else {
575
					kept++;
576
				}
577
			} catch (Exception e) {
578
				errored++;
579
				LOGGER.warn("Geocode/migrate failed for fofoId={}: {}", store.getId(), e.getMessage());
580
			}
581
		}
582
 
583
		Map<String, Object> result = new HashMap<>();
584
		result.put("mode", apply ? "APPLIED" : "DRY RUN — pass &apply=true to actually update");
585
		result.put("thresholdKm", thresholdKm);
36660 ranu 586
		result.put("totalAvailable", totalAvailable);  // total active stores in DB
587
		result.put("offset", from);
588
		result.put("processed", total);                 // stores processed this run
589
		result.put("nextOffset", to);                   // next offset to resume (or = totalAvailable when done)
590
		result.put("done", to >= totalAvailable);
36655 ranu 591
		result.put("updated", updated);
592
		result.put("kept", kept);
593
		result.put("noAddress", noAddress);
594
		result.put("noGeocode", noGeocode);
595
		result.put("errored", errored);
596
		// Limit changes preview to avoid huge responses
597
		result.put("changes", changes.size() > 200 ? changes.subList(0, 200) : changes);
598
		result.put("changesShownCount", Math.min(changes.size(), 200));
599
		return responseSender.ok(result);
600
	}
601
 
36651 ranu 602
	// ====================== EDIT BEAT ======================
603
	// Update an existing beat — name + partner stops (routes).
604
	// Schedules are NOT touched here; manage them via calendar drag-drop.
605
	@PostMapping(value = "/beatPlan/updateBeat")
606
	public ResponseEntity<?> updateBeat(
607
			HttpServletRequest request,
608
			@RequestParam int beatId,
609
			@RequestParam String planData) throws Exception {
610
 
611
		Beat beat = beatRepository.selectById(beatId);
612
		if (beat == null) return responseSender.badRequest("Beat not found");
613
 
614
		Gson gson = new Gson();
615
		Type type = new TypeToken<Map<String, Object>>() {
616
		}.getType();
617
		Map<String, Object> plan = gson.fromJson(planData, type);
618
 
619
		List<Map<String, Object>> days = (List<Map<String, Object>>) plan.get("days");
620
		if (days == null || days.isEmpty()) return responseSender.badRequest("No days provided");
621
 
622
		// Update name if changed (and not colliding with another beat)
623
		String newName = plan.get("beatName") != null ? ((String) plan.get("beatName")).trim() : beat.getName();
624
		if (newName != null && !newName.equalsIgnoreCase(beat.getName())) {
36698 ranu 625
			// Make sure no other ACTIVE beat for this user already uses this name.
626
			// Soft-deleted beats keep their name in the table; we don't want them
627
			// to block a legitimate rename.
628
			boolean collides = beatRepository.selectActiveByAuthUserId(beat.getAuthUserId()).stream()
36651 ranu 629
					.anyMatch(b -> b.getId() != beat.getId()
630
							&& b.getName() != null
631
							&& newName.equalsIgnoreCase(b.getName().trim()));
632
			if (collides) return responseSender.badRequest("Another beat with this name already exists");
633
			beat.setName(newName);
634
		}
635
 
636
		// Update start location from first day if present
637
		Map<String, Object> firstDay = days.get(0);
638
		if (firstDay.get("startLocationName") != null)
639
			beat.setStartLocationName((String) firstDay.get("startLocationName"));
640
		if (firstDay.get("startLatitude") != null) beat.setStartLatitude((String) firstDay.get("startLatitude"));
641
		if (firstDay.get("startLongitude") != null) beat.setStartLongitude((String) firstDay.get("startLongitude"));
642
 
36681 ranu 643
		int oldTotalDays = beat.getTotalDays();
644
		int newTotalDays = days.size();
645
 
646
		// Hard rule: you cannot grow the number of days on an existing beat.
647
		// If you need more days, create a new beat. (Shrinking is allowed and
648
		// the schedules for dropped day numbers are cleaned below.)
649
		if (newTotalDays > oldTotalDays) {
650
			return responseSender.badRequest(
651
					"Cannot increase the number of days on an existing beat. "
652
							+ "Original: " + oldTotalDays + " day(s), tried: " + newTotalDays + " day(s). "
653
							+ "Please create a new beat for additional days.");
654
		}
655
		beat.setTotalDays(newTotalDays);
656
 
657
		// Replace routes (partner stops). Schedules stay intact (except for
36711 ranu 658
        // dayNumber > newTotalDays cleanup + total km/min refresh below).
36651 ranu 659
		beatRouteRepository.deleteByBeatId(beatId);
36681 ranu 660
		// Collect lead IDs the user kept on the plan
36651 ranu 661
		Set<Integer> keptLeadIds = new HashSet<>();
662
		for (int d = 0; d < days.size(); d++) {
663
			Map<String, Object> day = days.get(d);
664
			int dayNumber = d + 1;
665
			List<Map<String, Object>> visits = (List<Map<String, Object>>) day.get("visits");
666
			if (visits == null) continue;
667
			int partnerSeq = 0;
668
			for (int i = 0; i < visits.size(); i++) {
669
				Map<String, Object> v = visits.get(i);
670
				if ("lead".equals(v.get("type"))) {
671
					keptLeadIds.add(((Number) v.get("id")).intValue());
672
					continue; // leads live in lead_route, handled below
673
				}
674
				BeatRoute route = new BeatRoute();
675
				route.setBeatId(beatId);
676
				route.setFofoId(((Number) v.get("id")).intValue());
677
				route.setSequenceOrder(partnerSeq++);
678
				route.setDayNumber(dayNumber);
679
				route.setActive(true);
36711 ranu 680
                if (v.get("distanceFromPrevKm") != null)
681
                    route.setDistanceFromPrevKm(((Number) v.get("distanceFromPrevKm")).doubleValue());
682
                if (v.get("timeFromPrevMins") != null)
683
                    route.setTimeFromPrevMins(((Number) v.get("timeFromPrevMins")).intValue());
36651 ranu 684
				beatRouteRepository.persist(route);
685
			}
686
		}
687
 
36681 ranu 688
		// If the beat shrank, drop schedule rows for day numbers that no longer exist
689
		if (newTotalDays < oldTotalDays) {
690
			List<BeatSchedule> currentSchedules = beatScheduleRepository.selectByBeatId(beatId);
691
			for (BeatSchedule s : currentSchedules) {
692
				if (s.getDayNumber() > newTotalDays) beatScheduleRepository.delete(s);
693
			}
694
		}
695
 
36711 ranu 696
        // Refresh the day-level totals on every remaining schedule row so they
697
        // reflect the post-edit route. Previously updateBeat left these stale
698
        // (or NULL, for beats created before this fix), which is what the user
699
        // reported. Keyed by dayNumber so multi-instance beats all get updated.
700
        Map<Integer, Map<String, Object>> dayByNumber = new HashMap<>();
701
        for (int d = 0; d < days.size(); d++) {
702
            dayByNumber.put(d + 1, days.get(d));
703
        }
704
        List<BeatSchedule> allSchedules = beatScheduleRepository.selectByBeatId(beatId);
705
        for (BeatSchedule s : allSchedules) {
706
            Map<String, Object> day = dayByNumber.get(s.getDayNumber());
707
            if (day == null) continue;
708
            if (day.get("totalDistanceKm") != null)
709
                s.setTotalDistanceKm(((Number) day.get("totalDistanceKm")).doubleValue());
710
            if (day.get("totalTimeMins") != null)
711
                s.setTotalTimeMins(((Number) day.get("totalTimeMins")).intValue());
712
        }
713
 
36681 ranu 714
		// Process per-lead actions sent from the editor's removed-leads popup.
715
		// Each entry: {leadId, action: "cancel"|"reschedule", toDate?: "yyyy-MM-dd"}.
716
		// - cancel: mark the lead's current APPROVED row for this beat as CANCELLED.
717
		// - reschedule: cancel here, then create a fresh APPROVED LeadRoute on
718
		//   whichever beat this user has scheduled on toDate. If no beat exists
719
		//   on toDate, the whole update fails (so the caller can prompt again).
720
		int leadsCancelled = 0, leadsRescheduled = 0;
721
		List<String> leadFailures = new ArrayList<>();
722
		String removedLeadActionsJson = (String) plan.get("removedLeadActions");
723
		if (removedLeadActionsJson != null && !removedLeadActionsJson.isEmpty()) {
724
			Type listType = new TypeToken<List<Map<String, Object>>>() {
725
			}.getType();
726
			List<Map<String, Object>> actions = gson.fromJson(removedLeadActionsJson, listType);
727
 
728
			List<LeadRoute> beatLeads = leadRouteRepository.selectByBeatId(beatId);
729
 
730
			for (Map<String, Object> act : actions) {
731
				int leadId = ((Number) act.get("leadId")).intValue();
732
				String mode = (String) act.get("action");
733
 
734
				// Find this lead's most-recent APPROVED row on this beat
735
				LeadRoute current = beatLeads.stream()
736
						.filter(r -> r.getLeadId() == leadId && "APPROVED".equals(r.getStatus()))
737
						.findFirst().orElse(null);
738
				if (current == null) continue; // already removed/cancelled; nothing to do
739
 
740
				if ("reschedule".equalsIgnoreCase(mode)) {
741
					String toDateStr = (String) act.get("toDate");
742
					if (toDateStr == null || toDateStr.isEmpty()) {
743
						leadFailures.add("Lead " + leadId + ": reschedule date missing");
744
						continue;
745
					}
746
					LocalDate toDate = LocalDate.parse(toDateStr);
747
 
748
					// Find ANY beat this user has scheduled on toDate
749
					Beat targetBeat = null;
750
					Integer targetDayNumber = null;
751
					List<Beat> userBeats = beatRepository.selectActiveByAuthUserId(beat.getAuthUserId());
752
					for (Beat b : userBeats) {
753
						List<BeatSchedule> sl = beatScheduleRepository.selectByBeatId(b.getId());
754
						for (BeatSchedule s : sl) {
755
							if (s.getStartDate() != null && s.getStartDate().equals(toDate)) {
756
								targetBeat = b;
757
								targetDayNumber = s.getDayNumber();
758
								break;
759
							}
760
						}
761
						if (targetBeat != null) break;
762
					}
763
					if (targetBeat == null) {
764
						return responseSender.badRequest(
765
								"No beat is scheduled for this user on " + toDateStr
766
										+ ". Pick a different date for lead " + leadId
767
										+ ", or choose Cancel for it.");
768
					}
769
 
770
					// Cancel the current attachment to this beat
771
					current.setStatus("CANCELLED");
772
					current.setUpdatedTimestamp(LocalDateTime.now());
773
 
774
					// Create the new attachment on the target beat/date
775
					LeadRoute fresh = new LeadRoute();
776
					fresh.setBeatId(targetBeat.getId());
777
					fresh.setLeadId(leadId);
778
					fresh.setNearestStoreId(current.getNearestStoreId());
779
					fresh.setScheduleDate(toDate);
780
					fresh.setSequenceOrder(9999); // append; the planner can reorder
781
					fresh.setStatus("APPROVED");
782
					fresh.setRequestedBy(current.getRequestedBy());
783
					fresh.setApprovedBy(current.getApprovedBy());
784
					fresh.setApprovedTimestamp(LocalDateTime.now());
785
					fresh.setCreatedTimestamp(LocalDateTime.now());
786
					fresh.setUpdatedTimestamp(LocalDateTime.now());
787
					leadRouteRepository.persist(fresh);
788
 
789
					LeadActivity la = new LeadActivity();
790
					la.setLeadId(leadId);
791
					la.setRemark("Rescheduled from beat '" + beat.getName() + "' to '"
792
							+ targetBeat.getName() + "' on " + toDateStr + " (day " + targetDayNumber + ")");
793
					la.setAuthId(0);
794
					la.setCreatedTimestamp(LocalDateTime.now());
795
					leadActivityRepositoryAuto.persist(la);
796
					leadsRescheduled++;
797
				} else {
798
					// cancel (default)
799
					current.setStatus("CANCELLED");
800
					current.setUpdatedTimestamp(LocalDateTime.now());
801
 
802
					LeadActivity la = new LeadActivity();
803
					la.setLeadId(leadId);
804
					la.setRemark("Cancelled from beat '" + beat.getName() + "' during edit");
805
					la.setAuthId(0);
806
					la.setCreatedTimestamp(LocalDateTime.now());
807
					leadActivityRepositoryAuto.persist(la);
808
					leadsCancelled++;
36651 ranu 809
				}
810
			}
811
		}
812
 
813
		Map<String, Object> response = new HashMap<>();
814
		response.put("status", true);
815
		response.put("planGroupId", String.valueOf(beat.getId()));
36681 ranu 816
		response.put("leadsCancelled", leadsCancelled);
817
		response.put("leadsRescheduled", leadsRescheduled);
818
		response.put("leadFailures", leadFailures);
819
		response.put("message", "Beat updated successfully"
820
				+ (leadsCancelled > 0 ? " (" + leadsCancelled + " lead(s) cancelled)" : "")
821
				+ (leadsRescheduled > 0 ? " (" + leadsRescheduled + " lead(s) rescheduled)" : ""));
36651 ranu 822
		return responseSender.ok(response);
823
	}
824
 
36681 ranu 825
	// Used by the edit-mode "removed leads" popup so the date picker can warn
826
	// upfront when the user picks a date that has no beat for them.
827
	@GetMapping(value = "/beatPlan/userBeatsOnDate")
828
	public ResponseEntity<?> userBeatsOnDate(
829
			@RequestParam int authUserId,
830
			@RequestParam String date) {
831
		LocalDate target;
832
		try {
833
			target = LocalDate.parse(date);
834
		} catch (Exception e) {
835
			return responseSender.badRequest("Invalid date");
836
		}
837
 
838
		List<Map<String, Object>> hits = new ArrayList<>();
839
		List<Beat> userBeats = beatRepository.selectActiveByAuthUserId(authUserId);
840
		for (Beat b : userBeats) {
841
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(b.getId());
842
			for (BeatSchedule s : schedules) {
843
				if (s.getStartDate() != null && s.getStartDate().equals(target)) {
844
					Map<String, Object> m = new HashMap<>();
845
					m.put("beatId", b.getId());
846
					m.put("beatName", b.getName());
847
					m.put("dayNumber", s.getDayNumber());
848
					hits.add(m);
849
				}
850
			}
851
		}
852
		Map<String, Object> result = new HashMap<>();
853
		result.put("date", date);
854
		result.put("authUserId", authUserId);
855
		result.put("beats", hits);
856
		return responseSender.ok(result);
857
	}
858
 
36686 ranu 859
	// ====================== BASE LOCATION MANAGEMENT ======================
860
	// Inline page that lets Sales L3+ pick a user and set their base (home)
861
	// location via map. Reads use the existing /beatPlan/getBaseLocation, writes
862
	// go through the L3+-guarded endpoint below.
863
	@GetMapping(value = "/beatPlan/baseLocationPage")
864
	public String baseLocationPage(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
865
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
866
		return "beat-plan-base-location";
36650 ranu 867
	}
868
 
869
	// Tabular JSON: one row per (beat, scheduled date) in [startDate, endDate].
870
	@GetMapping(value = "/beatPlan/scheduledList")
871
	public ResponseEntity<?> scheduledList(
872
			@RequestParam(required = false) String startDate,
873
			@RequestParam(required = false) String endDate) {
874
 
875
		LocalDate start, end;
876
		try {
877
			start = (startDate == null || startDate.isEmpty()) ? LocalDate.now() : LocalDate.parse(startDate);
878
			end = (endDate == null || endDate.isEmpty()) ? start.plusDays(7) : LocalDate.parse(endDate);
879
		} catch (Exception e) {
880
			return responseSender.badRequest("Invalid date — expected yyyy-MM-dd");
881
		}
882
 
883
		List<com.spice.profitmandi.dao.model.BeatDayDetails> beats =
884
				beatPlanQueryService.getAllScheduledBeats(start, end);
885
 
886
		// Resolve user names in bulk
887
		Set<Integer> userIds = beats.stream()
888
				.map(com.spice.profitmandi.dao.model.BeatDayDetails::getAuthUserId)
889
				.collect(java.util.stream.Collectors.toSet());
890
		Map<Integer, AuthUser> userMap = new HashMap<>();
891
		if (!userIds.isEmpty()) {
892
			authRepository.selectByIds(new ArrayList<>(userIds))
893
					.forEach(u -> userMap.put(u.getId(), u));
894
		}
895
 
896
		List<Map<String, Object>> rows = new ArrayList<>();
897
		for (com.spice.profitmandi.dao.model.BeatDayDetails b : beats) {
898
			AuthUser u = userMap.get(b.getAuthUserId());
899
			Map<String, Object> row = new HashMap<>();
900
			row.put("authUserId", b.getAuthUserId());
901
			row.put("userName", u != null ? (u.getFirstName() + " " + u.getLastName()) : "User #" + b.getAuthUserId());
902
			row.put("scheduleDate", b.getScheduleDate().toString());
903
			row.put("dayNumber", b.getDayNumber());
904
			row.put("beatId", b.getBeatId());
905
			row.put("beatName", b.getBeatName());
906
			row.put("beatColor", b.getBeatColor());
907
			row.put("partnerCount", b.getPartnerStops().size());
908
			row.put("leadCount", b.getLeadStops().size());
909
			row.put("visitCount", b.getPartnerStops().size() + b.getLeadStops().size());
910
			rows.add(row);
911
		}
912
 
913
		Map<String, Object> result = new HashMap<>();
914
		result.put("rows", rows);
915
		result.put("startDate", start.toString());
916
		result.put("endDate", end.toString());
917
		return responseSender.ok(result);
918
	}
919
 
920
	// JSON: beats running for (authUserId, date) — enriched with partner/lead names & coords
921
	@GetMapping(value = "/beatPlan/dayViewData")
922
	public ResponseEntity<?> beatPlanDayViewData(
923
			@RequestParam int authUserId,
924
			@RequestParam String date) throws ProfitMandiBusinessException {
925
 
926
		LocalDate localDate;
927
		try {
928
			localDate = LocalDate.parse(date);
929
		} catch (Exception e) {
930
			return responseSender.badRequest("Invalid date — expected yyyy-MM-dd");
931
		}
932
 
933
		List<com.spice.profitmandi.dao.model.BeatDayDetails> beats =
934
				beatPlanQueryService.getBeatsForUserOnDate(authUserId, localDate);
935
 
936
		// Collect all partner & lead IDs to fetch metadata in bulk
937
		Set<Integer> partnerIds = new HashSet<>();
938
		Set<Integer> leadIds = new HashSet<>();
939
		for (com.spice.profitmandi.dao.model.BeatDayDetails b : beats) {
940
			b.getPartnerStops().forEach(s -> partnerIds.add((Integer) s.get("fofoId")));
941
			b.getLeadStops().forEach(s -> leadIds.add((Integer) s.get("leadId")));
942
		}
943
 
944
		// Partners: name + geocoded lat/lng (geocoder is cached in Redis)
945
		Map<Integer, CustomRetailer> retailerMap = partnerIds.isEmpty()
946
				? new HashMap<>()
947
				: retailerService.getFofoRetailers(new ArrayList<>(partnerIds));
948
		Map<Integer, FofoStore> storeMap = new HashMap<>();
949
		if (!partnerIds.isEmpty()) {
950
			fofoStoreRepository.selectByRetailerIds(new ArrayList<>(partnerIds))
951
					.forEach(fs -> storeMap.put(fs.getId(), fs));
952
		}
953
 
954
		// Leads: name + geo
955
		Map<Integer, com.spice.profitmandi.dao.entity.user.Lead> leadMap = new HashMap<>();
956
		Map<Integer, com.spice.profitmandi.dao.entity.user.LeadLiveLocation> leadGeoMap = new HashMap<>();
957
		for (int leadId : leadIds) {
958
			com.spice.profitmandi.dao.entity.user.Lead l = leadRepository.selectById(leadId);
959
			if (l != null) leadMap.put(leadId, l);
960
			com.spice.profitmandi.dao.entity.user.LeadLiveLocation lg =
961
					leadLiveLocationRepositoryAuto.selectApprovedByLeadId(leadId);
962
			if (lg != null) leadGeoMap.put(leadId, lg);
963
		}
964
 
965
		// Enrich each stop
966
		List<Map<String, Object>> out = new ArrayList<>();
967
		for (com.spice.profitmandi.dao.model.BeatDayDetails b : beats) {
968
			Map<String, Object> beatJson = new HashMap<>();
969
			beatJson.put("beatId", b.getBeatId());
970
			beatJson.put("beatName", b.getBeatName());
971
			beatJson.put("beatColor", b.getBeatColor());
972
			beatJson.put("dayNumber", b.getDayNumber());
973
			beatJson.put("scheduleDate", b.getScheduleDate().toString());
974
			beatJson.put("endAction", b.getEndAction());
975
			beatJson.put("totalDistanceKm", b.getTotalDistanceKm());
976
			beatJson.put("totalTimeMins", b.getTotalTimeMins());
977
			beatJson.put("startLocationName", b.getStartLocationName());
978
			beatJson.put("startLatitude", b.getStartLatitude());
979
			beatJson.put("startLongitude", b.getStartLongitude());
980
 
981
			List<Map<String, Object>> stops = new ArrayList<>();
982
			// Partners
983
			for (Map<String, Object> ps : b.getPartnerStops()) {
984
				int fofoId = (Integer) ps.get("fofoId");
985
				Map<String, Object> stop = new HashMap<>();
986
				stop.put("type", "partner");
987
				stop.put("id", fofoId);
988
				stop.put("sequenceOrder", ps.get("sequenceOrder"));
989
				FofoStore fs = storeMap.get(fofoId);
990
				CustomRetailer cr = retailerMap.get(fofoId);
991
				stop.put("code", fs != null ? fs.getCode() : null);
992
				stop.put("name", fs != null && fs.getOutletName() != null ? fs.getOutletName()
993
						: (cr != null ? cr.getBusinessName() : "Store #" + fofoId));
36655 ranu 994
				// Use FofoStore lat/lng directly (no geocoding needed after migration)
995
				if (fs != null && fs.getLatitude() != null && fs.getLongitude() != null
996
						&& !fs.getLatitude().isEmpty() && !fs.getLongitude().isEmpty()) {
36650 ranu 997
					try {
36655 ranu 998
						stop.put("lat", Double.parseDouble(fs.getLatitude()));
999
						stop.put("lng", Double.parseDouble(fs.getLongitude()));
1000
					} catch (NumberFormatException ignored) {
36650 ranu 1001
					}
1002
				}
36655 ranu 1003
				if (cr != null && cr.getAddress() != null) {
1004
					stop.put("address", cr.getAddress().getAddressString());
1005
				}
36650 ranu 1006
				stops.add(stop);
1007
			}
1008
			// Leads
1009
			for (Map<String, Object> ls : b.getLeadStops()) {
1010
				int leadId = (Integer) ls.get("leadId");
1011
				Map<String, Object> stop = new HashMap<>();
1012
				stop.put("type", "lead");
1013
				stop.put("id", leadId);
1014
				stop.put("sequenceOrder", ls.get("sequenceOrder"));
1015
				stop.put("nearestStoreId", ls.get("nearestStoreId"));
1016
				com.spice.profitmandi.dao.entity.user.Lead l = leadMap.get(leadId);
1017
				stop.put("name", l != null ? l.getFirstName() + " " + l.getLastName() : "Lead #" + leadId);
1018
				stop.put("mobile", l != null ? l.getLeadMobile() : null);
1019
				stop.put("city", l != null ? l.getCity() : null);
1020
				com.spice.profitmandi.dao.entity.user.LeadLiveLocation lg = leadGeoMap.get(leadId);
1021
				if (lg != null) {
1022
					stop.put("lat", lg.getLatitude());
1023
					stop.put("lng", lg.getLongitude());
1024
				}
1025
				stops.add(stop);
1026
			}
1027
			beatJson.put("stops", stops);
1028
			beatJson.put("partnerCount", b.getPartnerStops().size());
1029
			beatJson.put("leadCount", b.getLeadStops().size());
1030
			out.add(beatJson);
1031
		}
1032
 
1033
		Map<String, Object> result = new HashMap<>();
1034
		result.put("beats", out);
1035
		return responseSender.ok(result);
1036
	}
1037
 
36686 ranu 1038
	// ====================== DAY VIEW ======================
1039
	// Inline page (loaded into dashboard #main-content): tabular list of all beats
1040
	// scheduled in a date range across all users. Each row has a View button that
1041
	// opens that user's calendar in a modal.
1042
	@GetMapping(value = "/beatPlan/dayView")
1043
	public String beatPlanDayView(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1044
		model.addAttribute("escalationTypes", visibleLevelsFor(request));
1045
		return "beat-plan-day-view";
36618 ranu 1046
	}
1047
 
36644 ranu 1048
	// Returns visits for a beat.
1049
	// - Partner stops (beat_route) belong to the beat template — always returned.
1050
	// - Lead stops (lead_route) belong to a specific run — returned ONLY when planDate
1051
	//   is given and matches the lead's schedule_date. (No planDate = template view.)
36632 ranu 1052
	@GetMapping(value = "/beatPlan/getBeatVisits")
36644 ranu 1053
	public ResponseEntity<?> getBeatVisits(
1054
			@RequestParam String planGroupId,
1055
			@RequestParam(required = false) String planDate) {
1056
 
1057
		int beatId;
1058
		try {
1059
			beatId = Integer.parseInt(planGroupId);
1060
		} catch (NumberFormatException e) {
1061
			return responseSender.ok(new ArrayList<>());
1062
		}
1063
 
1064
		List<BeatRoute> routes = beatRouteRepository.selectByBeatId(beatId);
1065
		List<Map<String, Object>> result = new ArrayList<>();
1066
 
1067
		// Partner stops — always (they belong to the beat template)
1068
		for (BeatRoute r : routes) {
36632 ranu 1069
			Map<String, Object> map = new HashMap<>();
36644 ranu 1070
			map.put("fofoId", r.getFofoId());
1071
			map.put("dayNumber", r.getDayNumber());
1072
			map.put("sequenceOrder", r.getSequenceOrder());
1073
			map.put("visitType", "partner");
1074
			result.add(map);
1075
		}
1076
 
1077
		// Lead stops — only for the requested run date
1078
		if (planDate != null && !planDate.isEmpty()) {
1079
			LocalDate date = LocalDate.parse(planDate);
1080
			List<LeadRoute> leads = leadRouteRepository.selectByBeatId(beatId);
1081
			for (LeadRoute lr : leads) {
1082
				if ("APPROVED".equals(lr.getStatus())
1083
						&& lr.getScheduleDate() != null
1084
						&& lr.getScheduleDate().equals(date)) {
1085
					Map<String, Object> map = new HashMap<>();
1086
					map.put("fofoId", lr.getLeadId());
1087
					map.put("dayNumber", 1);
1088
					map.put("sequenceOrder", lr.getSequenceOrder() != null ? lr.getSequenceOrder() : 999);
1089
					map.put("visitType", "lead");
1090
					result.add(map);
1091
				}
1092
			}
1093
		}
1094
 
1095
		// Sort by dayNumber then sequenceOrder
1096
		result.sort((a, b) -> {
1097
			int cmp = Integer.compare((int) a.get("dayNumber"), (int) b.get("dayNumber"));
1098
			return cmp != 0 ? cmp : Integer.compare((int) a.get("sequenceOrder"), (int) b.get("sequenceOrder"));
1099
		});
1100
 
36632 ranu 1101
		return responseSender.ok(result);
1102
	}
1103
 
36681 ranu 1104
	// Returns the user's DEFAULT base location. Falls back to most-recent for
1105
	// legacy users who pre-date the is_default column.
36618 ranu 1106
	@GetMapping(value = "/beatPlan/getBaseLocation")
1107
	public ResponseEntity<?> getBaseLocation(@RequestParam int authUserId) {
36681 ranu 1108
		AuthUserLocation baseLoc = authUserLocationRepository.selectDefaultByAuthUserIdAndType(authUserId, "BASE");
36618 ranu 1109
		if (baseLoc == null) {
1110
			return responseSender.ok(new HashMap<>());
1111
		}
1112
		Map<String, Object> result = new HashMap<>();
1113
		result.put("id", baseLoc.getId());
1114
		result.put("locationName", baseLoc.getLocationName());
1115
		result.put("latitude", baseLoc.getLatitude());
1116
		result.put("longitude", baseLoc.getLongitude());
1117
		result.put("address", baseLoc.getAddress());
36681 ranu 1118
		result.put("isDefault", baseLoc.isDefault());
36618 ranu 1119
		return responseSender.ok(result);
1120
	}
1121
 
36681 ranu 1122
	// Returns ALL BASE locations for a user, default first.
1123
	@GetMapping(value = "/beatPlan/listBaseLocations")
1124
	public ResponseEntity<?> listBaseLocations(@RequestParam int authUserId) {
1125
		List<AuthUserLocation> all = authUserLocationRepository.selectAllByAuthUserIdAndType(authUserId, "BASE");
1126
		// Default at the top, then by created desc (the repo already returns desc).
1127
		all.sort((a, b) -> {
1128
			if (a.isDefault() && !b.isDefault()) return -1;
1129
			if (!a.isDefault() && b.isDefault()) return 1;
1130
			return 0;
1131
		});
1132
		List<Map<String, Object>> rows = new ArrayList<>();
1133
		for (AuthUserLocation l : all) {
1134
			Map<String, Object> row = new HashMap<>();
1135
			row.put("id", l.getId());
1136
			row.put("locationName", l.getLocationName());
1137
			row.put("latitude", l.getLatitude());
1138
			row.put("longitude", l.getLongitude());
1139
			row.put("address", l.getAddress());
1140
			row.put("isDefault", l.isDefault());
1141
			row.put("createdTimestamp", l.getCreatedTimestamp() != null ? l.getCreatedTimestamp().toString() : null);
1142
			rows.add(row);
1143
		}
1144
		Map<String, Object> result = new HashMap<>();
1145
		result.put("authUserId", authUserId);
1146
		result.put("locations", rows);
1147
		return responseSender.ok(result);
1148
	}
1149
 
1150
	// Flip the default flag — set this id default, clear all others.
1151
	@PostMapping(value = "/beatPlan/setDefaultBaseLocation")
1152
	public ResponseEntity<?> setDefaultBaseLocation(
1153
			HttpServletRequest request,
1154
			@RequestParam int id) throws ProfitMandiBusinessException {
1155
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
1156
		AuthUser me = authRepository.selectByEmailOrMobile(ld.getEmailId());
1157
		if (me == null) return responseSender.unauthorized("Not logged in");
1158
		if (!isBaseLocationManager(me)) {
1159
			return responseSender.forbidden("You are not authorized for this action. Only Sales L3 and above can manage base locations.");
1160
		}
1161
 
1162
		AuthUserLocation target = authUserLocationRepository.selectById(id);
1163
		if (target == null) return responseSender.badRequest("Location not found");
1164
 
1165
		List<AuthUserLocation> all = authUserLocationRepository.selectAllByAuthUserIdAndType(target.getAuthUserId(), "BASE");
1166
		for (AuthUserLocation l : all) {
1167
			boolean shouldBeDefault = (l.getId() == id);
1168
			if (l.isDefault() != shouldBeDefault) {
1169
				l.setDefault(shouldBeDefault);
1170
				authUserLocationRepository.persist(l); // saveOrUpdate
1171
			}
1172
		}
1173
 
1174
		Map<String, Object> result = new HashMap<>();
1175
		result.put("status", true);
1176
		result.put("id", id);
1177
		result.put("message", "Default base location updated");
1178
		return responseSender.ok(result);
1179
	}
1180
 
1181
	// Delete a base location. The DEFAULT one cannot be deleted — user must
1182
	// first pick another row as default.
1183
	@PostMapping(value = "/beatPlan/deleteBaseLocation")
1184
	public ResponseEntity<?> deleteBaseLocation(
1185
			HttpServletRequest request,
1186
			@RequestParam int id) throws ProfitMandiBusinessException {
1187
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
1188
		AuthUser me = authRepository.selectByEmailOrMobile(ld.getEmailId());
1189
		if (me == null) return responseSender.unauthorized("Not logged in");
1190
		if (!isBaseLocationManager(me)) {
1191
			return responseSender.forbidden("You are not authorized for this action. Only Sales L3 and above can manage base locations.");
1192
		}
1193
 
1194
		AuthUserLocation target = authUserLocationRepository.selectById(id);
1195
		if (target == null) return responseSender.badRequest("Location not found");
1196
		if (target.isDefault()) {
1197
			return responseSender.badRequest("Default base location cannot be removed. Set another location as default first.");
1198
		}
1199
 
1200
		authUserLocationRepository.delete(target);
1201
 
1202
		Map<String, Object> result = new HashMap<>();
1203
		result.put("status", true);
1204
		result.put("message", "Base location removed");
1205
		return responseSender.ok(result);
1206
	}
1207
 
36686 ranu 1208
	@GetMapping(value = "/beatPlan/getAuthUsers")
1209
	public ResponseEntity<?> getAuthUsers(
1210
			HttpServletRequest request,
1211
			@RequestParam int categoryId,
1212
			@RequestParam EscalationType escalationType) throws ProfitMandiBusinessException {
1213
 
1214
		// Hierarchy filter: a manager only sees users in their downline
1215
		// (themselves + every reportee under them, recursively). Super-admin
1216
		// emails bypass the filter and see everyone. Downline is computed by
1217
		// AuthService.getAllReportees (existing recursive walker).
1218
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
1219
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
1220
 
1221
		final Set<Integer> visible;
1222
		if (me == null || isSuperAdmin(me)) {
1223
			visible = null; // null = no filter
1224
		} else {
1225
			visible = new HashSet<>(authService.getAllReportees(me.getId()));
1226
			visible.add(me.getId()); // include self
1227
		}
1228
 
1229
		List<AuthUser> authUsers = csService.getAuthUserByCategoryId(categoryId, escalationType);
1230
		List<Map<String, Object>> result = authUsers.stream()
1231
				.filter(au -> au.getActive())
1232
				.filter(au -> visible == null || visible.contains(au.getId()))
1233
				.map(au -> {
1234
					Map<String, Object> map = new HashMap<>();
1235
					map.put("id", au.getId());
1236
					map.put("name", au.getFirstName() + " " + au.getLastName());
1237
					return map;
1238
				})
1239
				.collect(Collectors.toList());
1240
		return responseSender.ok(result);
1241
	}
1242
 
1243
	private boolean isSuperAdmin(AuthUser me) {
36681 ranu 1244
		String myEmail = me.getEmailId() != null ? me.getEmailId().toLowerCase() : "";
36686 ranu 1245
		return SUPER_ADMIN_EMAILS.contains(myEmail);
1246
	}
36681 ranu 1247
 
36686 ranu 1248
	// Returns the user's highest escalation level across all positions.
1249
	// Mirrors OrderController.getSalesEscalationLevel but category-agnostic.
1250
	private EscalationType getHighestEscalation(int authUserId) {
1251
		EscalationType highest = null;
1252
		List<com.spice.profitmandi.dao.entity.cs.Position> positions = positionRepository.selectPositionByAuthId(authUserId);
1253
		for (com.spice.profitmandi.dao.entity.cs.Position p : positions) {
1254
			if (highest == null || p.getEscalationType().isGreaterThanEqualTo(highest)) {
1255
				highest = p.getEscalationType();
1256
			}
1257
		}
1258
		return highest;
1259
	}
1260
 
1261
	// Returns the escalation levels a user can manage — strictly below their own.
1262
	// L3 → [L1, L2]; L4 → [L1, L2, L3]; Final → all levels. Super-admin → all levels.
1263
	private List<EscalationType> getVisibleEscalationLevels(AuthUser me) {
1264
		if (isSuperAdmin(me)) return EscalationType.escalations;
1265
		EscalationType mine = getHighestEscalation(me.getId());
1266
		if (mine == null) return java.util.Collections.emptyList();
1267
		List<EscalationType> below = new ArrayList<>();
1268
		for (EscalationType e : EscalationType.escalations) {
1269
			if (mine.isGreaterThanEqualTo(e) && !e.equals(mine)) below.add(e);
1270
		}
1271
		return below;
1272
	}
1273
 
1274
	private List<EscalationType> visibleLevelsFor(HttpServletRequest request) throws ProfitMandiBusinessException {
1275
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
1276
		AuthUser me = (ld != null) ? authRepository.selectByEmailOrMobile(ld.getEmailId()) : null;
1277
		return me == null ? java.util.Collections.emptyList() : getVisibleEscalationLevels(me);
1278
	}
1279
 
1280
	// Shared permission check for base-location admin actions: Sales L3+ OR super-admin.
1281
	private boolean isBaseLocationManager(AuthUser me) {
1282
		if (isSuperAdmin(me)) return true;
36681 ranu 1283
		return csService.getAuthUserIds(
1284
						com.spice.profitmandi.common.model.ProfitMandiConstants.TICKET_CATEGORY_SALES,
1285
						Arrays.asList(EscalationType.L3, EscalationType.L4))
1286
				.stream().anyMatch(u -> u.getId() == me.getId());
1287
	}
1288
 
36618 ranu 1289
	@PostMapping(value = "/beatPlan/saveBaseLocation")
1290
	public ResponseEntity<?> saveBaseLocation(
1291
			@RequestParam int authUserId,
1292
			@RequestParam String locationName,
1293
			@RequestParam String latitude,
1294
			@RequestParam String longitude,
1295
			@RequestParam(required = false) String address) {
1296
		AuthUserLocation loc = new AuthUserLocation();
1297
		loc.setAuthUserId(authUserId);
1298
		loc.setLocationType("BASE");
1299
		loc.setLocationName(locationName);
1300
		loc.setLatitude(latitude);
1301
		loc.setLongitude(longitude);
1302
		loc.setAddress(address);
1303
		loc.setCreatedTimestamp(LocalDateTime.now());
36681 ranu 1304
 
1305
		// First BASE for this user → auto-default so every user always has one.
1306
		List<AuthUserLocation> existing = authUserLocationRepository.selectAllByAuthUserIdAndType(authUserId, "BASE");
1307
		boolean noExistingDefault = existing.stream().noneMatch(AuthUserLocation::isDefault);
1308
		loc.setDefault(existing.isEmpty() || noExistingDefault);
36618 ranu 1309
		authUserLocationRepository.persist(loc);
1310
 
1311
		Map<String, Object> result = new HashMap<>();
1312
		result.put("status", true);
1313
		result.put("id", loc.getId());
36681 ranu 1314
		result.put("isDefault", loc.isDefault());
36618 ranu 1315
		return responseSender.ok(result);
1316
	}
1317
 
1318
	@GetMapping(value = "/beatPlan/getPartners")
1319
	public ResponseEntity<?> getPartners(
1320
			@RequestParam int authUserId,
1321
			@RequestParam int categoryId,
1322
			@RequestParam(required = false) String startLat,
1323
			@RequestParam(required = false) String startLng) throws ProfitMandiBusinessException {
1324
 
1325
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1326
		List<Integer> fofoIds = pp.get(authUserId);
1327
 
36644 ranu 1328
		if (fofoIds == null || fofoIds.isEmpty()) {
36618 ranu 1329
			Map<String, Object> empty = new HashMap<>();
1330
			empty.put("partners", new ArrayList<>());
1331
			return responseSender.ok(empty);
1332
		}
1333
 
1334
		List<FofoStore> fofoStores = fofoStoreRepository.selectByRetailerIds(fofoIds);
1335
		Map<Integer, CustomRetailer> retailerMap = retailerService.getFofoRetailers(fofoIds);
1336
 
1337
		List<Map<String, Object>> partners = new ArrayList<>();
1338
 
1339
		for (FofoStore store : fofoStores) {
1340
			if (!store.isActive() || store.isClosed()) continue;
1341
			CustomRetailer retailer = retailerMap.get(store.getId());
1342
 
1343
			Map<String, Object> partnerData = new HashMap<>();
1344
			partnerData.put("fofoId", store.getId());
1345
			partnerData.put("code", store.getCode());
1346
			partnerData.put("outletName", store.getOutletName());
1347
			partnerData.put("type", "partner");
1348
 
36655 ranu 1349
			// Use FofoStore lat/lng directly (migrated from address geocode)
1350
			if (store.getLatitude() != null && !store.getLatitude().isEmpty()
1351
					&& store.getLongitude() != null && !store.getLongitude().isEmpty()) {
1352
				partnerData.put("latitude", store.getLatitude());
1353
				partnerData.put("longitude", store.getLongitude());
1354
			}
1355
 
36618 ranu 1356
			if (retailer != null) {
1357
				partnerData.put("businessName", retailer.getBusinessName());
1358
				if (retailer.getAddress() != null) {
36644 ranu 1359
					partnerData.put("address", retailer.getAddress().getAddressString());
36618 ranu 1360
				}
1361
			}
1362
			partners.add(partnerData);
1363
		}
1364
 
1365
		if (startLat != null && startLng != null && !startLat.isEmpty() && !startLng.isEmpty()) {
1366
			partners = sortByNearestNeighborFromStart(partners, Double.parseDouble(startLat), Double.parseDouble(startLng));
1367
		} else {
1368
			partners = sortByNearestNeighbor(partners);
1369
		}
1370
 
1371
		Map<String, Object> response = new HashMap<>();
1372
		response.put("partners", partners);
1373
		return responseSender.ok(response);
1374
	}
1375
 
1376
	@PostMapping(value = "/beatPlan/submitPlan")
1377
	public ResponseEntity<?> submitPlan(
1378
			HttpServletRequest request,
1379
			@RequestParam int authUserId,
1380
			@RequestParam String planData) throws Exception {
1381
 
1382
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1383
		AuthUser currentUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1384
 
1385
		Gson gson = new Gson();
1386
		Type type = new TypeToken<Map<String, Object>>() {
1387
		}.getType();
1388
		Map<String, Object> plan = gson.fromJson(planData, type);
1389
 
1390
		List<Map<String, Object>> days = (List<Map<String, Object>>) plan.get("days");
1391
		List<String> dates = (List<String>) plan.get("dates");
1392
 
36644 ranu 1393
		String beatName = (plan.get("beatName") != null ? (String) plan.get("beatName") : "Beat").trim();
36618 ranu 1394
 
36698 ranu 1395
		// Duplicate check — same name + same authUserId among ACTIVE beats only.
1396
		// Soft-deleted beats keep the name in the table; we don't want them to
1397
		// block the user from reusing a name they "deleted".
1398
		List<Beat> existingBeats = beatRepository.selectActiveByAuthUserId(authUserId);
36644 ranu 1399
		for (Beat existing : existingBeats) {
1400
			if (existing.getName() != null && beatName.equalsIgnoreCase(existing.getName().trim())) {
1401
				LOGGER.info("Duplicate beat blocked: name='{}' authUserId={} existingId={}", beatName, authUserId, existing.getId());
36618 ranu 1402
				Map<String, Object> response = new HashMap<>();
1403
				response.put("status", true);
36644 ranu 1404
				response.put("planGroupId", String.valueOf(existing.getId()));
36618 ranu 1405
				response.put("duplicate", true);
36644 ranu 1406
				response.put("message", "Beat '" + beatName + "' already exists");
36618 ranu 1407
				return responseSender.ok(response);
1408
			}
1409
		}
1410
 
36644 ranu 1411
		String beatColor = BEAT_COLORS[Math.abs(beatName.hashCode()) % BEAT_COLORS.length];
1412
		int totalDays = days.size();
36618 ranu 1413
 
36644 ranu 1414
		// Create Beat master
1415
		Beat beat = new Beat();
1416
		beat.setName(beatName);
1417
		beat.setAuthUserId(authUserId);
1418
		beat.setBeatColor(beatColor);
1419
		beat.setTotalDays(totalDays);
1420
		beat.setActive(true);
1421
		beat.setCreatedBy(currentUser.getId());
1422
		beat.setCreatedTimestamp(LocalDateTime.now());
1423
 
1424
		// Set start location from first day
1425
		if (!days.isEmpty()) {
1426
			Map<String, Object> firstDay = days.get(0);
1427
			beat.setStartLocationName((String) firstDay.get("startLocationName"));
1428
			beat.setStartLatitude((String) firstDay.get("startLatitude"));
1429
			beat.setStartLongitude((String) firstDay.get("startLongitude"));
1430
		}
1431
		beatRepository.persist(beat);
1432
 
1433
		// End date of the whole beat = last scheduled day's date
1434
		LocalDate beatEndDate = null;
1435
		if (dates != null) {
1436
			for (int d = dates.size() - 1; d >= 0; d--) {
1437
				if (dates.get(d) != null) {
1438
					beatEndDate = LocalDate.parse(dates.get(d), DateTimeFormatter.ISO_DATE);
1439
					break;
1440
				}
1441
			}
1442
		}
1443
 
1444
		// Create routes and schedules for each day
36618 ranu 1445
		for (int d = 0; d < days.size(); d++) {
1446
			Map<String, Object> day = days.get(d);
1447
			int dayNumber = d + 1;
1448
			LocalDate planDate = (dates != null && d < dates.size() && dates.get(d) != null)
36644 ranu 1449
					? LocalDate.parse(dates.get(d), DateTimeFormatter.ISO_DATE) : null;
36618 ranu 1450
 
36644 ranu 1451
			// Auto-determine end action: last day = HOME, others = DAYBREAK
1452
			String endAction = (String) day.get("endAction");
1453
			if (endAction == null || endAction.isEmpty()) {
1454
				endAction = (dayNumber == totalDays) ? "HOME" : "DAYBREAK";
36618 ranu 1455
			}
1456
 
36644 ranu 1457
			// Always create schedule (even if planDate is null — unscheduled beat)
1458
			BeatSchedule schedule = new BeatSchedule();
1459
			schedule.setBeatId(beat.getId());
1460
			schedule.setStartDate(planDate != null ? planDate : LocalDate.of(9999, 12, 31)); // placeholder for unscheduled
1461
			schedule.setEndDate(beatEndDate);
1462
			schedule.setDayNumber(dayNumber);
1463
			schedule.setEndAction(endAction);
1464
			schedule.setStayLocationName((String) day.get("stayLocationName"));
1465
			schedule.setStayLatitude((String) day.get("stayLatitude"));
1466
			schedule.setStayLongitude((String) day.get("stayLongitude"));
1467
			if (day.get("totalDistanceKm") != null)
1468
				schedule.setTotalDistanceKm(((Number) day.get("totalDistanceKm")).doubleValue());
1469
			if (day.get("totalTimeMins") != null)
1470
				schedule.setTotalTimeMins(((Number) day.get("totalTimeMins")).intValue());
1471
			schedule.setCreatedTimestamp(LocalDateTime.now());
1472
			beatScheduleRepository.persist(schedule);
1473
 
36711 ranu 1474
            // Routes (stops) — also persist per-leg distance/time supplied by the
1475
            // client so reports/dashboards don't have to recompute from lat/lng.
36618 ranu 1476
			List<Map<String, Object>> visits = (List<Map<String, Object>>) day.get("visits");
1477
			if (visits != null) {
1478
				for (int i = 0; i < visits.size(); i++) {
1479
					Map<String, Object> visit = visits.get(i);
36644 ranu 1480
					BeatRoute route = new BeatRoute();
1481
					route.setBeatId(beat.getId());
1482
					route.setFofoId(((Number) visit.get("id")).intValue());
1483
					route.setSequenceOrder(i);
1484
					route.setDayNumber(dayNumber);
1485
					route.setActive(true);
36711 ranu 1486
                    if (visit.get("distanceFromPrevKm") != null)
1487
                        route.setDistanceFromPrevKm(((Number) visit.get("distanceFromPrevKm")).doubleValue());
1488
                    if (visit.get("timeFromPrevMins") != null)
1489
                        route.setTimeFromPrevMins(((Number) visit.get("timeFromPrevMins")).intValue());
36644 ranu 1490
					beatRouteRepository.persist(route);
36618 ranu 1491
				}
1492
			}
1493
		}
1494
 
1495
		Map<String, Object> response = new HashMap<>();
1496
		response.put("status", true);
36644 ranu 1497
		response.put("planGroupId", String.valueOf(beat.getId()));
36618 ranu 1498
		response.put("message", "Beat plan submitted successfully");
1499
		return responseSender.ok(response);
1500
	}
1501
 
36632 ranu 1502
	// ============ BULK UPLOAD ============
1503
 
1504
	@GetMapping(value = "/beatPlan/bulkUpload")
1505
	public String bulkUploadPage(HttpServletRequest request, Model model) {
1506
		return "beat-plan-bulk";
1507
	}
1508
 
36681 ranu 1509
	// Adds a new base location for the user. Caller can request this new row
1510
	// becomes the default. If the user has NO base locations yet, the new row
1511
	// is auto-defaulted (so every user always has exactly one default).
36668 ranu 1512
	@PostMapping(value = "/beatPlan/updateBaseLocation")
1513
	public ResponseEntity<?> updateBaseLocation(
1514
			HttpServletRequest request,
1515
			@RequestParam int authUserId,
1516
			@RequestParam String locationName,
1517
			@RequestParam String latitude,
1518
			@RequestParam String longitude,
36681 ranu 1519
			@RequestParam(required = false) String address,
1520
			@RequestParam(required = false, defaultValue = "false") boolean isDefault) throws Exception {
36668 ranu 1521
 
1522
		LoginDetails ld = cookiesProcessor.getCookiesObject(request);
1523
		AuthUser me = authRepository.selectByEmailOrMobile(ld.getEmailId());
1524
		if (me == null) return responseSender.unauthorized("Not logged in");
36681 ranu 1525
		if (!isBaseLocationManager(me)) {
1526
			return responseSender.forbidden("You are not authorized for this action. Only Sales L3 and above can update base location.");
1527
		}
36668 ranu 1528
 
36681 ranu 1529
		List<AuthUserLocation> existing = authUserLocationRepository.selectAllByAuthUserIdAndType(authUserId, "BASE");
1530
		boolean noExistingDefault = existing.stream().noneMatch(AuthUserLocation::isDefault);
1531
		boolean makeDefault = isDefault || existing.isEmpty() || noExistingDefault;
36668 ranu 1532
 
36681 ranu 1533
		// If this new row becomes the default, clear any existing default.
1534
		if (makeDefault) {
1535
			for (AuthUserLocation e : existing) {
1536
				if (e.isDefault()) {
1537
					e.setDefault(false);
1538
					authUserLocationRepository.persist(e);
1539
				}
1540
			}
36668 ranu 1541
		}
1542
 
1543
		AuthUserLocation loc = new AuthUserLocation();
1544
		loc.setAuthUserId(authUserId);
1545
		loc.setLocationType("BASE");
1546
		loc.setLocationName(locationName);
1547
		loc.setLatitude(latitude);
1548
		loc.setLongitude(longitude);
1549
		loc.setAddress(address);
36681 ranu 1550
		loc.setDefault(makeDefault);
36668 ranu 1551
		loc.setCreatedTimestamp(LocalDateTime.now());
1552
		authUserLocationRepository.persist(loc);
1553
 
1554
		Map<String, Object> result = new HashMap<>();
1555
		result.put("status", true);
1556
		result.put("id", loc.getId());
36681 ranu 1557
		result.put("isDefault", loc.isDefault());
1558
		result.put("message", makeDefault ? "Base location added and set as default" : "Base location added");
36668 ranu 1559
		return responseSender.ok(result);
1560
	}
1561
 
36632 ranu 1562
	@GetMapping(value = "/beatPlan/downloadTemplate")
36668 ranu 1563
	public ResponseEntity<?> downloadTemplate() throws java.io.IOException {
1564
		org.apache.poi.xssf.usermodel.XSSFWorkbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
1565
		org.apache.poi.xssf.usermodel.XSSFSheet sheet = wb.createSheet("beat-plan");
36632 ranu 1566
 
36668 ranu 1567
		String[] cols = {"beat_name", "auth_user_id", "start_date", "day_number", "sequence_order", "partner_code"};
1568
 
1569
		// Header style
1570
		org.apache.poi.xssf.usermodel.XSSFCellStyle headerStyle = wb.createCellStyle();
1571
		org.apache.poi.xssf.usermodel.XSSFFont headerFont = wb.createFont();
1572
		headerFont.setBold(true);
1573
		headerStyle.setFont(headerFont);
1574
		headerStyle.setFillForegroundColor(new org.apache.poi.xssf.usermodel.XSSFColor(new java.awt.Color(230, 230, 230)));
1575
		headerStyle.setFillPattern(org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND);
1576
 
1577
		org.apache.poi.xssf.usermodel.XSSFRow header = sheet.createRow(0);
1578
		for (int i = 0; i < cols.length; i++) {
1579
			org.apache.poi.xssf.usermodel.XSSFCell c = header.createCell(i);
1580
			c.setCellValue(cols[i]);
1581
			c.setCellStyle(headerStyle);
1582
		}
1583
 
1584
		// Example rows — one partner per row. Inheritable columns blank after first row of a beat.
1585
		Object[][] sample = {
1586
				{"Jaipur East Route", "280", "2026-06-02", "1", "1", "RJKAI1478"},
1587
				{"", "", "", "1", "2", "RJBUN1449"},
1588
				{"", "", "", "1", "3", "RJDEG1443"},
1589
				{"", "", "", "2", "1", "RJALR1362"},
1590
				{"", "", "", "2", "2", "RJBTR1388"},
1591
				{"", "", "", "3", "1", "RJRSD1518"},
1592
				{"", "", "", "3", "2", "RJSML356"},
1593
				{"Agra Circuit", "145", "2026-06-05", "1", "1", "UPAGR101"},
1594
				{"", "", "", "1", "2", "UPAGR102"},
1595
		};
1596
		for (int r = 0; r < sample.length; r++) {
1597
			org.apache.poi.xssf.usermodel.XSSFRow row = sheet.createRow(r + 1);
1598
			for (int c = 0; c < cols.length; c++) {
1599
				row.createCell(c).setCellValue(sample[r][c].toString());
1600
			}
1601
		}
1602
		for (int i = 0; i < cols.length; i++) sheet.autoSizeColumn(i);
1603
 
1604
		java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
1605
		wb.write(out);
1606
		wb.close();
1607
 
36632 ranu 1608
		org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
36668 ranu 1609
		headers.add("Content-Disposition", "attachment; filename=beat_plan_template.xlsx");
1610
		headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1611
		return new ResponseEntity<>(out.toByteArray(), headers, org.springframework.http.HttpStatus.OK);
36632 ranu 1612
	}
1613
 
1614
	@PostMapping(value = "/beatPlan/bulkUploadProcess")
1615
	public ResponseEntity<?> bulkUploadProcess(
1616
			HttpServletRequest request,
1617
			@RequestParam("file") org.springframework.web.multipart.MultipartFile file,
1618
			@RequestParam(value = "includeSundays", defaultValue = "false") boolean includeSundays) throws Exception {
1619
 
1620
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1621
		AuthUser currentUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1622
 
36668 ranu 1623
		// Read .xlsx — one partner per row. beat_name / auth_user_id / start_date
1624
		// appear ONLY on the first row of a beat; subsequent rows inherit them.
1625
		org.apache.poi.ss.usermodel.Workbook workbook =
1626
				new org.apache.poi.xssf.usermodel.XSSFWorkbook(file.getInputStream());
1627
		org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
36632 ranu 1628
 
36668 ranu 1629
		// Header → column index map
1630
		org.apache.poi.ss.usermodel.Row headerRow = sheet.getRow(0);
1631
		if (headerRow == null) {
1632
			workbook.close();
1633
			return responseSender.badRequest("Empty file");
1634
		}
1635
		Map<String, Integer> colIdx = new HashMap<>();
1636
		for (int i = 0; i < headerRow.getLastCellNum(); i++) {
1637
			String h = readCell(headerRow.getCell(i));
1638
			if (h != null) colIdx.put(h.trim().toLowerCase(), i);
1639
		}
1640
		for (String required : new String[]{"beat_name", "auth_user_id", "day_number", "partner_code"}) {
1641
			if (!colIdx.containsKey(required)) {
1642
				workbook.close();
1643
				return responseSender.badRequest("Missing required column: " + required);
1644
			}
1645
		}
36632 ranu 1646
 
36668 ranu 1647
		// Walk rows, group partners by (beat_name + auth_user_id) → day_number → sequence_order
1648
		Map<String, BulkBeatGroup> beatGroups = new LinkedHashMap<>();
1649
		String currentKey = null;
1650
		String currentBeatName = null;
1651
		String currentAuthId = null;
1652
		String currentStartDate = null;
1653
 
1654
		for (int r = 1; r <= sheet.getLastRowNum(); r++) {
1655
			org.apache.poi.ss.usermodel.Row row = sheet.getRow(r);
1656
			if (row == null) continue;
1657
 
1658
			String beatName = readCell(row.getCell(colIdx.get("beat_name")));
1659
			String authId = readCell(row.getCell(colIdx.get("auth_user_id")));
1660
			String startDate = colIdx.containsKey("start_date") ? readCell(row.getCell(colIdx.get("start_date"))) : null;
1661
			String dayNumber = readCell(row.getCell(colIdx.get("day_number")));
1662
			String seqOrder = colIdx.containsKey("sequence_order") ? readCell(row.getCell(colIdx.get("sequence_order"))) : null;
1663
			String code = readCell(row.getCell(colIdx.get("partner_code")));
1664
 
1665
			if (beatName != null && !beatName.trim().isEmpty()) {
1666
				// Start of a new beat — capture inheritable fields
1667
				currentBeatName = beatName.trim().replaceAll("\\s+", " ");
1668
				currentAuthId = authId != null ? authId.trim() : null;
1669
				currentStartDate = (startDate != null && !startDate.trim().isEmpty()) ? startDate.trim() : null;
1670
				currentKey = currentBeatName + "|" + currentAuthId;
1671
			}
1672
			if (currentKey == null) continue; // partner row before any beat header — skip
1673
			if (code == null || code.trim().isEmpty()) continue;
1674
 
1675
			final String beatNameF = currentBeatName;
1676
			final String authIdF = currentAuthId;
1677
			final String startDateF = currentStartDate;
1678
			BulkBeatGroup g = beatGroups.computeIfAbsent(currentKey, k -> new BulkBeatGroup(beatNameF, authIdF, startDateF));
1679
 
1680
			int day;
1681
			try {
1682
				day = Integer.parseInt(dayNumber.trim());
1683
			} catch (Exception e) {
1684
				continue;
1685
			} // bad day → skip row
1686
 
1687
			int seq = -1;
1688
			if (seqOrder != null && !seqOrder.trim().isEmpty()) {
1689
				try {
1690
					seq = Integer.parseInt(seqOrder.trim());
1691
				} catch (Exception ignore) {
1692
				}
1693
			}
1694
			g.addPartner(day, seq, code.trim(), r + 1);
36632 ranu 1695
		}
36668 ranu 1696
		workbook.close();
36632 ranu 1697
 
1698
		List<FofoStore> allStores = fofoStoreRepository.selectAll();
1699
		Map<String, Integer> codeToId = new HashMap<>();
36644 ranu 1700
		for (FofoStore store : allStores) codeToId.put(store.getCode(), store.getId());
36632 ranu 1701
 
1702
		LocalDate holidayStart = LocalDate.now();
36644 ranu 1703
		List<PublicHolidays> holidays = publicHolidaysRepository.selectAllBetweenDates(holidayStart, holidayStart.plusMonths(6));
36632 ranu 1704
		Set<LocalDate> holidayDates = holidays.stream().map(PublicHolidays::getDate).collect(Collectors.toSet());
1705
 
36644 ranu 1706
		int beatsCreated = 0, errors = 0;
36632 ranu 1707
		List<String> errorMessages = new ArrayList<>();
1708
 
36668 ranu 1709
		for (BulkBeatGroup g : beatGroups.values()) {
36632 ranu 1710
			try {
36668 ranu 1711
				String beatName = g.beatName;
1712
				int authUserId;
1713
				try {
1714
					authUserId = Integer.parseInt(g.authUserId);
1715
				} catch (Exception e) {
1716
					errorMessages.add("Beat '" + beatName + "': invalid auth_user_id '" + g.authUserId + "'. Skipped.");
1717
					errors++;
1718
					continue;
1719
				}
36632 ranu 1720
 
36668 ranu 1721
				LocalDate startDate = (g.startDate == null) ? null : LocalDate.parse(g.startDate, DateTimeFormatter.ISO_DATE);
36632 ranu 1722
				if (startDate != null && startDate.isBefore(LocalDate.now())) {
36644 ranu 1723
					errorMessages.add("Beat '" + beatName + "': start_date in past. Skipped.");
36632 ranu 1724
					errors++;
1725
					continue;
1726
				}
1727
 
36668 ranu 1728
				List<Integer> sortedDays = new ArrayList<>(g.dayToPartners.keySet());
1729
				Collections.sort(sortedDays);
1730
 
36632 ranu 1731
				List<LocalDate> scheduleDates = new ArrayList<>();
1732
				if (startDate != null) {
1733
					LocalDate d = startDate;
36668 ranu 1734
					while (scheduleDates.size() < sortedDays.size()) {
1735
						if (holidayDates.contains(d) || (d.getDayOfWeek() == DayOfWeek.SUNDAY && !includeSundays)) {
36644 ranu 1736
							d = d.plusDays(1);
1737
							continue;
36632 ranu 1738
						}
36644 ranu 1739
						scheduleDates.add(d);
36632 ranu 1740
						d = d.plusDays(1);
1741
					}
1742
				}
1743
 
36698 ranu 1744
				// Duplicate check — ACTIVE beats only (soft-deleted names are reusable)
1745
				boolean isDuplicate = beatRepository.selectActiveByAuthUserId(authUserId).stream()
36644 ranu 1746
						.anyMatch(b -> b.getName() != null && beatName.equalsIgnoreCase(b.getName().trim()));
1747
				if (isDuplicate) {
1748
					errorMessages.add("Beat '" + beatName + "' already exists for user " + authUserId + ". Skipped.");
1749
					errors++;
1750
					continue;
1751
				}
36632 ranu 1752
 
36644 ranu 1753
				String beatColor = BEAT_COLORS[Math.abs(beatName.hashCode()) % BEAT_COLORS.length];
36681 ranu 1754
				AuthUserLocation homeLoc = authUserLocationRepository.selectDefaultByAuthUserIdAndType(authUserId, "BASE");
36632 ranu 1755
 
36644 ranu 1756
				Beat beat = new Beat();
1757
				beat.setName(beatName);
1758
				beat.setAuthUserId(authUserId);
1759
				beat.setBeatColor(beatColor);
36668 ranu 1760
				beat.setTotalDays(sortedDays.size());
36644 ranu 1761
				beat.setStartLocationName(homeLoc != null ? homeLoc.getLocationName() : "Home");
1762
				beat.setStartLatitude(homeLoc != null ? homeLoc.getLatitude() : null);
1763
				beat.setStartLongitude(homeLoc != null ? homeLoc.getLongitude() : null);
1764
				beat.setActive(true);
1765
				beat.setCreatedBy(currentUser.getId());
1766
				beat.setCreatedTimestamp(LocalDateTime.now());
1767
				beatRepository.persist(beat);
36632 ranu 1768
 
36668 ranu 1769
				LocalDate bulkEndDate = scheduleDates.isEmpty() ? null : scheduleDates.get(scheduleDates.size() - 1);
36632 ranu 1770
 
36668 ranu 1771
				for (int dayIdx = 0; dayIdx < sortedDays.size(); dayIdx++) {
1772
					int dayNumber = sortedDays.get(dayIdx);
1773
					LocalDate planDate = (dayIdx < scheduleDates.size()) ? scheduleDates.get(dayIdx) : null;
1774
 
36644 ranu 1775
					BeatSchedule schedule = new BeatSchedule();
1776
					schedule.setBeatId(beat.getId());
1777
					schedule.setStartDate(planDate != null ? planDate : LocalDate.of(9999, 12, 31));
1778
					schedule.setEndDate(bulkEndDate);
1779
					schedule.setDayNumber(dayNumber);
36668 ranu 1780
					schedule.setEndAction(dayIdx == sortedDays.size() - 1 ? "HOME" : "DAYBREAK");
36644 ranu 1781
					schedule.setCreatedTimestamp(LocalDateTime.now());
1782
					beatScheduleRepository.persist(schedule);
36632 ranu 1783
 
36668 ranu 1784
					List<BulkPartner> partners = g.dayToPartners.get(dayNumber);
1785
					// Sort by explicit sequence_order when present, else by row order
1786
					partners.sort((a, b) -> {
1787
						if (a.seq >= 0 && b.seq >= 0) return Integer.compare(a.seq, b.seq);
1788
						if (a.seq >= 0) return -1;
1789
						if (b.seq >= 0) return 1;
1790
						return Integer.compare(a.rowNum, b.rowNum);
1791
					});
1792
 
1793
					int autoSeq = 0;
1794
					for (BulkPartner p : partners) {
1795
						Integer fofoId = codeToId.get(p.code);
36632 ranu 1796
						if (fofoId == null) {
36668 ranu 1797
							errorMessages.add("Row " + p.rowNum + ": code not found '" + p.code + "'");
36632 ranu 1798
							errors++;
1799
							continue;
1800
						}
36644 ranu 1801
						BeatRoute route = new BeatRoute();
1802
						route.setBeatId(beat.getId());
1803
						route.setFofoId(fofoId);
36668 ranu 1804
						route.setSequenceOrder(p.seq >= 0 ? p.seq : autoSeq);
36644 ranu 1805
						route.setDayNumber(dayNumber);
1806
						route.setActive(true);
1807
						beatRouteRepository.persist(route);
36668 ranu 1808
						autoSeq++;
36632 ranu 1809
					}
1810
				}
1811
				beatsCreated++;
1812
			} catch (Exception e) {
1813
				errors++;
36668 ranu 1814
				errorMessages.add("Error: " + g.beatName + " - " + e.getMessage());
36632 ranu 1815
			}
1816
		}
1817
 
1818
		Map<String, Object> response = new HashMap<>();
1819
		response.put("status", true);
1820
		response.put("beatsCreated", beatsCreated);
1821
		response.put("errors", errors);
1822
		response.put("errorMessages", errorMessages);
1823
		return responseSender.ok(response);
1824
	}
1825
 
36668 ranu 1826
	private static class BulkBeatGroup {
1827
		final String beatName;
1828
		final String authUserId;
1829
		final String startDate;
1830
		final Map<Integer, List<BulkPartner>> dayToPartners = new LinkedHashMap<>();
1831
 
1832
		BulkBeatGroup(String beatName, String authUserId, String startDate) {
1833
			this.beatName = beatName;
1834
			this.authUserId = authUserId;
1835
			this.startDate = startDate;
1836
		}
1837
 
1838
		void addPartner(int day, int seq, String code, int rowNum) {
1839
			dayToPartners.computeIfAbsent(day, k -> new ArrayList<>()).add(new BulkPartner(seq, code, rowNum));
1840
		}
1841
	}
1842
 
1843
	private static class BulkPartner {
1844
		final int seq;
1845
		final String code;
1846
		final int rowNum;
1847
 
1848
		BulkPartner(int seq, String code, int rowNum) {
1849
			this.seq = seq;
1850
			this.code = code;
1851
			this.rowNum = rowNum;
1852
		}
1853
	}
1854
 
36644 ranu 1855
	// ============ CALENDAR ============
36618 ranu 1856
 
1857
	@PostMapping(value = "/beatPlan/delete")
1858
	public ResponseEntity<?> deleteBeat(@RequestParam String planGroupId) {
36644 ranu 1859
		int beatId = Integer.parseInt(planGroupId);
36698 ranu 1860
		// Hard delete — wipe all child rows first, then the beat itself.
1861
		// The name slot is freed naturally because the row is gone.
36644 ranu 1862
		beatRouteRepository.deleteByBeatId(beatId);
1863
		beatScheduleRepository.deleteByBeatId(beatId);
36698 ranu 1864
		leadRouteRepository.deleteByBeatId(beatId);
36644 ranu 1865
		Beat beat = beatRepository.selectById(beatId);
1866
		if (beat != null) {
36698 ranu 1867
			beatRepository.delete(beat);
36644 ranu 1868
		}
36618 ranu 1869
 
1870
		Map<String, Object> response = new HashMap<>();
1871
		response.put("status", true);
1872
		response.put("message", "Beat deleted");
1873
		return responseSender.ok(response);
1874
	}
1875
 
36670 ranu 1876
	// Unschedule the beat from ONE specific date — does NOT delete the beat.
1877
	// The beat (and its route template) stays; only the matching beat_schedule
1878
	// row is removed. If no real-date schedules remain, a placeholder
1879
	// (9999-12-31) row is added so the beat still shows up as "unscheduled".
1880
	@PostMapping(value = "/beatPlan/unscheduleDate")
1881
	public ResponseEntity<?> unscheduleDate(
1882
			@RequestParam String planGroupId,
1883
			@RequestParam String date) {
1884
		int beatId = Integer.parseInt(planGroupId);
1885
		LocalDate target = LocalDate.parse(date);
1886
 
1887
		Beat beat = beatRepository.selectById(beatId);
1888
		if (beat == null) return responseSender.badRequest("Beat not found");
1889
 
1890
		List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beatId);
1891
		int removed = 0;
1892
		for (BeatSchedule s : schedules) {
1893
			if (s.getStartDate() != null && s.getStartDate().equals(target)) {
1894
				beatScheduleRepository.delete(s);
1895
				removed++;
1896
			}
1897
		}
1898
		if (removed == 0) return responseSender.badRequest("No schedule found for that date");
1899
 
1900
		// If no real-date schedules left, drop in a placeholder so the beat
1901
		// remains visible in the unscheduled bucket.
1902
		boolean hasReal = schedules.stream()
1903
				.filter(s -> !s.getStartDate().equals(target))
1904
				.anyMatch(s -> s.getStartDate() != null && s.getStartDate().getYear() != 9999);
1905
		if (!hasReal) {
1906
			boolean hasPlaceholder = schedules.stream()
1907
					.filter(s -> !s.getStartDate().equals(target))
1908
					.anyMatch(s -> s.getStartDate() != null && s.getStartDate().getYear() == 9999);
1909
			if (!hasPlaceholder) {
1910
				BeatSchedule ph = new BeatSchedule();
1911
				ph.setBeatId(beatId);
1912
				ph.setStartDate(LocalDate.of(9999, 12, 31));
1913
				ph.setDayNumber(1);
1914
				ph.setEndAction("HOME");
1915
				ph.setCreatedTimestamp(LocalDateTime.now());
1916
				beatScheduleRepository.persist(ph);
1917
			}
1918
		}
1919
 
1920
		Map<String, Object> response = new HashMap<>();
1921
		response.put("status", true);
1922
		response.put("message", "Unscheduled from " + date);
1923
		return responseSender.ok(response);
1924
	}
1925
 
1926
	// Move a beat from one date to another — used by calendar drag-and-drop.
1927
	// Just updates the start_date of the matching beat_schedule row.
1928
	@PostMapping(value = "/beatPlan/moveScheduleDate")
1929
	public ResponseEntity<?> moveScheduleDate(
1930
			@RequestParam String planGroupId,
1931
			@RequestParam String fromDate,
1932
			@RequestParam String toDate) {
1933
		int beatId = Integer.parseInt(planGroupId);
1934
		LocalDate from = LocalDate.parse(fromDate);
1935
		LocalDate to = LocalDate.parse(toDate);
1936
 
1937
		if (from.equals(to)) {
1938
			Map<String, Object> ok = new HashMap<>();
1939
			ok.put("status", true);
1940
			ok.put("message", "Same date — no change");
1941
			return responseSender.ok(ok);
1942
		}
1943
 
1944
		Beat beat = beatRepository.selectById(beatId);
1945
		if (beat == null) return responseSender.badRequest("Beat not found");
1946
 
1947
		List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beatId);
1948
 
1949
		// Reject if the beat is already on the target date
1950
		boolean conflict = schedules.stream()
1951
				.anyMatch(s -> s.getStartDate() != null && s.getStartDate().equals(to));
1952
		if (conflict) return responseSender.badRequest("Beat is already scheduled on " + toDate);
1953
 
1954
		BeatSchedule match = schedules.stream()
1955
				.filter(s -> s.getStartDate() != null && s.getStartDate().equals(from))
1956
				.findFirst().orElse(null);
1957
		if (match == null) return responseSender.badRequest("No schedule found for " + fromDate);
1958
 
1959
		match.setStartDate(to);
1960
		// Recompute endDate as the max across all (post-update) schedules
1961
		LocalDate newEnd = schedules.stream()
1962
				.map(s -> s == match ? to : s.getStartDate())
1963
				.filter(d -> d != null && d.getYear() != 9999)
1964
				.max(LocalDate::compareTo).orElse(to);
1965
		for (BeatSchedule s : schedules) {
1966
			if (s.getStartDate() != null && s.getStartDate().getYear() != 9999) {
1967
				s.setEndDate(newEnd);
1968
			}
1969
		}
1970
 
1971
		Map<String, Object> response = new HashMap<>();
1972
		response.put("status", true);
1973
		response.put("message", "Moved from " + fromDate + " to " + toDate);
1974
		return responseSender.ok(response);
1975
	}
1976
 
36618 ranu 1977
	@GetMapping(value = "/beatPlan/calendar")
1978
	public ResponseEntity<?> getCalendar(
1979
			@RequestParam int authUserId,
1980
			@RequestParam String month) {
1981
 
1982
		YearMonth ym = YearMonth.parse(month);
1983
		LocalDate startDate = ym.atDay(1);
1984
		LocalDate endDate = ym.atEndOfMonth();
1985
 
1986
		List<PublicHolidays> holidays = publicHolidaysRepository.selectAllBetweenDates(startDate, endDate);
1987
		List<Map<String, String>> holidayList = holidays.stream().map(h -> {
1988
			Map<String, String> m = new HashMap<>();
1989
			m.put("date", h.getDate().toString());
1990
			m.put("occasion", h.getOccasion());
1991
			return m;
1992
		}).collect(Collectors.toList());
1993
 
36644 ranu 1994
		List<Beat> allBeats = beatRepository.selectActiveByAuthUserId(authUserId);
36618 ranu 1995
		LocalDate today = LocalDate.now();
1996
		List<Map<String, Object>> scheduledBeats = new ArrayList<>();
1997
 
36644 ranu 1998
		for (Beat beat : allBeats) {
1999
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(beat.getId());
2000
			List<BeatRoute> routes = beatRouteRepository.selectByBeatId(beat.getId());
36618 ranu 2001
 
36644 ranu 2002
			boolean allNullDates = schedules.isEmpty() || schedules.stream().allMatch(s -> s.getStartDate().getYear() == 9999);
2003
			boolean hasToday = !allNullDates && schedules.stream().anyMatch(s -> s.getStartDate().equals(today));
2004
			boolean allPast = !allNullDates && schedules.stream().filter(s -> s.getStartDate().getYear() != 9999).allMatch(s -> s.getStartDate().isBefore(today));
2005
			boolean allFuture = !allNullDates && schedules.stream().filter(s -> s.getStartDate().getYear() != 9999).allMatch(s -> s.getStartDate().isAfter(today));
36618 ranu 2006
 
2007
			String status;
2008
			if (allNullDates) status = "unscheduled";
2009
			else if (hasToday) status = "running";
2010
			else if (allPast) status = "completed";
36644 ranu 2011
			else status = "scheduled";
36618 ranu 2012
 
36644 ranu 2013
			Map<String, Object> beatInfo = new HashMap<>();
2014
			beatInfo.put("planGroupId", String.valueOf(beat.getId()));
2015
			beatInfo.put("beatName", beat.getName() != null ? beat.getName() : "Beat");
2016
			beatInfo.put("beatColor", beat.getBeatColor() != null ? beat.getBeatColor() : "#3498DB");
2017
			beatInfo.put("status", status);
36618 ranu 2018
 
2019
			List<Map<String, Object>> dayInfoList = new ArrayList<>();
36644 ranu 2020
			for (BeatSchedule s : schedules) {
36618 ranu 2021
				Map<String, Object> dayInfo = new HashMap<>();
36644 ranu 2022
				dayInfo.put("dayNumber", s.getDayNumber());
2023
				boolean isUnscheduled = s.getStartDate().getYear() == 9999;
2024
				dayInfo.put("planDate", isUnscheduled ? null : s.getStartDate().toString());
2025
				dayInfo.put("totalKm", s.getTotalDistanceKm());
2026
				dayInfo.put("totalMins", s.getTotalTimeMins());
36711 ranu 2027
                // endAction tells the planner whether to draw the return-to-home line
2028
                // for this day (HOME) or end at the last stop (DAYBREAK).
2029
                dayInfo.put("endAction", s.getEndAction());
36644 ranu 2030
				long visitCount = routes.stream().filter(r -> r.getDayNumber() == s.getDayNumber()).count();
2031
				dayInfo.put("visitCount", (int) visitCount);
36618 ranu 2032
				dayInfoList.add(dayInfo);
2033
			}
36644 ranu 2034
			if (schedules.isEmpty()) {
2035
				// No schedule at all — show from routes
2036
				Map<Integer, Long> dayCounts = routes.stream()
2037
						.collect(Collectors.groupingBy(BeatRoute::getDayNumber, Collectors.counting()));
2038
				for (int d = 1; d <= beat.getTotalDays(); d++) {
2039
					Map<String, Object> dayInfo = new HashMap<>();
2040
					dayInfo.put("dayNumber", d);
2041
					dayInfo.put("planDate", null);
2042
					dayInfo.put("totalKm", null);
2043
					dayInfo.put("totalMins", null);
2044
					dayInfo.put("visitCount", dayCounts.getOrDefault(d, 0L).intValue());
2045
					dayInfoList.add(dayInfo);
2046
				}
2047
			}
2048
			beatInfo.put("days", dayInfoList);
2049
			scheduledBeats.add(beatInfo);
36618 ranu 2050
		}
2051
 
2052
		Set<String> blockedDates = new HashSet<>();
2053
		for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
36644 ranu 2054
			if (d.getDayOfWeek() == DayOfWeek.SUNDAY) blockedDates.add(d.toString());
36618 ranu 2055
		}
36644 ranu 2056
		for (PublicHolidays h : holidays) blockedDates.add(h.getDate().toString());
36618 ranu 2057
 
2058
		Map<String, Object> response = new HashMap<>();
2059
		response.put("holidays", holidayList);
2060
		response.put("scheduledBeats", scheduledBeats);
2061
		response.put("blockedDates", blockedDates);
2062
		return responseSender.ok(response);
2063
	}
2064
 
2065
	@PostMapping(value = "/beatPlan/scheduleOnCalendar")
2066
	public ResponseEntity<?> scheduleOnCalendar(
2067
			HttpServletRequest request,
2068
			@RequestParam String planGroupId,
2069
			@RequestParam String dates,
2070
			@RequestParam(required = false) String beatName,
2071
			@RequestParam(required = false) String beatColor) throws Exception {
2072
 
36644 ranu 2073
		int beatId = Integer.parseInt(planGroupId);
36618 ranu 2074
		Gson gson = new Gson();
2075
		List<String> dateList = gson.fromJson(dates, new TypeToken<List<String>>() {
2076
		}.getType());
2077
 
36644 ranu 2078
		Beat beat = beatRepository.selectById(beatId);
2079
		if (beat == null) return responseSender.badRequest("Beat not found");
36618 ranu 2080
 
36644 ranu 2081
		if (beatName != null) beat.setName(beatName);
2082
		if (beatColor != null && !beatColor.isEmpty()) beat.setBeatColor(beatColor);
36618 ranu 2083
 
36644 ranu 2084
		// Delete old schedules and create new
2085
		beatScheduleRepository.deleteByBeatId(beatId);
2086
		LocalDate schEndDate = dateList.isEmpty() ? null : LocalDate.parse(dateList.get(dateList.size() - 1));
2087
		for (int i = 0; i < dateList.size() && i < beat.getTotalDays(); i++) {
36711 ranu 2088
            int dayNumber = i + 1;
2089
            String endAction = (i == dateList.size() - 1) ? "HOME" : "DAYBREAK";
36644 ranu 2090
			BeatSchedule schedule = new BeatSchedule();
2091
			schedule.setBeatId(beatId);
2092
			schedule.setStartDate(LocalDate.parse(dateList.get(i)));
2093
			schedule.setEndDate(schEndDate);
36711 ranu 2094
            schedule.setDayNumber(dayNumber);
2095
            schedule.setEndAction(endAction);
2096
            // Fill total_distance_km / total_time_mins from beat_route so the new
2097
            // schedule row isn't NULL (this was the bug — these were left unset).
2098
            double[] totals = computeDayTotals(beatId, dayNumber, endAction);
2099
            schedule.setTotalDistanceKm(totals[0]);
2100
            schedule.setTotalTimeMins((int) totals[1]);
36644 ranu 2101
			schedule.setCreatedTimestamp(LocalDateTime.now());
2102
			beatScheduleRepository.persist(schedule);
36618 ranu 2103
		}
2104
 
2105
		Map<String, Object> response = new HashMap<>();
2106
		response.put("status", true);
2107
		response.put("message", "Beat scheduled successfully");
2108
		return responseSender.ok(response);
2109
	}
2110
 
36644 ranu 2111
	// Drag-drop scheduling — adds schedule dates to the EXISTING beat (no new beat created)
36618 ranu 2112
	@PostMapping(value = "/beatPlan/repeatBeat")
2113
	public ResponseEntity<?> repeatBeat(
2114
			HttpServletRequest request,
2115
			@RequestParam String sourcePlanGroupId,
2116
			@RequestParam int authUserId,
2117
			@RequestParam String dates) throws Exception {
2118
 
36644 ranu 2119
		int beatId = Integer.parseInt(sourcePlanGroupId);
36618 ranu 2120
		Gson gson = new Gson();
2121
		List<String> dateList = gson.fromJson(dates, new TypeToken<List<String>>() {
2122
		}.getType());
2123
 
36644 ranu 2124
		Beat beat = beatRepository.selectById(beatId);
2125
		if (beat == null) return responseSender.badRequest("Beat not found");
36618 ranu 2126
 
36644 ranu 2127
		// Remove placeholder (unscheduled) schedule rows
2128
		List<BeatSchedule> existing = beatScheduleRepository.selectByBeatId(beatId);
2129
		for (BeatSchedule s : existing) {
2130
			if (s.getStartDate() != null && s.getStartDate().getYear() == 9999) {
2131
				beatScheduleRepository.delete(s);
2132
			}
36618 ranu 2133
		}
2134
 
36711 ranu 2135
        // Add new real-date schedule rows for the existing beat — fill totals
2136
        // from beat_route so total_distance_km / total_time_mins aren't NULL.
36644 ranu 2137
		LocalDate repeatEndDate = dateList.isEmpty() ? null : LocalDate.parse(dateList.get(dateList.size() - 1));
2138
		for (int i = 0; i < dateList.size(); i++) {
36711 ranu 2139
            int dayNumber = i + 1;
2140
            String endAction = (i == dateList.size() - 1) ? "HOME" : "DAYBREAK";
36644 ranu 2141
			BeatSchedule schedule = new BeatSchedule();
2142
			schedule.setBeatId(beatId);
2143
			schedule.setStartDate(LocalDate.parse(dateList.get(i)));
2144
			schedule.setEndDate(repeatEndDate);
36711 ranu 2145
            schedule.setDayNumber(dayNumber);
2146
            schedule.setEndAction(endAction);
2147
            double[] totals = computeDayTotals(beatId, dayNumber, endAction);
2148
            schedule.setTotalDistanceKm(totals[0]);
2149
            schedule.setTotalTimeMins((int) totals[1]);
36644 ranu 2150
			schedule.setCreatedTimestamp(LocalDateTime.now());
2151
			beatScheduleRepository.persist(schedule);
36618 ranu 2152
		}
2153
 
2154
		Map<String, Object> response = new HashMap<>();
2155
		response.put("status", true);
36644 ranu 2156
		response.put("planGroupId", String.valueOf(beatId));
2157
		response.put("message", "Beat scheduled successfully");
36618 ranu 2158
		return responseSender.ok(response);
2159
	}
2160
 
2161
	@GetMapping(value = "/beatPlan/availableSlots")
2162
	public ResponseEntity<?> getAvailableSlots(
2163
			@RequestParam int authUserId,
2164
			@RequestParam String month,
2165
			@RequestParam int daysNeeded) {
2166
 
2167
		YearMonth ym = YearMonth.parse(month);
2168
		LocalDate startDate = ym.atDay(1);
2169
		LocalDate endDate = ym.atEndOfMonth();
2170
		LocalDate today = LocalDate.now();
2171
 
2172
		Set<LocalDate> blocked = new HashSet<>();
2173
		for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
2174
			if (d.getDayOfWeek() == DayOfWeek.SUNDAY) blocked.add(d);
36644 ranu 2175
			if (!d.isAfter(today)) blocked.add(d);
36618 ranu 2176
		}
2177
 
2178
		List<PublicHolidays> holidays = publicHolidaysRepository.selectAllBetweenDates(startDate, endDate);
2179
		for (PublicHolidays h : holidays) blocked.add(h.getDate());
2180
 
36644 ranu 2181
		// Get all scheduled dates for this user
2182
		List<Beat> userBeats = beatRepository.selectActiveByAuthUserId(authUserId);
2183
		for (Beat b : userBeats) {
2184
			List<BeatSchedule> schedules = beatScheduleRepository.selectByBeatId(b.getId());
2185
			for (BeatSchedule s : schedules) blocked.add(s.getStartDate());
36618 ranu 2186
		}
2187
 
2188
		List<String> available = new ArrayList<>();
2189
		for (LocalDate d = startDate.isAfter(today) ? startDate : today.plusDays(1);
2190
			 !d.isAfter(endDate) && available.size() < daysNeeded;
2191
			 d = d.plusDays(1)) {
36644 ranu 2192
			if (!blocked.contains(d)) available.add(d.toString());
36618 ranu 2193
		}
2194
 
2195
		Map<String, Object> response = new HashMap<>();
2196
		response.put("suggestedDates", available);
2197
		response.put("totalAvailable", available.size());
2198
		return responseSender.ok(response);
2199
	}
2200
 
2201
	// --- Sorting helpers ---
2202
 
2203
	private List<Map<String, Object>> sortByNearestNeighborFromStart(
2204
			List<Map<String, Object>> partners, double startLat, double startLng) {
2205
		List<Map<String, Object>> withCoords = new ArrayList<>();
2206
		List<Map<String, Object>> withoutCoords = new ArrayList<>();
2207
		for (Map<String, Object> p : partners) {
36644 ranu 2208
			if (hasValidCoords(p)) withCoords.add(p);
2209
			else withoutCoords.add(p);
36618 ranu 2210
		}
2211
		List<Map<String, Object>> sorted = new ArrayList<>();
36644 ranu 2212
		double currentLat = startLat, currentLng = startLng;
36618 ranu 2213
		while (!withCoords.isEmpty()) {
2214
			int nearestIdx = 0;
2215
			double nearestDist = Double.MAX_VALUE;
2216
			for (int i = 0; i < withCoords.size(); i++) {
36644 ranu 2217
				double dist = haversine(currentLat, currentLng,
2218
						Double.parseDouble(withCoords.get(i).get("latitude").toString()),
2219
						Double.parseDouble(withCoords.get(i).get("longitude").toString()));
36618 ranu 2220
				if (dist < nearestDist) {
2221
					nearestDist = dist;
2222
					nearestIdx = i;
2223
				}
2224
			}
2225
			Map<String, Object> nearest = withCoords.remove(nearestIdx);
2226
			sorted.add(nearest);
2227
			currentLat = Double.parseDouble(nearest.get("latitude").toString());
2228
			currentLng = Double.parseDouble(nearest.get("longitude").toString());
2229
		}
2230
		sorted.addAll(withoutCoords);
2231
		return sorted;
2232
	}
2233
 
2234
	private List<Map<String, Object>> sortByNearestNeighbor(List<Map<String, Object>> partners) {
2235
		List<Map<String, Object>> withCoords = new ArrayList<>();
2236
		List<Map<String, Object>> withoutCoords = new ArrayList<>();
2237
		for (Map<String, Object> p : partners) {
36644 ranu 2238
			if (hasValidCoords(p)) withCoords.add(p);
2239
			else withoutCoords.add(p);
36618 ranu 2240
		}
2241
		List<Map<String, Object>> sorted = new ArrayList<>();
2242
		if (!withCoords.isEmpty()) {
2243
			sorted.add(withCoords.remove(0));
2244
			while (!withCoords.isEmpty()) {
2245
				Map<String, Object> last = sorted.get(sorted.size() - 1);
2246
				double lastLat = Double.parseDouble(last.get("latitude").toString());
2247
				double lastLng = Double.parseDouble(last.get("longitude").toString());
2248
				int nearestIdx = 0;
2249
				double nearestDist = Double.MAX_VALUE;
2250
				for (int i = 0; i < withCoords.size(); i++) {
36644 ranu 2251
					double dist = haversine(lastLat, lastLng,
2252
							Double.parseDouble(withCoords.get(i).get("latitude").toString()),
2253
							Double.parseDouble(withCoords.get(i).get("longitude").toString()));
36618 ranu 2254
					if (dist < nearestDist) {
2255
						nearestDist = dist;
2256
						nearestIdx = i;
2257
					}
2258
				}
2259
				sorted.add(withCoords.remove(nearestIdx));
2260
			}
2261
		}
2262
		sorted.addAll(withoutCoords);
2263
		return sorted;
2264
	}
2265
 
2266
	private boolean hasValidCoords(Map<String, Object> p) {
2267
		Object lat = p.get("latitude");
2268
		Object lng = p.get("longitude");
36644 ranu 2269
		return lat != null && lng != null && !lat.toString().isEmpty() && !lng.toString().isEmpty();
36618 ranu 2270
	}
2271
 
2272
	private double haversine(double lat1, double lng1, double lat2, double lng2) {
2273
		double R = 6371;
2274
		double dLat = Math.toRadians(lat2 - lat1);
2275
		double dLng = Math.toRadians(lng2 - lng1);
2276
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
2277
				+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
2278
				* Math.sin(dLng / 2) * Math.sin(dLng / 2);
2279
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
2280
		return R * c;
2281
	}
2282
}