Subversion Repositories SmartDukaan

Rev

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

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