Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
24383 amit.gupta 1
package com.spice.profitmandi.dao.repository.cs;
24500 govind 2
 
26418 tejbeer 3
import java.time.LocalDate;
24383 amit.gupta 4
import java.time.LocalDateTime;
26418 tejbeer 5
import java.time.LocalTime;
24417 govind 6
import java.util.ArrayList;
25721 tejbeer 7
import java.util.Arrays;
26298 tejbeer 8
import java.util.Collection;
24417 govind 9
import java.util.HashMap;
24439 govind 10
import java.util.HashSet;
26418 tejbeer 11
import java.util.LinkedHashMap;
24417 govind 12
import java.util.List;
13
import java.util.Map;
26298 tejbeer 14
import java.util.Map.Entry;
25570 tejbeer 15
import java.util.Set;
16
import java.util.stream.Collectors;
24500 govind 17
 
25570 tejbeer 18
import org.apache.commons.collections4.map.HashedMap;
24439 govind 19
import org.apache.commons.lang.RandomStringUtils;
20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
24383 amit.gupta 22
import org.springframework.beans.factory.annotation.Autowired;
25726 amit.gupta 23
import org.springframework.cache.annotation.Cacheable;
24439 govind 24
import org.springframework.mail.javamail.JavaMailSender;
24383 amit.gupta 25
import org.springframework.stereotype.Component;
24701 govind 26
 
26298 tejbeer 27
import com.google.common.collect.HashMultimap;
28
import com.google.common.collect.Multimap;
24383 amit.gupta 29
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24417 govind 30
import com.spice.profitmandi.common.model.CustomRetailer;
24439 govind 31
import com.spice.profitmandi.common.model.ProfitMandiConstants;
32
import com.spice.profitmandi.common.util.Utils;
24417 govind 33
import com.spice.profitmandi.dao.entity.auth.AuthUser;
24383 amit.gupta 34
import com.spice.profitmandi.dao.entity.cs.Activity;
24417 govind 35
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
36
import com.spice.profitmandi.dao.entity.cs.Position;
24471 govind 37
import com.spice.profitmandi.dao.entity.cs.Region;
24383 amit.gupta 38
import com.spice.profitmandi.dao.entity.cs.Ticket;
24500 govind 39
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
24439 govind 40
import com.spice.profitmandi.dao.entity.cs.TicketCategory;
24417 govind 41
import com.spice.profitmandi.dao.entity.cs.TicketSubCategory;
24383 amit.gupta 42
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
26418 tejbeer 43
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
44
import com.spice.profitmandi.dao.entity.user.Lead;
24417 govind 45
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26418 tejbeer 46
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
47
import com.spice.profitmandi.dao.model.PartnerDetailModel;
24417 govind 48
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25570 tejbeer 49
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
26418 tejbeer 50
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
51
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
52
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
53
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
54
import com.spice.profitmandi.service.PartnerInvestmentService;
24417 govind 55
import com.spice.profitmandi.service.user.RetailerService;
24383 amit.gupta 56
 
