Subversion Repositories SmartDukaan

Rev

Rev 37178 | Details | Compare with Previous | Last modification | View Log | RSS feed

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