57
@Component
58
public class CsServiceImpl implements CsService {
24417 govind 59
 
24439 govind 60
	private static final Logger LOGGER = LogManager.getLogger(CsServiceImpl.class);
61
 
24570 govind 62
	private static final String ASSIGNED_TICKET = "Dear %s,You have assigned a ticket by %s with ticketId#%s.Regards\nSmartdukaan";
24439 govind 63
	private static final String ASSINMENT_SUBJECT = "Assignment Ticket";
64
 
24383 amit.gupta 65
	@Autowired
66
	TicketRepository ticketRepository;
24417 govind 67
 
24383 amit.gupta 68
	@Autowired
24439 govind 69
	JavaMailSender mailSender;
70
 
71
	@Autowired
24383 amit.gupta 72
	TicketCategoryRepository ticketCategoryRepository;
24417 govind 73
 
24383 amit.gupta 74
	@Autowired
75
	TicketSubCategoryRepository ticketSubCategoryRepository;
24417 govind 76
 
77
	@Autowired
24388 amit.gupta 78
	ActivityRepository activityRepository;
24417 govind 79
 
80
	@Autowired
24439 govind 81
	PartnerRegionRepository partnerRegionRepository;
24417 govind 82
 
83
	@Autowired
84
	private PositionRepository positionRepository;
85
 
86
	@Autowired
87
	private AuthRepository authRepository;
88
 
89
	@Autowired
90
	private RetailerService retailerService;
24500 govind 91
 
24471 govind 92
	@Autowired
93
	private RegionRepository regionRepository;
24417 govind 94
 
24500 govind 95
	@Autowired
96
	private TicketAssignedRepository ticketAssignedRepository;
97
 
25570 tejbeer 98
	@Autowired
99
	private PartnersPositionRepository partnersPositionRepository;
100
 
101
	@Autowired
102
	private FofoStoreRepository fofoStoreRepository;
103
 
26418 tejbeer 104
	@Autowired
105
	private FofoOrderItemRepository fofoOrderItemRepository;
106
 
107
	@Autowired
108
	private LeadRepository leadRepository;
109
 
110
	@Autowired
111
	private HygieneDataRepository hygieneDataRepository;
112
 
113
	@Autowired
114
	private PartnerInvestmentService partnerInvestmentService;
115
 
116
	@Autowired
117
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
118
 
24383 amit.gupta 119
	@Override
24439 govind 120
	public void createTicket(int fofoId, int categoryId, int subcategoryId, String message)
121
			throws ProfitMandiBusinessException {
24417 govind 122
 
24383 amit.gupta 123
		ActivityType type = ActivityType.OPENED;
24439 govind 124
		EscalationType escalationTypeL1 = EscalationType.L1;
125
		EscalationType escalationTypeL2 = EscalationType.L2;
126
		EscalationType escalationTypeL3 = EscalationType.L3;
24383 amit.gupta 127
		Ticket ticket = new Ticket();
24500 govind 128
		TicketAssigned ticketAssigned = new TicketAssigned();
24383 amit.gupta 129
		ticket.setSubCategoryId(subcategoryId);
24417 govind 130
		ticket.setFofoId(fofoId);
24383 amit.gupta 131
		ticket.setCreateTimestamp(LocalDateTime.now());
24417 govind 132
		ticket.setUpdateTimestamp(LocalDateTime.now());
24467 govind 133
		ticket.setL2EscalationTimestamp(ticket.getUpdateTimestamp().plusDays(2));
134
		ticket.setL3EscalationTimestamp(ticket.getL2EscalationTimestamp().plusDays(2));
135
		ticket.setLastEscalationTimestamp(ticket.getL3EscalationTimestamp().plusDays(2));
24439 govind 136
		ticket.setHappyCode(getRandomString());
137
		int l1Auth = this.getAuthUserId(categoryId, escalationTypeL1, fofoId);
24699 govind 138
		LOGGER.info("l1Auth" + l1Auth);
24439 govind 139
		int l2Auth = this.getAuthUserId(categoryId, escalationTypeL2, fofoId);
24699 govind 140
		LOGGER.info("l2Auth" + l2Auth);
24557 govind 141
		int l3Auth = this.getAuthUserId(categoryId, escalationTypeL3, fofoId);
24699 govind 142
		LOGGER.info("l3Auth" + l3Auth);
24439 govind 143
		if (l1Auth == 0) {
144
			if (l2Auth == 0) {
24500 govind 145
				this.setAssignment(ticket, ticketAssigned);
24439 govind 146
			} else {
24500 govind 147
				ticketAssigned.setAssineeId(l2Auth);
24526 govind 148
				ticket.setL1AuthUser(l2Auth);
149
				ticket.setL2AuthUser(l2Auth);
24439 govind 150
			}
151
		} else {
24500 govind 152
			ticketAssigned.setAssineeId(l1Auth);
24439 govind 153
			ticket.setL1AuthUser(l1Auth);
154
			ticket.setL2AuthUser(l2Auth);
155
		}
24699 govind 156
		if (ticket.getL2AuthUser() == 0) {
24569 govind 157
			ticket.setL2AuthUser(l3Auth);
158
		}
24439 govind 159
		ticket.setL3AuthUser(l3Auth);
160
		ticketRepository.persist(ticket);
24500 govind 161
		ticketAssigned.setTicketId(ticket.getId());
162
		ticketAssignedRepository.persist(ticketAssigned);
163
		AuthUser authUser = authRepository.selectById(ticketAssigned.getAssineeId());
24569 govind 164
		this.sendAssignedTicketMail(authUser, ticket);
24383 amit.gupta 165
		Activity activity = this.createActivity(type, message, 0);
166
		this.addActivity(ticket.getId(), activity);
167
	}
168
 
169
	private Activity createActivity(ActivityType activityType, String message, int createdBy) {
170
		Activity activity = new Activity();
171
		activity.setMessage(message);
172
		activity.setCreatedBy(createdBy);
173
		activity.setType(activityType);
24417 govind 174
		activity.setCreateTimestamp(LocalDateTime.now());
24383 amit.gupta 175
		return activity;
176
	}
24417 govind 177
 
24439 govind 178
	private int getAuthUserId(int categoryId, EscalationType escalationType, int fofoId) {
24417 govind 179
 
24439 govind 180
		List<Position> positions = null;
181
		if (escalationType == EscalationType.L3) {
182
			positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(0, escalationType, 0);
183
		} else {
184
			List<PartnerRegion> regions = partnerRegionRepository.selectByfofoId(fofoId);
185
			LOGGER.info("regions=" + regions);
24500 govind 186
			if (regions.size() == 0) {
187
				regions = partnerRegionRepository.selectByfofoId(0);
24452 govind 188
				LOGGER.info("regions=" + regions);
189
			}
24439 govind 190
			for (PartnerRegion region : regions) {
24699 govind 191
				LOGGER.info(categoryId + ":" + escalationType + ":" + region.getRegionId());
24439 govind 192
				positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType,
193
						region.getRegionId());
194
				LOGGER.info("positions:-" + positions);
24500 govind 195
				if (positions.size() > 0) {
24439 govind 196
					break;
197
				}
198
 
199
			}
200
			if (positions.size() == 0) {
24557 govind 201
				if (escalationType == EscalationType.L1) {
202
					regions = partnerRegionRepository.selectByfofoId(0);
203
					LOGGER.info("regions=" + regions);
204
					for (PartnerRegion region : regions) {
205
						positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId,
206
								escalationType, region.getRegionId());
207
						LOGGER.info("positions:-" + positions);
208
						if (positions.size() > 0) {
209
							break;
210
						}
211
					}
212
				} else {
213
					regions = partnerRegionRepository.selectByfofoId(0);
214
					LOGGER.info("regions=" + regions);
215
					for (PartnerRegion region : regions) {
216
						positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId,
217
								escalationType, region.getRegionId());
218
						LOGGER.info("positions:-" + positions);
219
						if (positions.size() > 0) {
220
							break;
221
						}
222
					}
223
				}
24439 govind 224
			}
24699 govind 225
 
24439 govind 226
		}
24699 govind 227
		if (positions.size() == 0) {
24557 govind 228
			return 0;
229
		}
230
		LOGGER.info(positions.get(0).getAuthUserId());
24439 govind 231
		return positions.get(0).getAuthUserId();
24417 govind 232
		/*
233
		 * if(ActivityType.escalationTypes.contains(escalationType)) {
234
		 * //escalationMatrix } else { throw new
235
		 * ProfitMandiBusinessException("SubCategory", subcategoryId,
236
		 * "Could not find Assignee for "); }
237
		 */
24439 govind 238
 
24383 amit.gupta 239
	}
240
 
241
	@Override
242
	public void addActivity(int ticketId, Activity activity) {
243
		activity.setTicketId(ticketId);
24417 govind 244
		activityRepository.persist(activity);
24383 amit.gupta 245
	}
246
 
24439 govind 247
	private String getRandomString() {
248
		int length = 4;
249
		boolean useLetters = false;
250
		boolean useNumbers = true;
251
		String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
252
		return generatedString;
253
	}
254
 
24417 govind 255
	@Override
256
	public void addPartnerToRegion(int regionId, List<Integer> fofoIds) {
257
 
24557 govind 258
		for (int fofoId : fofoIds) {
259
			PartnerRegion partnerRegion = new PartnerRegion();
260
			partnerRegion.setFofoId(fofoId);
261
			partnerRegion.setRegionId(regionId);
262
			partnerRegionRepository.persist(partnerRegion);
24417 govind 263
		}
264
	}
265
 
266
	@Override
24500 govind 267
	public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMap(List<TicketAssigned> ticketAssigneds) {
24417 govind 268
		Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();
24500 govind 269
 
270
		for (TicketAssigned ticketAssigned : ticketAssigneds) {
271
			AuthUser authUser = authRepository.selectById(ticketAssigned.getAssineeId());
272
			authUserIdAndAuthUserMap.put(ticketAssigned.getTicketId(), authUser);
273
		}
274
		return authUserIdAndAuthUserMap;
275
	}
276
 
277
	@Override
278
	public Map<Integer, AuthUser> getTicketIdAndAuthUserMapUsingTickets(List<Ticket> tickets) {
279
		Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();
280
 
24417 govind 281
		for (Ticket ticket : tickets) {
24500 govind 282
			AuthUser authUser = authRepository.selectById(ticket.getL1AuthUser());
283
			authUserIdAndAuthUserMap.put(ticket.getId(), authUser);
24417 govind 284
		}
285
		return authUserIdAndAuthUserMap;
286
	}
287
 
288
	@Override
289
	public Map<Integer, TicketSubCategory> getSubCategoryIdAndSubCategoryMap(List<Ticket> tickets) {
290
		Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = new HashMap<>();
24699 govind 291
		if (tickets != null) {
292
			for (Ticket ticket : tickets) {
293
				TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
294
				subCategoryIdAndSubCategoryMap.put(ticket.getSubCategoryId(), ticketSubCategory);
295
			}
24417 govind 296
		}
297
		return subCategoryIdAndSubCategoryMap;
298
	}
299
 
300
	@Override
301
	public Map<Integer, CustomRetailer> getPartnerByFofoIds(List<Ticket> tickets) {
302
		List<Integer> fofoIds = new ArrayList<>();
24569 govind 303
		LOGGER.info(tickets);
24699 govind 304
		if (tickets == null) {
24569 govind 305
			return null;
306
		}
24417 govind 307
		for (Ticket ticket : tickets) {
308
			fofoIds.add(ticket.getFofoId());
309
		}
24699 govind 310
		Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = retailerService.getFofoRetailers(fofoIds);
24417 govind 311
		return fofoIdsAndCustomRetailer;
312
	}
313
 
24439 govind 314
	@Override
315
	public List<TicketCategory> getAllTicketCategotyFromSubCategory() {
316
 
317
		List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAll();
318
		HashSet<Integer> categoryIds = new HashSet<>();
319
		for (TicketSubCategory ticketSubcategory : ticketSubCategories) {
320
			categoryIds.add(ticketSubcategory.getcategoryId());
321
		}
322
		List<TicketCategory> ticketcategories = ticketCategoryRepository.selectAll(new ArrayList<>(categoryIds));
323
		return ticketcategories;
324
	}
325
 
24500 govind 326
	private Ticket setAssignment(Ticket ticket, TicketAssigned ticketAssigned) {
24439 govind 327
		TicketCategory ticketCategory = ticketCategoryRepository.selectByName(ProfitMandiConstants.CRM);
328
		List<Position> positions = positionRepository.selectPositionByCategoryId(ticketCategory.getId());
329
		for (Position position : positions) {
330
			if (position.getEscalationType().equals(EscalationType.L1)) {
24500 govind 331
				ticketAssigned.setAssineeId(position.getAuthUserId());
24439 govind 332
				ticket.setL1AuthUser(position.getAuthUserId());
24557 govind 333
			} else if (position.getEscalationType().equals(EscalationType.L2)) {
24439 govind 334
				ticket.setL2AuthUser(position.getAuthUserId());
335
			}
336
		}
337
		return ticket;
338
	}
24500 govind 339
 
24471 govind 340
	@Override
341
	public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMapUsingPositions(List<Position> positions) {
342
		Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();
343
		for (Position position : positions) {
344
			AuthUser authUser = authRepository.selectById(position.getAuthUserId());
345
			authUserIdAndAuthUserMap.put(position.getAuthUserId(), authUser);
346
		}
347
		return authUserIdAndAuthUserMap;
348
	}
24500 govind 349
 
24471 govind 350
	@Override
351
	public Map<Integer, TicketCategory> getCategoryIdAndCategoryUsingPositions(List<Position> positions) {
352
		Map<Integer, TicketCategory> categoryIdAndCategoryMap = new HashMap<>();
353
		for (Position position : positions) {
24500 govind 354
			TicketCategory ticketCategory = ticketCategoryRepository.selectById(position.getCategoryId());
24471 govind 355
			categoryIdAndCategoryMap.put(position.getCategoryId(), ticketCategory);
356
		}
357
		return categoryIdAndCategoryMap;
358
	}
24439 govind 359
 
24471 govind 360
	@Override
361
	public Map<Integer, Region> getRegionIdAndRegionMap(List<Position> positions) {
362
		Map<Integer, Region> regionIdAndRegionMap = new HashMap<>();
363
		for (Position position : positions) {
24500 govind 364
			Region region = regionRepository.selectById(position.getRegionId());
24471 govind 365
			regionIdAndRegionMap.put(position.getRegionId(), region);
366
		}
367
		return regionIdAndRegionMap;
368
	}
24500 govind 369
 
370
	@Override
24699 govind 371
	public Map<Integer, List<AuthUser>> getAuthUserList(List<Ticket> tickets, AuthUser authUser) {
24500 govind 372
		Map<Integer, List<AuthUser>> authUserListMap = new HashMap<>();
373
		for (Ticket ticket : tickets) {
24570 govind 374
			if (ticket.getL2AuthUser() == authUser.getId()) {
24500 govind 375
				List<AuthUser> authUsers = new ArrayList<>();
376
				authUsers.add(authRepository.selectById(ticket.getL1AuthUser()));
377
				authUserListMap.put(ticket.getId(), authUsers);
378
 
24570 govind 379
			} else if (ticket.getL3AuthUser() == authUser.getId()) {
24500 govind 380
				TicketAssigned ticketAssigned = ticketAssignedRepository
381
						.selectByAssigneeIdAndTicketId(ticket.getL2AuthUser(), ticket.getId());
382
				if (ticketAssigned == null) {
383
					List<AuthUser> authUsers = new ArrayList<>();
384
					authUsers.add(authRepository.selectById(ticket.getL1AuthUser()));
385
					authUserListMap.put(ticket.getId(), authUsers);
386
				} else {
387
					List<AuthUser> authUsers = new ArrayList<>();
388
					authUsers.add(authRepository.selectById(ticket.getL1AuthUser()));
389
					authUsers.add(authRepository.selectById(ticket.getL2AuthUser()));
390
					authUserListMap.put(ticket.getId(), authUsers);
391
				}
392
			} else {
393
				TicketAssigned ticketAssigned = ticketAssignedRepository
394
						.selectByAssigneeIdAndTicketId(ticket.getL3AuthUser(), ticket.getId());
395
				if (ticketAssigned == null) {
396
					ticketAssigned = ticketAssignedRepository.selectByAssigneeIdAndTicketId(ticket.getL2AuthUser(),
397
							ticket.getId());
398
					if (ticketAssigned == null) {
399
						List<AuthUser> authUsers = new ArrayList<>();
400
						authUsers.add(authRepository.selectById(ticket.getL1AuthUser()));
401
						authUserListMap.put(ticket.getId(), authUsers);
402
					} else {
403
						List<AuthUser> authUsers = new ArrayList<>();
404
						authUsers.add(authRepository.selectById(ticket.getL1AuthUser()));
405
						authUsers.add(authRepository.selectById(ticket.getL2AuthUser()));
406
						authUserListMap.put(ticket.getId(), authUsers);
407
					}
408
				} else {
409
					List<AuthUser> authUsers = new ArrayList<>();
410
					authUsers.add(authRepository.selectById(ticket.getL1AuthUser()));
411
					authUsers.add(authRepository.selectById(ticket.getL2AuthUser()));
412
					authUsers.add(authRepository.selectById(ticket.getL3AuthUser()));
413
					authUserListMap.put(ticket.getId(), authUsers);
414
 
415
				}
416
			}
417
		}
418
		return authUserListMap;
419
	}
24557 govind 420
 
24500 govind 421
	@Override
24557 govind 422
	public void updateTicket(int categoryId, int subCategoryId, Ticket ticket) throws ProfitMandiBusinessException {
423
		TicketAssigned ticketAssigned = new TicketAssigned();
24500 govind 424
		ticket.setSubCategoryId(subCategoryId);
425
		ticket.setUpdateTimestamp(LocalDateTime.now());
426
		ticket.setL2EscalationTimestamp(ticket.getUpdateTimestamp().plusDays(2));
427
		ticket.setL3EscalationTimestamp(ticket.getL2EscalationTimestamp().plusDays(2));
428
		ticket.setLastEscalationTimestamp(ticket.getL3EscalationTimestamp().plusDays(2));
429
		int l3Auth = this.getAuthUserId(categoryId, EscalationType.L3, ticket.getFofoId());
25505 amit.gupta 430
		int l2Auth = this.getAuthUserId(categoryId, EscalationType.L2, ticket.getFofoId());
24500 govind 431
		int l1Auth = this.getAuthUserId(categoryId, EscalationType.L1, ticket.getFofoId());
432
		LOGGER.info(l1Auth + "-" + l2Auth + "-" + l3Auth);
433
		if (l1Auth == 0) {
434
			if (l2Auth == 0) {
435
				this.setAssignment(ticket, ticketAssigned);
436
			} else {
437
				ticketAssigned.setAssineeId(l2Auth);
24569 govind 438
				ticket.setL1AuthUser(0);
24536 govind 439
				ticket.setL2AuthUser(l2Auth);
24500 govind 440
			}
441
		} else {
442
			ticketAssigned.setAssineeId(l1Auth);
443
			ticket.setL1AuthUser(l1Auth);
444
			ticket.setL2AuthUser(l2Auth);
445
		}
446
		ticket.setL3AuthUser(l3Auth);
447
		ticketRepository.persist(ticket);
448
		ticketAssigned.setTicketId(ticket.getId());
449
		ticketAssignedRepository.persist(ticketAssigned);
450
		AuthUser authUser = authRepository.selectById(ticketAssigned.getAssineeId());
24569 govind 451
		this.sendAssignedTicketMail(authUser, ticket);
452
	}
453
 
454
	@Override
24699 govind 455
	public void sendAssignedTicketMail(AuthUser authUser, Ticket ticket) throws ProfitMandiBusinessException {
24500 govind 456
		try {
457
			Utils.sendMailWithAttachments(mailSender, authUser.getEmailId(), null, ASSINMENT_SUBJECT,
458
					String.format(ASSIGNED_TICKET, authUser.getFirstName(),
24699 govind 459
							retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName(), ticket.getId()),
24500 govind 460
					null);
461
		} catch (Exception e) {
462
			throw new ProfitMandiBusinessException("Ticket Assingment", authUser.getEmailId(),
463
					"Could not send ticket assignment mail");
464
		}
465
	}
25570 tejbeer 466
 
467
	@Override
468
	public Map<Integer, List<CustomRetailer>> getPositionCustomRetailerMap(List<Position> positions) {
469
		Map<Integer, List<CustomRetailer>> positionRetailerMap = new HashMap<>();
470
		for (Position position : positions) {
471
			List<Integer> fofoIds = partnersPositionRepository.selectByPositionId(position.getId()).stream()
472
					.map(x -> x.getFofoId()).collect(Collectors.toList());
473
 
474
			if (!fofoIds.isEmpty()) {
475
				if (fofoIds.contains(0)) {
476
					fofoIds = partnerRegionRepository.selectByRegionId(position.getRegionId()).stream()
477
							.map(x -> x.getFofoId()).collect(Collectors.toList());
478
					if (fofoIds.contains(0)) {
479
						fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
480
								.collect(Collectors.toList());
481
					}
482
 
483
				}
484
				positionRetailerMap.put(position.getId(),
485
						new ArrayList<CustomRetailer>(retailerService.getFofoRetailers(fofoIds).values()));
486
 
487
			}
488
		}
489
		return positionRetailerMap;
490
	}
491
 
492
	@Override
493
	public Map<Integer, List<CustomRetailer>> getpositionIdAndpartnerRegionMap(List<Position> positions) {
494
		Map<Integer, List<CustomRetailer>> positionIdAndpartnerRegionMap = new HashedMap<>();
495
		for (Position position : positions) {
496
			List<Integer> fofoIds = partnerRegionRepository.selectByRegionId(position.getRegionId()).stream()
497
					.map(x -> x.getFofoId()).collect(Collectors.toList());
498
 
499
			if (!fofoIds.isEmpty()) {
500
				if (fofoIds.contains(0)) {
501
					fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());
502
 
503
				}
504
 
505
				Map<Integer, CustomRetailer> fofoRetailers = retailerService.getFofoRetailers(fofoIds);
506
				positionIdAndpartnerRegionMap.put(position.getRegionId(),
507
						new ArrayList<CustomRetailer>(fofoRetailers.values()));
508
			}
509
 
510
		}
511
 
512
		return positionIdAndpartnerRegionMap;
513
	}
25597 amit.gupta 514
 
515
	@Override
25726 amit.gupta 516
	@Cacheable(value = "authUserEmailMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
25597 amit.gupta 517
	public Map<String, Set<String>> getAuthUserPartnerEmailMapping() {
518
		Map<String, Set<String>> storeGuyMap = new HashMap<>();
519
		Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
520
				.collect(Collectors.toSet());
521
		List<Position> categoryPositions = positionRepository
522
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
523
		Map<Integer, Position> positionsMap = categoryPositions.stream()
524
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
525
 
25721 tejbeer 526
		Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
25597 amit.gupta 527
		for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
528
			int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
529
			Set<String> partnerEmails = positionPartnerEntry.getValue().stream()
530
					.filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getEmail())
531
					.collect(Collectors.toSet());
532
			AuthUser authUser = authRepository.selectById(authUserId);
533
			if (authUser.isActive()) {
26298 tejbeer 534
				if (!storeGuyMap.containsKey(authUser.getEmailId())) {
26111 amit.gupta 535
					storeGuyMap.put(authUser.getEmailId(), partnerEmails);
536
				} else {
537
					storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
538
				}
25597 amit.gupta 539
			}
540
		}
541
		return storeGuyMap;
542
	}
25721 tejbeer 543
 
544
	@Override
25777 amit.gupta 545
	@Cacheable(value = "authUserEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
25721 tejbeer 546
	public Map<String, Set<Integer>> getAuthUserPartnerIdMapping() {
547
		Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
25777 amit.gupta 548
		Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
549
				.collect(Collectors.toSet());
25721 tejbeer 550
		List<Position> categoryPositions = positionRepository
551
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
552
		Map<Integer, Position> positionsMap = categoryPositions.stream()
553
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
554
 
555
		Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
556
		for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
557
			int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
25777 amit.gupta 558
			Set<Integer> partnerEmails = positionPartnerEntry.getValue().stream()
559
					.filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId())
25721 tejbeer 560
					.collect(Collectors.toSet());
561
			AuthUser authUser = authRepository.selectById(authUserId);
562
			if (authUser.isActive()) {
26298 tejbeer 563
				if (!storeGuyMap.containsKey(authUser.getEmailId())) {
26111 amit.gupta 564
					storeGuyMap.put(authUser.getEmailId(), partnerEmails);
565
				} else {
566
					storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
567
				}
25721 tejbeer 568
			}
569
		}
570
		return storeGuyMap;
571
	}
572
 
573
	@Override
574
	public List<String> getAuthUserByPartnerId(int fofoId) {
575
 
576
		List<String> emails = new ArrayList<>();
577
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
578
				.collect(Collectors.toList());
579
 
580
		regionIds.add(5);// All partners Id;
581
		List<Integer> fofoIds = new ArrayList<>();
582
		fofoIds.add(fofoId);
583
		fofoIds.add(0);
25799 tejbeer 584
 
585
		LOGGER.info("fofoIds" + fofoIds);
25721 tejbeer 586
		List<Integer> partnerPositionIds = partnersPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds)
587
				.stream().map(x -> x.getPositionId()).collect(Collectors.toList());
588
 
25799 tejbeer 589
		LOGGER.info("partnerPositionIds" + partnerPositionIds);
590
 
25721 tejbeer 591
		for (Integer partnerPostionId : partnerPositionIds) {
25799 tejbeer 592
			Position position = positionRepository.selectByIdAndCategoryId(partnerPostionId,
593
					ProfitMandiConstants.TICKET_CATEGORY_SALES);
594
			LOGGER.info("position" + position);
595
			if (position != null) {
25721 tejbeer 596
 
25799 tejbeer 597
				AuthUser authUser = authRepository.selectById(position.getAuthUserId());
598
				LOGGER.info("authUser" + authUser);
599
				emails.add(authUser.getEmailId());
600
			}
25721 tejbeer 601
		}
602
 
603
		return emails;
604
	}
26298 tejbeer 605
 
606
	@Override
607
	@Cacheable(value = "authUserIdPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
608
	public Map<Integer, List<Integer>> getAuthUserIdPartnerIdMapping() {
609
		Map<Integer, List<Integer>> storeGuyMap = new HashMap<>();
610
		Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
611
				.collect(Collectors.toSet());
612
		List<Position> categoryPositions = positionRepository
613
				.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
614
		Map<Integer, Position> positionsMap = categoryPositions.stream()
615
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
616
 
617
		Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
618
		for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
619
			int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
620
			List<Integer> partnerEmails = positionPartnerEntry.getValue().stream()
621
					.filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId())
622
					.collect(Collectors.toList());
623
			AuthUser authUser = authRepository.selectById(authUserId);
624
			if (authUser.isActive()) {
625
				if (!storeGuyMap.containsKey(authUser.getEmailId())) {
626
					storeGuyMap.put(authUser.getId(), partnerEmails);
627
				} else {
628
					storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
629
				}
630
			}
631
		}
632
		return storeGuyMap;
633
	}
634
 
635
	@Override
636
	@Cacheable(value = "L1L2Mapping", cacheManager = "thirtyMinsTimeOutCacheManager")
637
	public Map<Integer, List<Integer>> getL1L2Mapping() {
638
		List<Position> positions = positionRepository.selectPositionsByEscalationType(EscalationType.L1);
639
		LOGGER.info("position" + positions);
640
		Map<Integer, List<Integer>> map = this.getAuthUserIdPartnerIdMapping();
641
		LOGGER.info("map" + map);
642
 
643
		Map<Integer, Integer> l1andl2Map = new HashMap<>();
644
 
645
		for (Position position : positions) {
646
 
647
			if (map.containsKey(position.getAuthUserId())) {
648
				LOGGER.info("authId" + position.getAuthUserId());
649
				LOGGER.info("Vals" + map.get(position.getAuthUserId()));
650
				List<Integer> fofoIds = map.get(position.getAuthUserId());
651
				Integer fofoId = fofoIds.get(0);
652
				LOGGER.info("fofo" + fofoId);
653
				List<Position> l2position = new ArrayList<>();
654
 
655
				List<Position> finall2position = new ArrayList<>();
656
 
657
				for (Map.Entry<Integer, List<Integer>> bs : map.entrySet()) {
658
					if (!bs.getKey().equals(position.getAuthUserId())) {
659
 
660
						if (bs.getValue().contains(fofoId)) {
661
 
662
							LOGGER.info("key" + bs.getKey());
663
 
664
							l2position = positionRepository.selectPositionsByAuthUserAndEscalationType(bs.getKey(),
665
									EscalationType.L2);
666
 
667
							finall2position.addAll(l2position);
668
 
669
						}
670
					}
671
				}
672
				LOGGER.info("alll2position" + finall2position);
673
 
674
				l1andl2Map.put(position.getAuthUserId(), finall2position.get(0).getAuthUserId());
675
			}
676
 
677
		}
678
 
679
		Map<Integer, List<Integer>> l2andl1Map = l1andl2Map.entrySet().stream().collect(
680
				Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
681
		return l2andl1Map;
682
	}
26418 tejbeer 683
 
684
	@Override
685
	public Map<Integer, Object> getL2AuthUserPartnerDetail() throws Exception {
686
		List<Position> pos = positionRepository.selectPositionbyCategoryIdAndEscalationType(
687
				ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
688
 
689
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
690
		Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(
691
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
692
		Map<Integer, Double> mtdSale = fofoOrderItemRepository.selectSumAmountGroupByRetailer(curDate.withDayOfMonth(1),
693
				curDate.with(LocalTime.MAX), 0, false);
694
 
695
		Map<Integer, List<Integer>> pp = this.getAuthUserIdPartnerIdMapping();
696
		Map<Integer, Long> ticketMap = ticketRepository.selectAllNotClosedTicketsGroupByRetailer();
697
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
698
		Map<Integer, List<Integer>> L2L1Mapping = this.getL1L2Mapping();
699
 
700
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
701
			List<Integer> authIds = l2l1.getValue();
702
			authIds.add(l2l1.getKey());
703
 
704
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
705
 
706
			AuthUser auth = authRepository.selectById(l2l1.getKey());
707
			authIdAndleadsCountMap.put(auth.getId(), leads.size());
708
		}
709
 
710
		Map<Integer, Object> authIdAndallValues = new LinkedHashMap<>();
711
 
712
		for (Position po : pos) {
713
 
714
			double totallmtdAmount = 0;
715
			double totalmtdAmount = 0;
716
			int totalTicketCount = 0;
717
			float totalTodayInvestment = 0;
718
			float totalStockInInvestment = 0;
719
			double currentMonthRatingAllPartners = 0;
720
 
721
			AuthUser auth = authRepository.selectById(po.getAuthUserId());
722
 
723
			List<Integer> fofoIds = pp.get(po.getAuthUserId());
724
 
725
			for (Integer fId : fofoIds) {
726
				Map<String, Object> investmentMap = this.getInvestments(fId);
727
 
728
				double currentMonthRating = hygieneDataRepository.selectRatingAvg(fId,
729
						curDate.withDayOfMonth(1).minusMonths(1), curDate.plusMonths(1).withDayOfMonth(1));
730
 
731
				currentMonthRatingAllPartners += currentMonthRating;
732
 
733
				fofoIds.size();
734
 
735
				Double lmtdAmount = lmtdSale.get(fId);
736
				Double mtdAmount = mtdSale.get(fId);
737
				Long ticketCount = ticketMap.get(fId);
738
 
739
				if (!investmentMap.isEmpty()) {
740
					totalTodayInvestment += (float) investmentMap.get("today");
741
					totalStockInInvestment += (float) investmentMap.get("inStock");
742
 
743
				}
744
				LOGGER.info("totalTodayInvestment" + totalTodayInvestment);
745
				LOGGER.info("totalStockInInvestment" + totalStockInInvestment);
746
				if (ticketCount != null) {
747
					totalTicketCount += ticketCount;
748
				}
749
 
750
				if (lmtdAmount != null) {
751
					totallmtdAmount += lmtdAmount;
752
				}
753
 
754
				if (mtdAmount != null) {
755
					totalmtdAmount += mtdAmount;
756
				}
757
 
758
			}
759
			LOGGER.info("currentMonthRatingAllPartners" + currentMonthRatingAllPartners);
760
			LOGGER.info("size" + fofoIds.size());
761
			double totalHygieneRating = currentMonthRatingAllPartners / fofoIds.size();
762
 
763
			LOGGER.info("totalHygieneRating" + totalHygieneRating);
764
 
765
			PartnerDetailModel pm = new PartnerDetailModel();
766
			pm.setLmtd(totallmtdAmount);
767
			pm.setMtd(totalmtdAmount);
768
			pm.setLeads(authIdAndleadsCountMap.get(po.getAuthUserId()));
769
			pm.setInvestment(totalTodayInvestment);
770
			pm.setStockInInvestment(totalStockInInvestment);
771
			pm.setTicket(totalTicketCount);
772
			pm.setHygiene((double) Math.round(totalHygieneRating));
773
			authIdAndallValues.put(auth.getId(), pm);
774
 
775
		}
776
		return authIdAndallValues;
777
	}
778
 
779
	private Map<String, Object> getInvestments(int fofoId) throws Exception {
780
		Map<String, Object> investments = new LinkedHashMap<>();
781
 
782
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
783
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
784
		LocalDate yesterDate = LocalDate.now().minusDays(1);
785
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
786
		if (yesterdayInvestment == null) {
787
			yesterdayInvestment = new PartnerDailyInvestment();
788
		}
789
 
790
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
791
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
792
 
793
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
794
				.collect(Collectors.counting());
795
		investments.put("today", investment.getTotalInvestment());
796
		investments.put("investment", investment);
797
		investments.put("inStock", investment.getInStockAmount());
798
		investments.put("minimum", investment.getMinInvestmentString());
799
		investments.put("short", investment.getShortPercentage());
800
		investments.put("activated_stock", investment.getActivatedStockAmount());
801
		investments.put("okDays", okInvestmentDays);
802
 
803
		return investments;
804
	}
24383 amit.gupta 805
}