Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21615 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
25651 tejbeer 3
import java.io.File;
4
import java.io.FileInputStream;
5
import java.io.FileNotFoundException;
27628 tejbeer 6
import java.io.FileOutputStream;
7
import java.io.ObjectInputStream;
8
import java.io.ObjectOutputStream;
24288 amit.gupta 9
import java.time.LocalDate;
24276 amit.gupta 10
import java.time.LocalDateTime;
24880 govind 11
import java.time.LocalTime;
27555 tejbeer 12
import java.time.YearMonth;
25649 tejbeer 13
import java.time.ZoneOffset;
27474 tejbeer 14
import java.time.format.DateTimeFormatter;
24339 amit.gupta 15
import java.util.ArrayList;
26027 amit.gupta 16
import java.util.Arrays;
27701 tejbeer 17
import java.util.Comparator;
26011 amit.gupta 18
import java.util.HashMap;
26090 amit.gupta 19
import java.util.HashSet;
25136 amit.gupta 20
import java.util.LinkedHashMap;
23884 amit.gupta 21
import java.util.List;
24880 govind 22
import java.util.Map;
26055 tejbeer 23
import java.util.Map.Entry;
26071 tejbeer 24
import java.util.Optional;
26090 amit.gupta 25
import java.util.Set;
24880 govind 26
import java.util.stream.Collectors;
23568 govind 27
 
22086 amit.gupta 28
import javax.servlet.http.HttpServletRequest;
25221 amit.gupta 29
import javax.transaction.Transactional;
22086 amit.gupta 30
 
23786 amit.gupta 31
import org.apache.logging.log4j.LogManager;
23568 govind 32
import org.apache.logging.log4j.Logger;
26158 amit.gupta 33
import org.json.JSONObject;
22481 ashik.ali 34
import org.springframework.beans.factory.annotation.Autowired;
23379 ashik.ali 35
import org.springframework.beans.factory.annotation.Value;
25651 tejbeer 36
import org.springframework.core.io.InputStreamResource;
37
import org.springframework.http.HttpHeaders;
38
import org.springframework.http.HttpStatus;
25649 tejbeer 39
import org.springframework.http.ResponseEntity;
21615 kshitij.so 40
import org.springframework.stereotype.Controller;
22073 ashik.ali 41
import org.springframework.ui.Model;
21615 kshitij.so 42
import org.springframework.web.bind.annotation.RequestMapping;
43
import org.springframework.web.bind.annotation.RequestMethod;
25649 tejbeer 44
import org.springframework.web.bind.annotation.RequestParam;
21615 kshitij.so 45
 
25649 tejbeer 46
import com.google.gson.Gson;
25677 amit.gupta 47
import com.mongodb.DBObject;
25651 tejbeer 48
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 49
import com.spice.profitmandi.common.enumuration.MessageType;
26065 amit.gupta 50
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22481 ashik.ali 51
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27636 tejbeer 52
import com.spice.profitmandi.common.model.ActivateItemModel;
27884 tejbeer 53
import com.spice.profitmandi.common.model.Axis;
25677 amit.gupta 54
import com.spice.profitmandi.common.model.BrandStockPrice;
27884 tejbeer 55
import com.spice.profitmandi.common.model.ChartInvestmentModel;
26055 tejbeer 56
import com.spice.profitmandi.common.model.ChartModel;
26005 amit.gupta 57
import com.spice.profitmandi.common.model.CustomRetailer;
27884 tejbeer 58
import com.spice.profitmandi.common.model.Data;
59
import com.spice.profitmandi.common.model.DataInvestmentModel;
26055 tejbeer 60
import com.spice.profitmandi.common.model.DataModel;
61
import com.spice.profitmandi.common.model.DatasetModel;
27884 tejbeer 62
import com.spice.profitmandi.common.model.Legend;
26055 tejbeer 63
import com.spice.profitmandi.common.model.LegendModel;
27902 tejbeer 64
 
25649 tejbeer 65
import com.spice.profitmandi.common.model.Notification;
27884 tejbeer 66
import com.spice.profitmandi.common.model.OptionModel;
26055 tejbeer 67
import com.spice.profitmandi.common.model.OptionsModel;
27884 tejbeer 68
import com.spice.profitmandi.common.model.PieLables;
24203 amit.gupta 69
import com.spice.profitmandi.common.model.ProfitMandiConstants;
27884 tejbeer 70
import com.spice.profitmandi.common.model.ScalesModel;
26055 tejbeer 71
import com.spice.profitmandi.common.model.TitleModel;
25651 tejbeer 72
import com.spice.profitmandi.common.web.util.ResponseSender;
25649 tejbeer 73
import com.spice.profitmandi.dao.Interface.Campaign;
26011 amit.gupta 74
import com.spice.profitmandi.dao.entity.auth.AuthUser;
75
import com.spice.profitmandi.dao.entity.auth.Menu;
27355 tejbeer 76
import com.spice.profitmandi.dao.entity.catalog.Item;
27636 tejbeer 77
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26011 amit.gupta 78
import com.spice.profitmandi.dao.entity.cs.Position;
27660 tejbeer 79
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
25651 tejbeer 80
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 81
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
22654 ashik.ali 82
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
27636 tejbeer 83
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24288 amit.gupta 84
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
25214 amit.gupta 85
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
25566 tejbeer 86
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
27529 tejbeer 87
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
27586 tejbeer 88
import com.spice.profitmandi.dao.entity.transaction.Order;
26418 tejbeer 89
import com.spice.profitmandi.dao.entity.user.Lead;
26024 amit.gupta 90
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26418 tejbeer 91
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
27628 tejbeer 92
import com.spice.profitmandi.dao.model.BrandWisePartnerSaleModel;
27670 tejbeer 93
import com.spice.profitmandi.dao.model.BrandWiseUnbilledActivateStockModel;
26674 tejbeer 94
import com.spice.profitmandi.dao.model.CreateOfferRequest;
27660 tejbeer 95
import com.spice.profitmandi.dao.model.InStockBrandItemModel;
27640 tejbeer 96
import com.spice.profitmandi.dao.model.InStockBrandModel;
27579 tejbeer 97
import com.spice.profitmandi.dao.model.ItemWiseTertiaryModel;
27474 tejbeer 98
import com.spice.profitmandi.dao.model.MonthSaleModel;
26418 tejbeer 99
import com.spice.profitmandi.dao.model.PartnerDetailModel;
27599 tejbeer 100
import com.spice.profitmandi.dao.model.PartnerPendingIndentItemModel;
25649 tejbeer 101
import com.spice.profitmandi.dao.model.SimpleCampaign;
102
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
27670 tejbeer 103
import com.spice.profitmandi.dao.model.WarehouseBrandItemUnbilledActivatedModel;
27556 tejbeer 104
import com.spice.profitmandi.dao.model.WarehouseBrandWiseItemSaleModel;
27628 tejbeer 105
import com.spice.profitmandi.dao.model.WarehouseWiseBrandSaleModel;
27591 tejbeer 106
import com.spice.profitmandi.dao.model.WarehouseWiseBrandStockModel;
27670 tejbeer 107
import com.spice.profitmandi.dao.model.WarehouseWiseBrandUnbilledActivatedModel;
27509 tejbeer 108
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
109
import com.spice.profitmandi.dao.model.WarehouseWiseitemStockModel;
25976 amit.gupta 110
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
26011 amit.gupta 111
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
112
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
27355 tejbeer 113
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
26588 tejbeer 114
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
115
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
116
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
27632 tejbeer 117
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
26090 amit.gupta 118
import com.spice.profitmandi.dao.repository.cs.CsService;
26418 tejbeer 119
import com.spice.profitmandi.dao.repository.cs.PartnersPositionRepository;
26011 amit.gupta 120
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
27660 tejbeer 121
import com.spice.profitmandi.dao.repository.cs.TicketAssignedRepository;
26011 amit.gupta 122
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
26418 tejbeer 123
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
25651 tejbeer 124
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
22481 ashik.ali 125
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
26418 tejbeer 126
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
24996 amit.gupta 127
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25649 tejbeer 128
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
129
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
130
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
24203 amit.gupta 131
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24880 govind 132
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
26071 tejbeer 133
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
25649 tejbeer 134
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
26234 amit.gupta 135
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24288 amit.gupta 136
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
25214 amit.gupta 137
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
27474 tejbeer 138
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
25566 tejbeer 139
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
27529 tejbeer 140
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
141
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
27509 tejbeer 142
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
27893 tejbeer 143
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
24336 amit.gupta 144
import com.spice.profitmandi.service.PartnerInvestmentService;
26460 amit.gupta 145
import com.spice.profitmandi.service.PartnerStatsService;
23844 amit.gupta 146
import com.spice.profitmandi.service.authentication.RoleManager;
25677 amit.gupta 147
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 148
import com.spice.profitmandi.service.offers.OfferService;
27586 tejbeer 149
import com.spice.profitmandi.service.transaction.TransactionService;
26005 amit.gupta 150
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 151
import com.spice.profitmandi.web.model.LoginDetails;
152
import com.spice.profitmandi.web.util.CookiesProcessor;
27529 tejbeer 153
import com.spice.profitmandi.web.util.MVCResponseSender;
22481 ashik.ali 154
 
21615 kshitij.so 155
@Controller
25222 amit.gupta 156
@Transactional(rollbackOn = Throwable.class)
21615 kshitij.so 157
public class DashboardController {
23923 amit.gupta 158
 
26460 amit.gupta 159
	private static final double ONE_LAC = 1 * 1000 * 100;
160
	private static final double TWO_LAC = 2 * 1000 * 100;
161
	private static final double FOUR_LAC = 4 * 1000 * 100;
162
 
27727 tejbeer 163
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
27778 tejbeer 164
			"niranjan.kala@smartdukaan.com", "hemant.kaura@smartdukaan.com", "amit.gupta@shop2020.in",
165
			"tejbeer.kaur@shop2020.in");
27727 tejbeer 166
 
23379 ashik.ali 167
	@Value("${web.api.host}")
168
	private String webApiHost;
23923 amit.gupta 169
 
24072 amit.gupta 170
	@Value("${web.api.scheme}")
171
	private String webApiScheme;
24288 amit.gupta 172
 
24078 amit.gupta 173
	@Value("${web.api.root}")
174
	private String webApiRoot;
175
 
23379 ashik.ali 176
	@Value("${web.api.port}")
177
	private int webApiPort;
21615 kshitij.so 178
 
22481 ashik.ali 179
	@Autowired
22927 ashik.ali 180
	private CookiesProcessor cookiesProcessor;
26468 amit.gupta 181
 
26460 amit.gupta 182
	@Autowired
183
	private PartnerStatsService partnerStatsService;
23923 amit.gupta 184
 
23568 govind 185
	@Autowired
26011 amit.gupta 186
	private MenuRepository menuRepository;
26012 amit.gupta 187
 
26011 amit.gupta 188
	@Autowired
189
	private MenuCategoryRepository menuCategoryRepository;
190
 
191
	@Autowired
26090 amit.gupta 192
	private CsService csService;
193
 
194
	@Autowired
25214 amit.gupta 195
	private PartnerTargetRepository partnerTargetRepository;
196
 
197
	@Autowired
25653 amit.gupta 198
	private ResponseSender<?> responseSender;
26012 amit.gupta 199
 
26005 amit.gupta 200
	@Autowired
201
	RetailerService retailerService;
25214 amit.gupta 202
 
203
	@Autowired
23786 amit.gupta 204
	private RoleManager roleManager;
23923 amit.gupta 205
 
23838 ashik.ali 206
	@Autowired
207
	private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 208
 
209
	@Autowired
24880 govind 210
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
23923 amit.gupta 211
 
23884 amit.gupta 212
	@Autowired
24880 govind 213
	private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 214
 
23884 amit.gupta 215
	@Autowired
25653 amit.gupta 216
	DocumentRepository documentRepository;
26236 amit.gupta 217
 
26234 amit.gupta 218
	@Autowired
219
	InventoryItemRepository inventoryItemRepository;
25683 tejbeer 220
 
25677 amit.gupta 221
	@Autowired
222
	InventoryService inventoryService;
23923 amit.gupta 223
 
23884 amit.gupta 224
	@Autowired
24203 amit.gupta 225
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
226
 
24880 govind 227
	@Autowired
228
	private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 229
 
26011 amit.gupta 230
	@Autowired
231
	private TicketCategoryRepository ticketCategoryRepository;
24880 govind 232
 
233
	@Autowired
25566 tejbeer 234
	private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 235
 
24996 amit.gupta 236
	@Autowired
25649 tejbeer 237
	private HygieneDataRepository hygieneDataRepository;
238
 
239
	@Autowired
240
	private UserCampaignRepository userCampaignRepository;
26012 amit.gupta 241
 
26011 amit.gupta 242
	@Autowired
243
	private PositionRepository positionRepository;
27474 tejbeer 244
	@Autowired
245
	private PartnerTypeChangeRepository partnerTypeChangeRepository;
25649 tejbeer 246
 
247
	@Autowired
26418 tejbeer 248
	private PartnersPositionRepository partnerPositionRepository;
249
 
250
	@Autowired
25649 tejbeer 251
	private UserAccountRepository userAccountRepository;
252
 
253
	@Autowired
254
	private NotificationCampaignRepository notificationCampaignRepository;
255
 
256
	@Autowired
24996 amit.gupta 257
	private Mongo mongoClient;
26012 amit.gupta 258
 
25976 amit.gupta 259
	@Autowired
260
	private AuthRepository authRepository;
24880 govind 261
 
25649 tejbeer 262
	@Autowired
26071 tejbeer 263
	private FofoOrderRepository fofoOrderRepository;
264
 
265
	@Autowired
25649 tejbeer 266
	private Gson gson;
267
 
26418 tejbeer 268
	@Autowired
269
	TicketRepository ticketRepository;
270
 
271
	@Autowired
272
	private LeadRepository leadRepository;
273
 
26588 tejbeer 274
	@Autowired
275
	private OfferRepository offerRepository;
276
 
277
	@Autowired
278
	private OfferPartnerRepository offerPartnerRepository;
279
 
280
	@Autowired
27876 amit.gupta 281
	private OfferService offerService;
282
 
283
	@Autowired
26588 tejbeer 284
	private OfferMarginRepository offerMarginRepository;
27529 tejbeer 285
 
27355 tejbeer 286
	@Autowired
287
	private ItemRepository itemRepository;
26588 tejbeer 288
 
27509 tejbeer 289
	@Autowired
290
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
27529 tejbeer 291
 
292
	@Autowired
293
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
294
 
295
	@Autowired
296
	private MVCResponseSender mvcResponseSender;
297
 
298
	@Autowired
299
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
300
 
27586 tejbeer 301
	@Autowired
302
	private TransactionService transactionService;
303
 
27632 tejbeer 304
	@Autowired
305
	private TagListingRepository tagListingRepository;
306
 
27660 tejbeer 307
	@Autowired
308
	private TicketAssignedRepository ticketAssignedRepository;
309
 
27893 tejbeer 310
	@Autowired
311
	private OrderRepository orderRepository;
23568 govind 312
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
23923 amit.gupta 313
 
25136 amit.gupta 314
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
25726 amit.gupta 315
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
25740 amit.gupta 316
		boolean isAdmin = false;
317
		model.addAttribute("isAdmin", isAdmin);
318
 
319
		model.addAttribute("webApiHost", webApiHost);
320
		model.addAttribute("webApiPort", webApiPort);
321
		model.addAttribute("webApiScheme", webApiScheme);
322
		model.addAttribute("webApiRoot", webApiRoot);
323
		if (isAdmin) {
324
			return "dashboard1";
26236 amit.gupta 325
		}
326
 
327
		FofoStore fofoStore = null;
26234 amit.gupta 328
		try {
329
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
330
			fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
331
			if (!fofoStore.isActive()) {
332
				return "redirect:/login";
333
			}
25740 amit.gupta 334
 
26234 amit.gupta 335
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
336
			model.addAttribute("partnerType", partnerType);
337
			model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
338
			model.addAttribute("fofoStore", customRetailer);
339
			model.addAttribute("partnerType", partnerType);
340
			model.addAttribute("hasGift", hasGift(fofoId));
341
			model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
25740 amit.gupta 342
 
27884 tejbeer 343
			model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26234 amit.gupta 344
			model.addAttribute("salesMap", this.getSales(fofoId));
345
			model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
346
			// this.setInvestments
347
			//
348
			model.addAttribute("investments", this.getInvestments(fofoId));
349
			model.addAttribute("isInvestmentOk",
350
					partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
351
		} catch (ProfitMandiBusinessException e) {
352
			LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
25740 amit.gupta 353
 
354
		}
355
 
356
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
357
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
26012 amit.gupta 358
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd)
359
				/ 2;
360
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
361
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(fofoId, currentMonthStart, currentMonthEnd) / 2;
25740 amit.gupta 362
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
363
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
364
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
365
 
26012 amit.gupta 366
		long hygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, true, currentMonthStart, currentMonthEnd);
367
 
368
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(fofoId, false, currentMonthStart,
25740 amit.gupta 369
				currentMonthEnd);
370
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
371
			invalidHygieneCount = 1;
372
		}
373
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
26460 amit.gupta 374
 
25740 amit.gupta 375
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
376
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
377
		return "12dashboard34";
25136 amit.gupta 378
	}
379
 
380
	private Map<String, Object> getInvestments(int fofoId) throws Exception {
381
		Map<String, Object> investments = new LinkedHashMap<>();
26233 amit.gupta 382
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
25649 tejbeer 383
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
25136 amit.gupta 384
		LocalDate yesterDate = LocalDate.now().minusDays(1);
385
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
386
		if (yesterdayInvestment == null) {
387
			yesterdayInvestment = new PartnerDailyInvestment();
388
		}
389
 
390
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
391
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
392
 
25140 amit.gupta 393
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
25136 amit.gupta 394
				.collect(Collectors.counting());
25140 amit.gupta 395
		investments.put("today", investment.getTotalInvestment());
396
		investments.put("investment", investment);
397
		investments.put("inStock", investment.getInStockAmount());
25182 amit.gupta 398
		investments.put("minimum", investment.getMinInvestmentString());
25140 amit.gupta 399
		investments.put("short", investment.getShortPercentage());
26267 amit.gupta 400
		investments.put("activated_stock", investment.getActivatedStockAmount());
25649 tejbeer 401
		investments.put("okDays", okInvestmentDays);
25136 amit.gupta 402
		return investments;
403
	}
404
 
25221 amit.gupta 405
	private Map<String, Object> getSales(int fofoId) {
25653 amit.gupta 406
 
25221 amit.gupta 407
		Map<String, Object> salesMap = new LinkedHashMap<>();
25140 amit.gupta 408
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
25214 amit.gupta 409
		int monthLength = LocalDate.now().lengthOfMonth();
26012 amit.gupta 410
		Double todaySale = fofoOrderItemRepository
27084 amit.gupta 411
				.selectSumMopGroupByRetailer(curDate, curDate.with(LocalTime.MAX), fofoId, false).get(fofoId);
26012 amit.gupta 412
		Double mtdSale = fofoOrderItemRepository
27084 amit.gupta 413
				.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId, false)
26012 amit.gupta 414
				.get(fofoId);
27352 tejbeer 415
		Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1).minusMonths(1),
416
				curDate.with(LocalTime.MAX).minusMonths(1), fofoId, false).get(fofoId);
25214 amit.gupta 417
 
418
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
419
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
25544 amit.gupta 420
		if (partnerTargetDetails.isEmpty()) {
25372 tejbeer 421
			partnerTargetDetails = partnerTargetRepository
25653 amit.gupta 422
					.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
25372 tejbeer 423
		}
25214 amit.gupta 424
 
25653 amit.gupta 425
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
25214 amit.gupta 426
 
25664 amit.gupta 427
		int currentRate = (int) (mtdSale / curDate.getDayOfMonth());
25653 amit.gupta 428
 
429
		salesMap.put("requiredType", partnerType.next());
430
		float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
431
		int requiredRate = (int) ((reqdAmount - mtdSale) / (monthLength - curDate.getDayOfMonth()));
27859 tejbeer 432
		if (partnerType.equals(PartnerType.PLATINUM) && requiredRate < currentRate) {
433
			requiredRate = currentRate;
434
		}
25653 amit.gupta 435
		salesMap.put("requiredRate", requiredRate);
436
		salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));
437
 
25858 amit.gupta 438
		salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
439
		salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
26012 amit.gupta 440
		salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);
26065 amit.gupta 441
 
27352 tejbeer 442
		PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate * monthLength);
25653 amit.gupta 443
		salesMap.put("currentRate", currentRate);
444
		salesMap.put("currentType", currentType);
445
		salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
25136 amit.gupta 446
		return salesMap;
447
	}
448
 
27474 tejbeer 449
	@RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
450
	public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
451
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
452
		int fofoId = loginDetails.getFofoId();
453
		Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
454
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
455
		int dayOfMonth = curDate.getDayOfMonth();
456
		for (int i = 1; i <= 6; i++) {
457
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
27555 tejbeer 458
			int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
27474 tejbeer 459
			double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
460
					startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
461
 
27574 tejbeer 462
			double mtdSales = fofoOrderItemRepository
463
					.selectSumMopGroupByRetailer(startOfMonth,
464
							startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false)
465
					.get(fofoId);
27474 tejbeer 466
 
467
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
468
 
469
			MonthSaleModel ms = new MonthSaleModel();
470
			ms.setMtdSales(this.format((long) mtdSales));
471
			ms.setMonthlySales(this.format(((long) monthSales)));
472
			ms.setPartnerType(partnerType);
27476 tejbeer 473
			ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
27474 tejbeer 474
			monthSaleMap.put(i, ms);
475
 
476
		}
477
		model.addAttribute("monthSales", monthSaleMap);
478
		return "monthSales";
479
	}
480
 
481
	private String format(long value) {
482
		String finalval = null;
483
 
484
		if (value >= 100000 && value < 10000000) {
485
			long reminder = value / 100000;
486
			long quitonent = value % 100000;
487
			finalval = reminder + "." + quitonent;
488
			String secondval = String.valueOf(quitonent);
489
			if (secondval.length() >= 2) {
490
				secondval = secondval.substring(0, 2);
491
				finalval = reminder + "." + secondval;
492
			}
493
			return String.valueOf(finalval) + " Lacs";
494
		} else if (value >= 1000 && value < 100000) {
495
			long reminder = value / 1000;
496
			long quitonent = value % 1000;
497
			finalval = reminder + "." + quitonent;
498
			String secondval = String.valueOf(quitonent);
499
			if (secondval.length() >= 2) {
500
				secondval = secondval.substring(0, 2);
501
				finalval = reminder + "." + secondval;
502
			}
503
			return String.valueOf(finalval) + " K";
504
		} else if (value >= 10000000 && value < 1000000000) {
505
			long reminder = value / 10000000;
506
			long quitonent = value % 10000000;
507
			finalval = reminder + "." + quitonent;
508
			String secondval = String.valueOf(quitonent);
509
			if (secondval.length() >= 2) {
510
				secondval = secondval.substring(0, 2);
511
				finalval = reminder + "." + secondval;
512
			}
513
			return String.valueOf(finalval) + " Cr";
514
		}
515
		return String.valueOf(finalval);
516
 
517
	}
518
 
27702 tejbeer 519
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
520
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25175 amit.gupta 521
 
27702 tejbeer 522
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
523
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
524
 
525
		mobileBrands.stream().forEach(x -> {
526
			String brand = (String) x.get("name");
527
			if (brandStockPricesMap.containsKey(brand)) {
528
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
529
				brandStockPrice.setBrandUrl((String) x.get("url"));
530
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
531
				brandStockPrices.add(brandStockPrice);
532
			}
533
		});
534
 
535
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
536
				.collect(Collectors.toList());
537
	}
538
 
21615 kshitij.so 539
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 540
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 541
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 542
		String email = loginDetails.getEmailId();
25180 amit.gupta 543
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
544
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 545
 
25274 amit.gupta 546
		model.addAttribute("webApiHost", webApiHost);
547
		model.addAttribute("webApiPort", webApiPort);
548
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 549
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 550
		if (isAdmin) {
26011 amit.gupta 551
			return adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 552
		} else {
25740 amit.gupta 553
			FofoStore fofoStore = null;
25180 amit.gupta 554
			try {
555
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 556
				if (!fofoStore.isActive()) {
557
					return "redirect:/login";
558
				}
25649 tejbeer 559
 
25740 amit.gupta 560
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 561
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 562
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 563
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 564
				model.addAttribute("partnerType", partnerType);
25180 amit.gupta 565
				model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
566
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26222 tejbeer 567
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
26162 amit.gupta 568
						.append("partnerId", fofoStore.getId()).toString());
26460 amit.gupta 569
				model.addAttribute("activatedImeis",
570
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
26071 tejbeer 571
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
572
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
573
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
574
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27701 tejbeer 575
 
26071 tejbeer 576
				Double accesoriesStock = currentInventorySnapshotRepository
577
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
578
								Optional.of(false))
579
						.get(loginDetails.getFofoId());
25180 amit.gupta 580
 
26071 tejbeer 581
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
27702 tejbeer 582
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
25180 amit.gupta 583
				model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
26055 tejbeer 584
				ChartModel cm = this.getBrandChart(loginDetails.getFofoId());
585
 
586
				LOGGER.info("chartMap" + gson.toJson(cm));
587
				model.addAttribute("chartMap", gson.toJson(cm));
27701 tejbeer 588
 
27876 amit.gupta 589
				List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(),
590
						YearMonth.from(LocalDateTime.now()));
591
				model.addAttribute("publishedOffers", publishedOffers);
25180 amit.gupta 592
				model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 593
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
594
						10, ProfitMandiConstants.CUTOFF_INVESTMENT));
26460 amit.gupta 595
 
25180 amit.gupta 596
			} catch (ProfitMandiBusinessException e) {
597
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
598
 
599
			}
22481 ashik.ali 600
		}
25649 tejbeer 601
 
602
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 603
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 604
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
605
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 606
				currentMonthEnd) / 2;
25747 amit.gupta 607
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
608
				currentMonthStart) / 2;
609
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 610
				currentMonthEnd) / 2;
611
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
612
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
613
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 614
 
25653 amit.gupta 615
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
616
				currentMonthEnd);
25651 tejbeer 617
 
25653 amit.gupta 618
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
619
				currentMonthStart, currentMonthEnd);
620
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
621
			invalidHygieneCount = 1;
622
		}
623
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 624
 
25197 amit.gupta 625
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
626
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
27884 tejbeer 627
		/*
628
		 * if (loginDetails.isReadOnly()) { return "dashboard-readonly"; } else { }
629
		 */
27882 amit.gupta 630
		return "dashboard1";
21615 kshitij.so 631
	}
23923 amit.gupta 632
 
27884 tejbeer 633
	@RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
634
	public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
635
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
636
		int fofoId = loginDetails.getFofoId();
637
		ChartInvestmentModel cm = this.getInvestmentChart(fofoId);
638
		model.addAttribute("chartPieMap", gson.toJson(cm));
639
 
640
		LOGGER.info("InvestmentChart" + gson.toJson(cm));
641
		LOGGER.info("InvestmentChart" + cm);
642
		return "investmentdetails";
643
	}
644
 
645
	private ChartInvestmentModel getInvestmentChart(int fofoId) throws ProfitMandiBusinessException {
646
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
27900 tejbeer 647
 
27884 tejbeer 648
		Map<String, Float> investmentWalletAmount = new HashMap<>();
649
		investmentWalletAmount.put("Wallet", investment.getWalletAmount());
650
		investmentWalletAmount.put("InStock", investment.getInStockAmount());
27900 tejbeer 651
		investmentWalletAmount.put("Unbilled Order", investment.getUnbilledAmount());
27884 tejbeer 652
		investmentWalletAmount.put("GrnPending", investment.getGrnPendingAmount());
653
		investmentWalletAmount.put("ReturnInTransit", investment.getReturnInTransitAmount());
654
 
27900 tejbeer 655
		if (investment.getShortInvestment() > 0) {
656
			investmentWalletAmount.put("Short Investment", investment.getShortInvestment());
657
		}
658
 
27884 tejbeer 659
		ChartInvestmentModel cm = new ChartInvestmentModel();
660
 
661
		HashSet<String> labels = new HashSet<String>();
662
		labels.addAll(investmentWalletAmount.keySet());
663
 
664
		List<String> labelList = new ArrayList<>(labels);
665
		List<String> backgroundColor = new ArrayList<>();
27900 tejbeer 666
		List<Float> labelsValue = new ArrayList<>();
27884 tejbeer 667
		List<Float> values = new ArrayList<>();
668
		for (String label : labelList) {
669
			values.add(investmentWalletAmount.get(label));
670
			if (label.equals("Wallet")) {
671
				backgroundColor.add("pink");
672
			}
27900 tejbeer 673
			if (label.equals("Short Investment")) {
674
				backgroundColor.add("red");
675
			}
27884 tejbeer 676
			if (label.equals("InStock")) {
27900 tejbeer 677
				backgroundColor.add("#9ACD32");
27884 tejbeer 678
			}
27900 tejbeer 679
			if (label.equals("Unbilled Order")) {
680
				backgroundColor.add("blue");
27884 tejbeer 681
			}
682
 
683
			if (label.equals("ReturnInTransit")) {
684
				backgroundColor.add("orange");
685
			}
686
			if (label.equals("GrnPending")) {
687
				backgroundColor.add("yellow");
688
			}
689
 
690
		}
691
 
692
		Data data = new Data();
693
		data.setData(values);
694
		data.setBackgroundColor(backgroundColor);
695
		data.setLabel("DataSet 1");
696
 
697
		PieLables label = new PieLables();
698
		label.setFontColor("White");
699
		label.setFontSize(15);
700
 
701
		Legend legend = new Legend();
702
		legend.setLabels(label);
703
		legend.setPosition("left");
704
 
705
		List<Data> dataList = new ArrayList<>();
706
		dataList.add(data);
707
 
708
		DataInvestmentModel datasets = new DataInvestmentModel();
709
		datasets.setDatasets(dataList);
710
		datasets.setLabels(labels);
711
 
712
		OptionModel om = new OptionModel();
713
		om.setLegend(legend);
714
		cm.setType("pie");
715
		cm.setData(datasets);
716
		cm.setOptions(om);
717
 
718
		return cm;
719
	}
720
 
26055 tejbeer 721
	private ChartModel getBrandChart(int fofoId) {
722
 
723
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
724
 
725
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
726
 
727
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
728
 
27900 tejbeer 729
		Map<String, Double> brandwisesale = fofoOrderItemRepository
26055 tejbeer 730
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 731
 
27900 tejbeer 732
		LOGGER.info("brandwisesale" + brandwisesale);
27884 tejbeer 733
 
26244 tejbeer 734
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
735
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27900 tejbeer 736
		brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
27884 tejbeer 737
		Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
738
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
739
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
27900 tejbeer 740
 
27884 tejbeer 741
		Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
742
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
743
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
744
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26244 tejbeer 745
 
26055 tejbeer 746
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
747
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
748
 
26244 tejbeer 749
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
750
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
751
				Optional.of(false));
27884 tejbeer 752
 
753
		lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));
754
 
26055 tejbeer 755
		ChartModel cm = new ChartModel();
756
 
27884 tejbeer 757
		HashSet<String> labels = new HashSet<String>();
27900 tejbeer 758
		labels.addAll(brandwisesale.keySet());
27876 amit.gupta 759
		labels.addAll(lmtdBrandWiseSale.keySet());
26055 tejbeer 760
 
27884 tejbeer 761
		List<String> labelList = new ArrayList<>(labels);
762
 
763
		List<Double> mtdActivatedImeisValues = new ArrayList<>();
764
 
765
		List<Double> mtdValues = new ArrayList<>();
766
		List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
767
		List<Double> lmtdActivatedImeisValues = new ArrayList<>();
768
		List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
26055 tejbeer 769
		List<Double> lmtdValues = new ArrayList<>();
27884 tejbeer 770
		for (String label : labelList) {
771
			mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
772
					: activatedImeisWithSellingPriceMTD.get(label));
773
			lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
774
					: activatedImeisWithSellingPriceLMTD.get(label));
26055 tejbeer 775
 
27900 tejbeer 776
			mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
777
			if (brandwisesale.get(label) != null) {
27884 tejbeer 778
				mtdUnActivatedImeisValues
27900 tejbeer 779
						.add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
27884 tejbeer 780
								: activatedImeisWithSellingPriceMTD.get(label)));
781
			} else {
782
				mtdUnActivatedImeisValues.add(0.0);
783
			}
784
			if (lmtdBrandWiseSale.get(label) != null) {
785
				lmtdUnActivatedImeisValues
786
						.add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
787
								: activatedImeisWithSellingPriceLMTD.get(label)));
788
			} else {
789
				lmtdUnActivatedImeisValues.add(0.0);
790
			}
26055 tejbeer 791
 
27884 tejbeer 792
			lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
793
		}
794
		DatasetModel dsmtotal = new DatasetModel();
795
		dsmtotal.setLabel("MTD");
796
		dsmtotal.setBackgroundColor("blue");
797
		dsmtotal.setData(mtdValues);
798
		dsmtotal.setStack("stack0");
27900 tejbeer 799
		dsmtotal.setOrder(1);
26055 tejbeer 800
 
27884 tejbeer 801
		DatasetModel dsmUnactivated = new DatasetModel();
802
		dsmUnactivated.setLabel("MTD Unactivated");
803
		dsmUnactivated.setBackgroundColor("red");
804
		dsmUnactivated.setData(mtdUnActivatedImeisValues);
805
		dsmUnactivated.setStack("stack0");
27900 tejbeer 806
		dsmUnactivated.setOrder(1);
27884 tejbeer 807
 
808
		LOGGER.info("mtdValuesMoney" + mtdValues);
809
 
810
		DatasetModel mtdActivatedImeis = new DatasetModel();
811
		mtdActivatedImeis.setLabel("MTD Activation");
812
		mtdActivatedImeis.setData(mtdActivatedImeisValues);
27913 tejbeer 813
		mtdActivatedImeis.setBackgroundColor("#00008b");
27884 tejbeer 814
		mtdActivatedImeis.setStack("stack0");
27900 tejbeer 815
		mtdActivatedImeis.setOrder(1);
27884 tejbeer 816
 
817
		DatasetModel lmtddsmtotal = new DatasetModel();
818
		lmtddsmtotal.setLabel("LMTD");
819
		lmtddsmtotal.setBackgroundColor("blue");
820
		lmtddsmtotal.setData(lmtdValues);
821
		lmtddsmtotal.setStack("stack1");
27900 tejbeer 822
		lmtddsmtotal.setOrder(1);
27884 tejbeer 823
 
824
		DatasetModel lmtdUnActivated = new DatasetModel();
825
		lmtdUnActivated.setLabel("LMTD Unactivation");
826
		lmtdUnActivated.setBackgroundColor("red");
827
		lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
828
		lmtdUnActivated.setStack("stack1");
27900 tejbeer 829
		lmtdUnActivated.setOrder(1);
27906 tejbeer 830
 
27884 tejbeer 831
 
832
		DatasetModel LmtdActivatedImeis = new DatasetModel();
833
		LmtdActivatedImeis.setLabel("LMTD Activation");
27910 tejbeer 834
		LmtdActivatedImeis.setBackgroundColor("#87ceeb");
27884 tejbeer 835
		LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
836
		LmtdActivatedImeis.setStack("stack1");
27900 tejbeer 837
		LmtdActivatedImeis.setOrder(1);
838
 
839
 
840
		DatasetModel linemtdChart = new DatasetModel();
841
		linemtdChart.setLabel("MTD");
27915 tejbeer 842
		linemtdChart.setBackgroundColor("#006400");
27900 tejbeer 843
		linemtdChart.setData(mtdValues);
844
		linemtdChart.setType("line");
845
		linemtdChart.setOrder(2);
27910 tejbeer 846
		linemtdChart.setFill("false");
27900 tejbeer 847
 
848
		DatasetModel lineLmtdChart = new DatasetModel();
849
		lineLmtdChart.setLabel("LMTD");
27915 tejbeer 850
		lineLmtdChart.setBackgroundColor("#006400");
27900 tejbeer 851
		lineLmtdChart.setData(lmtdValues);
852
		lineLmtdChart.setType("line");
27910 tejbeer 853
		lineLmtdChart.setOrder(3);
854
		lineLmtdChart.setFill("false");
27900 tejbeer 855
 
27884 tejbeer 856
 
26055 tejbeer 857
		List<DatasetModel> datasets = new ArrayList<>();
27910 tejbeer 858
		datasets.add(lmtdUnActivated);
859
		datasets.add(LmtdActivatedImeis);
27884 tejbeer 860
		datasets.add(dsmUnactivated);
861
		datasets.add(mtdActivatedImeis);
862
 
27900 tejbeer 863
		datasets.add(linemtdChart);
864
		datasets.add(lineLmtdChart);
27884 tejbeer 865
 
26055 tejbeer 866
		DataModel dm = new DataModel();
867
		dm.setDatasets(datasets);
868
		dm.setLabels(labels);
869
 
870
		LegendModel lm = new LegendModel();
27703 amit.gupta 871
		lm.setPosition("top");
26055 tejbeer 872
 
873
		TitleModel tm = new TitleModel();
27703 amit.gupta 874
		tm.setText("Brand Wise Sales");
26055 tejbeer 875
		tm.setDisplay(true);
876
 
27884 tejbeer 877
		List<Axis> xAxes = new ArrayList<>();
878
		Axis xAxis = new Axis();
879
		xAxis.setStacked(true);
880
		xAxes.add(xAxis);
881
 
882
		List<Axis> yAxes = new ArrayList<>();
883
		Axis yAxis = new Axis();
27910 tejbeer 884
		yAxis.setStacked(false);
27884 tejbeer 885
		yAxes.add(yAxis);
886
 
887
		ScalesModel sm = new ScalesModel();
888
		sm.setxAxes(xAxes);
27910 tejbeer 889
 
27884 tejbeer 890
 
26055 tejbeer 891
		OptionsModel om = new OptionsModel();
892
		om.setLegend(lm);
893
		om.setTitle(tm);
27884 tejbeer 894
		om.setScales(sm);
26055 tejbeer 895
 
896
		cm.setType("bar");
897
		cm.setData(dm);
898
		cm.setOptions(om);
899
 
27884 tejbeer 900
		LOGGER.info("cm" + cm);
901
 
26055 tejbeer 902
		return cm;
903
 
904
	}
905
 
26418 tejbeer 906
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 907
		List<Menu> menus = null;
26011 amit.gupta 908
		try {
909
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
910
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 911
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 912
			ReporticoCacheTable rctSaholic = null;
913
			ReporticoCacheTable rctPartneStat = null;
914
 
27509 tejbeer 915
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 916
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
917
 
27509 tejbeer 918
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 919
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 920
 
27670 tejbeer 921
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 922
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 923
 
27819 tejbeer 924
			Map<AuthUser, Long> authUserTicketCount = null;
925
 
27539 tejbeer 926
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
927
				wm.put(entry.getKey(), entry.getValue());
928
			}
929
 
930
			wm.put(0, "Total Values");
931
			long stockValue = 0;
932
			long stockQty = 0;
933
			long pendingIndent = 0;
27542 tejbeer 934
			long tertiary = 0;
26418 tejbeer 935
 
27701 tejbeer 936
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 937
 
27701 tejbeer 938
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 939
			if (emails.contains(authUser.getEmailId())) {
940
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
941
			}
27556 tejbeer 942
 
27701 tejbeer 943
			LOGGER.info("fofoIds" + fofoIds);
27352 tejbeer 944
 
27701 tejbeer 945
			if (fofoIds != null) {
27539 tejbeer 946
 
27701 tejbeer 947
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
948
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
949
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
950
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
951
				// warehouseStock
952
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
953
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
954
 
955
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
956
 
957
				if (!warehouseStockMap.isEmpty()) {
958
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
959
						stockValue += warehouseStock.getValue().getStockValue();
960
						stockQty += warehouseStock.getValue().getStockQty();
961
						pendingIndent += warehouseStock.getValue().getPendingIndent();
962
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 963
					}
27701 tejbeer 964
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
965
					ws.setStockQty(stockQty);
966
					ws.setStockValue(stockValue);
967
					ws.setPendingIndent(pendingIndent);
968
					ws.setTertiary(tertiary);
969
					ws.setWarehouseId(0);
970
					warehouseStockMap.put(0, ws);
27591 tejbeer 971
 
27701 tejbeer 972
				}
27670 tejbeer 973
 
27701 tejbeer 974
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
975
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 976
 
27701 tejbeer 977
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
978
 
979
				// warehouseStock
980
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
981
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
982
 
983
				partnersBrandSaleMap = fofoStoreRepository
984
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
985
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
986
 
987
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
988
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
989
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
990
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
991
					if (bpt != null) {
992
						bpt.setAmtd(un.getUnbilledMtd());
993
						bpt.setUamtdQty(un.getUnbilledMTDQty());
994
					} else {
995
						bpt = new BrandWisePartnerSaleModel();
996
						bpt.setBrand(un.getBrand());
997
						bpt.setAmtd(un.getUnbilledMtd());
998
						bpt.setUamtdQty(un.getUnbilledMTDQty());
999
						bpt.setLms(0);
1000
						bpt.setLmtd(0);
1001
						bpt.setMtd(0);
1002
						bpt.setMtdQty(0);
1003
						bpt.setLmtd(0);
1004
						bpt.setLmtdQty(0);
1005
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 1006
					}
26418 tejbeer 1007
				}
27701 tejbeer 1008
				accessoriesBrandSales = fofoStoreRepository
1009
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
1010
 
26418 tejbeer 1011
			}
1012
 
27819 tejbeer 1013
			if (positions.size() > 0) {
1014
				if (positions.stream()
1015
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1016
								|| x.getEscalationType().equals(EscalationType.L4)
1017
								|| x.getEscalationType().equals(EscalationType.L5))
1018
						.count() > 0) {
1019
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1020
				}
1021
			}
1022
 
27415 tejbeer 1023
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
27701 tejbeer 1024
					.contains(email))
1025
 
1026
			{
26029 amit.gupta 1027
				menus = menuRepository.selectAll();
1028
			} else if (positions.size() > 0) {
27108 amit.gupta 1029
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1030
					menus = menuRepository.selectAll();
27893 tejbeer 1031
				} else {
1032
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1033
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1034
					if (menuIds.size() > 0) {
1035
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1036
					}
26022 amit.gupta 1037
				}
26090 amit.gupta 1038
				List<Position> salesPositions = positions.stream()
1039
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1040
						.collect(Collectors.toList());
1041
				if (salesPositions.size() > 0) {
1042
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 1043
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 1044
						positionRetailers.addAll(customRetailers);
1045
					});
1046
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1047
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 1048
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 1049
				}
26114 amit.gupta 1050
				List<Position> warehousePositions = positions.stream()
1051
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1052
						.collect(Collectors.toList());
1053
				if (warehousePositions.size() > 0) {
1054
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 1055
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 1056
						positionRetailers.addAll(customRetailers);
1057
					});
1058
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1059
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 1060
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 1061
				}
26142 amit.gupta 1062
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1063
 
26022 amit.gupta 1064
			}
27628 tejbeer 1065
			model.addAttribute("rctPartneStat", rctPartneStat);
1066
 
1067
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1068
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1069
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1070
 
1071
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1072
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1073
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1074
 
27594 tejbeer 1075
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1076
 
26012 amit.gupta 1077
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1078
		}
26028 amit.gupta 1079
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1080
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1081
		model.addAttribute("menu", menuList);
26012 amit.gupta 1082
		return "admin";
1083
	}
1084
 
26468 amit.gupta 1085
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1086
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1087
			throws Exception {
1088
 
1089
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1090
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1091
 
26468 amit.gupta 1092
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1093
		if (authId != 0) {
1094
			List<Integer> fofoIds = pp.get(authId);
1095
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1096
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1097
		} else {
26418 tejbeer 1098
		}
1099
 
1100
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1101
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1102
 
1103
		return "auth_user_partner_detail";
26468 amit.gupta 1104
	}
26418 tejbeer 1105
 
27545 tejbeer 1106
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1107
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1108
			throws Exception {
27701 tejbeer 1109
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1110
		String email = loginDetails.getEmailId();
1111
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1112
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1113
 
27701 tejbeer 1114
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1115
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1116
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1117
 
27545 tejbeer 1118
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1119
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1120
		if (warehouseId != 0) {
27701 tejbeer 1121
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1122
			/*
1123
			 * List<Integer> fofoIds =
1124
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1125
			 * .map(x -> x.getId()).collect(Collectors.toList());
1126
			 */
27545 tejbeer 1127
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1128
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1129
		} else {
27701 tejbeer 1130
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1131
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1132
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1133
		}
1134
 
1135
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1136
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1137
 
1138
		return "auth_user_partner_detail";
1139
	}
1140
 
27509 tejbeer 1141
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1142
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1143
			@RequestParam List<Integer> warehouseId) throws Exception {
1144
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1145
		String email = loginDetails.getEmailId();
1146
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1147
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1148
 
27701 tejbeer 1149
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1150
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1151
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1152
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1153
		if (!warehouseId.contains(0)) {
1154
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1155
		} else {
1156
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1157
			warehouseWiseBrandStock = saholicInventoryCISRepository
1158
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1159
 
1160
		}
27542 tejbeer 1161
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1162
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1163
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1164
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1165
 
27509 tejbeer 1166
		return "warehouse_brand_stock";
1167
	}
1168
 
27529 tejbeer 1169
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1170
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1171
		inventoryService.getItemAvailabilityAndIndent();
1172
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1173
		return "response";
1174
	}
1175
 
27701 tejbeer 1176
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1177
			throws Exception {
27628 tejbeer 1178
 
1179
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1180
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1181
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1182
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1183
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1184
		if (partnerStats != null) {
27701 tejbeer 1185
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1186
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1187
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1188
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1189
						.collect(Collectors.toList());
27634 tejbeer 1190
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1191
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1192
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1193
				}
27628 tejbeer 1194
 
1195
			}
27701 tejbeer 1196
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1197
					.collect(Collectors.toList());
1198
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1199
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1200
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1201
			warehouseIdAndallValues.put(0, partnerDetailModel);
1202
		}
1203
		return warehouseIdAndallValues;
1204
	}
1205
 
1206
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1207
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1208
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1209
		ObjectOutputStream oos = null;
1210
		FileOutputStream fout = null;
1211
		try {
1212
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1213
			oos = new ObjectOutputStream(fout);
1214
			oos.writeObject(partnerStats);
1215
 
1216
		} catch (Exception ex) {
1217
			ex.printStackTrace();
1218
		} finally {
1219
			if (oos != null) {
1220
				oos.close();
1221
			}
1222
		}
1223
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1224
		if (rct == null) {
1225
			rct = new ReporticoCacheTable();
1226
			rct.setTableName("partnerStat");
1227
 
1228
		}
1229
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1230
		reporticoCacheTableRepository.persist(rct);
1231
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1232
		return "response";
1233
	}
1234
 
1235
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1236
		ObjectInputStream objectinputstream = null;
1237
		Map<Integer, PartnerDetailModel> partnerStat = null;
1238
		try {
1239
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1240
			objectinputstream = new ObjectInputStream(streamIn);
1241
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1242
 
1243
			LOGGER.info("partnerStat" + partnerStat);
1244
			objectinputstream.close();
1245
 
1246
		} catch (Exception e) {
1247
			LOGGER.info("exceptionddd" + e);
1248
 
1249
			e.printStackTrace();
1250
 
1251
		} finally {
1252
			if (objectinputstream != null) {
1253
				objectinputstream.close();
1254
				LOGGER.info("clofddd" + partnerStat);
1255
 
1256
			}
1257
		}
1258
		return partnerStat;
1259
 
1260
	}
1261
 
27539 tejbeer 1262
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1263
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1264
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1265
			throws Exception {
27509 tejbeer 1266
 
1267
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1268
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1269
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1270
 
27509 tejbeer 1271
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1272
		model.addAttribute("brands", listbrands);
27538 tejbeer 1273
		model.addAttribute("listCategory", listCategory);
1274
 
27529 tejbeer 1275
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1276
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1277
		model.addAttribute("selectedCategory", category);
1278
 
27509 tejbeer 1279
		return "warehouse_brand_item_stock";
1280
	}
1281
 
27538 tejbeer 1282
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1283
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1284
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1285
			throws Exception {
27539 tejbeer 1286
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1287
		if (warehouseId.contains(0)) {
1288
			warehouseId.addAll(warehouseMap.keySet());
1289
		}
27538 tejbeer 1290
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1291
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1292
 
27538 tejbeer 1293
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1294
		model.addAttribute("warehouseMap", warehouseMap);
1295
		return "warehouse_item_details";
1296
	}
1297
 
26114 amit.gupta 1298
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1299
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1300
		positionRetailers.stream().forEach(x -> {
1301
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1302
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1303
			}
1304
		});
26114 amit.gupta 1305
		return gson.toJson(warehouses);
1306
 
1307
	}
1308
 
27556 tejbeer 1309
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1310
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1311
			throws Exception {
27701 tejbeer 1312
 
1313
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1314
		String email = loginDetails.getEmailId();
1315
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1316
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1317
 
27670 tejbeer 1318
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1319
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1320
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1321
 
1322
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1323
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1324
 
1325
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1326
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1327
			if (bpt != null) {
1328
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 1329
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1330
			} else {
1331
				bpt = new WarehouseWiseBrandSaleModel();
1332
				bpt.setWarehouseId(un.getWarehouseId());
1333
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 1334
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1335
				bpt.setLms(0);
1336
				bpt.setLmtd(0);
1337
				bpt.setMtd(0);
1338
				bpt.setMtdQty(0);
1339
				bpt.setLmtd(0);
1340
				bpt.setLmtdQty(0);
1341
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1342
			}
1343
		}
27556 tejbeer 1344
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1345
 
1346
		Set<String> brands = inventoryService.getAllTagListingBrands();
1347
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1348
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1349
		model.addAttribute("brands", brands);
1350
		model.addAttribute("selectedbrand", brand);
1351
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1352
	}
1353
 
27594 tejbeer 1354
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1355
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1356
			@RequestParam String brand) throws Exception {
27701 tejbeer 1357
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1358
		String email = loginDetails.getEmailId();
1359
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1360
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1361
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1362
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1363
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1364
 
1365
		Set<String> brands = inventoryService.getAllTagListingBrands();
1366
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1367
		model.addAttribute("warehouseMap", warehouseMap);
1368
		model.addAttribute("brands", brands);
1369
		model.addAttribute("selectedbrand", brand);
1370
		return "warehousewise_accessoriesbrand_sale";
1371
	}
1372
 
27556 tejbeer 1373
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1374
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1375
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1376
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1377
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1378
		String email = loginDetails.getEmailId();
1379
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1380
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 1381
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 1382
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1383
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1384
 
1385
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 1386
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1387
 
1388
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1389
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1390
			if (bpt != null) {
1391
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 1392
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1393
			} else {
1394
				bpt = new WarehouseBrandWiseItemSaleModel();
1395
				bpt.setWarehouseId(un.getWarehouseId());
1396
				bpt.setItemId(un.getItemId());
1397
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 1398
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1399
				bpt.setBrand(un.getBrand());
1400
				bpt.setModelName(un.getModelName());
1401
				bpt.setModelNumber(un.getModelNumber());
1402
				bpt.setColor(un.getColor());
1403
				bpt.setLms(0);
1404
				bpt.setLmtd(0);
1405
				bpt.setMtd(0);
1406
				bpt.setMtdQty(0);
1407
				bpt.setLmtd(0);
1408
				bpt.setLmtdQty(0);
1409
				branditemSalesMap.put(un.getItemId(), bpt);
1410
			}
1411
		}
1412
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 1413
		model.addAttribute("warehouseMap", warehouseMap);
1414
		return "warehouse_partner_itemwise_sale";
1415
	}
1416
 
27594 tejbeer 1417
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1418
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1419
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1420
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1421
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1422
		String email = loginDetails.getEmailId();
1423
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1424
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1425
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 1426
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1427
		model.addAttribute("branditemSales", branditemSales);
1428
		model.addAttribute("warehouseMap", warehouseMap);
1429
		return "warehouse_accessories_itemwsie_sale";
1430
	}
1431
 
26012 amit.gupta 1432
	private List<Menu> prepareMenu(List<Menu> menus) {
1433
		List<Menu> returnMenu = new ArrayList<>();
1434
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1435
		for (Menu menu : menus) {
1436
			if (menu.get_parent() == null) {
26014 amit.gupta 1437
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1438
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1439
				}
1440
			} else {
26012 amit.gupta 1441
				Menu parentMenu = menu.get_parent();
1442
				if (!subMenuMap.containsKey(parentMenu)) {
1443
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1444
				}
26012 amit.gupta 1445
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1446
			}
1447
		}
26012 amit.gupta 1448
		subMenuMap.entrySet().stream().forEach(entry -> {
1449
			entry.getKey().setSubMenus(entry.getValue());
1450
			returnMenu.add(entry.getKey());
1451
		});
1452
		return returnMenu;
26005 amit.gupta 1453
	}
1454
 
24288 amit.gupta 1455
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1456
	private boolean hasGift(int fofoId) {
1457
		try {
24288 amit.gupta 1458
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1459
					.getAvailability() > 0;
24203 amit.gupta 1460
		} catch (ProfitMandiBusinessException e) {
1461
			return false;
1462
		}
1463
	}
24288 amit.gupta 1464
 
22354 ashik.ali 1465
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1466
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1467
		model.addAttribute("appContextPath", request.getContextPath());
1468
		return "contact-us";
1469
	}
23923 amit.gupta 1470
 
25649 tejbeer 1471
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1472
	public String getNotificationsWithType(HttpServletRequest request,
1473
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1474
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1475
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1476
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1477
		int userId = 0;
1478
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1479
		if (isAdmin) {
1480
			userId = loginDetails.getFofoId();
1481
		} else {
1482
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1483
		}
25683 tejbeer 1484
		List<Notification> notifications = null;
1485
 
26086 tejbeer 1486
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1487
				userId, offset, limit);
1488
		LOGGER.info("messageType" + messageType);
1489
		notifications = getNotifications(notificationCampaigns, messageType);
1490
 
25683 tejbeer 1491
		model.addAttribute("notifications", notifications);
1492
 
1493
		LOGGER.info("notifications" + notifications);
1494
		return "notification-template";
1495
	}
1496
 
1497
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1498
			throws ProfitMandiBusinessException {
1499
		List<Notification> notifications = new ArrayList<>();
1500
		Document document = null;
1501
		if (messageType != null) {
1502
			for (NotificationCampaign notificationCampaign : nc) {
1503
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1504
					Notification ns = new Notification();
1505
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1506
							SimpleCampaignParams.class);
1507
					Campaign campaign = new SimpleCampaign(scp);
1508
					LocalDateTime expire = campaign.getExpireTimestamp();
1509
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1510
					ns.setType(campaign.getType());
1511
					ns.setMessage(campaign.getMessage());
1512
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1513
					if (notificationCampaign.getDocumentId() != null) {
1514
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1515
						ns.setDocumentName(document.getDisplayName());
1516
					}
25683 tejbeer 1517
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1518
					ns.setShowImage(campaign.getShowImage());
1519
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1520
					ns.setDocumentId(notificationCampaign.getDocumentId());
1521
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1522
					ns.setCreated(
1523
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1524
									* 1000);
1525
					if (LocalDateTime.now().isAfter(expire)) {
1526
						ns.setExpired(true);
1527
					} else {
1528
						ns.setExpired(false);
1529
					}
1530
					notifications.add(ns);
1531
				}
1532
			}
25683 tejbeer 1533
		} else {
1534
			for (NotificationCampaign notificationCampaign : nc) {
1535
 
1536
				Notification ns = new Notification();
1537
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1538
						SimpleCampaignParams.class);
1539
				Campaign campaign = new SimpleCampaign(scp);
1540
				LocalDateTime expire = campaign.getExpireTimestamp();
1541
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1542
				ns.setType(campaign.getType());
1543
				ns.setMessage(campaign.getMessage());
1544
				ns.setTitle(campaign.getTitle());
1545
				if (notificationCampaign.getDocumentId() != null) {
1546
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1547
					ns.setDocumentName(document.getDisplayName());
1548
				}
1549
				ns.setUrl(campaign.getUrl());
1550
				ns.setShowImage(campaign.getShowImage());
1551
				ns.setImageUrl(campaign.getImageUrl());
1552
				ns.setDocumentId(notificationCampaign.getDocumentId());
1553
				ns.setMessageType(notificationCampaign.getMessageType());
1554
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1555
						* 1000);
1556
				if (LocalDateTime.now().isAfter(expire)) {
1557
					ns.setExpired(true);
1558
				} else {
1559
					ns.setExpired(false);
1560
				}
1561
				notifications.add(ns);
1562
			}
1563
 
25649 tejbeer 1564
		}
25683 tejbeer 1565
		return notifications;
25651 tejbeer 1566
 
1567
	}
25649 tejbeer 1568
 
25651 tejbeer 1569
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1570
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1571
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1572
			throws ProfitMandiBusinessException {
1573
		Document document = documentRepository.selectById(documentId);
1574
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1575
		if (nc.getDocumentId() == null) {
1576
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1577
		}
1578
		if (nc.getDocumentId() != documentId) {
1579
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1580
		}
1581
		return responseSender.ok(document);
25649 tejbeer 1582
	}
1583
 
25651 tejbeer 1584
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1585
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1586
			throws ProfitMandiBusinessException {
1587
 
1588
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1589
 
1590
		if (nc.getDocumentId() == null) {
1591
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1592
		}
1593
 
1594
		Document document = documentRepository.selectById(nc.getDocumentId());
1595
 
1596
		FileInputStream file = null;
1597
		try {
1598
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1599
		} catch (FileNotFoundException e) {
1600
			LOGGER.error("Retailer Document file not found : ", e);
1601
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1602
		}
1603
		// ByteArrayOutputStream byteArrayOutputStream = new
1604
		// ByteArrayOutputStream();
1605
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1606
 
1607
		final HttpHeaders headers = new HttpHeaders();
1608
		String contentType = "";
1609
		if (document.getContentType() == ContentType.JPEG) {
1610
			contentType = "image/jpeg";
1611
		} else if (document.getContentType() == ContentType.PNG) {
1612
			contentType = "image/png";
1613
		} else if (document.getContentType() == ContentType.PDF) {
1614
			contentType = "application/pdf";
1615
		}
1616
		headers.set("Content-Type", contentType);
1617
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1618
		headers.setContentLength(document.getSize());
1619
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1620
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1621
	}
26460 amit.gupta 1622
 
1623
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1624
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1625
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1626
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1627
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1628
			List<Integer> authIds = l2l1.getValue();
1629
			authIds.add(l2l1.getKey());
1630
 
1631
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1632
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1633
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1634
			if (!leads.isEmpty()) {
1635
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1636
			} else {
1637
				authIdAndleadsCountMap.put(auth.getId(), 0);
1638
			}
26422 tejbeer 1639
		}
26468 amit.gupta 1640
 
26460 amit.gupta 1641
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1642
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1643
				.collect(Collectors.toList());
26433 tejbeer 1644
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1645
 
26460 amit.gupta 1646
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1647
 
26460 amit.gupta 1648
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1649
		for (int authUserId : pp.keySet()) {
1650
			if (L2L1Mapping.keySet().contains(authUserId)) {
1651
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1652
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1653
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1654
						.collect(Collectors.toList());
27632 tejbeer 1655
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 1656
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1657
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1658
			}
1659
		}
26997 amit.gupta 1660
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1661
				.collect(Collectors.toList());
26468 amit.gupta 1662
		PartnerDetailModel partnerDetailModel = partnerStatsService
1663
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1664
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1665
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1666
		return authIdAndallValues;
1667
	}
1668
 
27579 tejbeer 1669
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1670
	public String getItemWiseTertiary(HttpServletRequest request,
1671
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1672
			throws ProfitMandiBusinessException {
1673
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1674
 
1675
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1676
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1677
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1678
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1679
		return "item-wise-tertiary";
1680
	}
1681
 
27586 tejbeer 1682
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1683
	public String getItemWiseIndent(HttpServletRequest request,
1684
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1685
			throws ProfitMandiBusinessException {
1686
 
1687
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1688
		model.addAttribute("unbilledOrders", unbilledOrders);
1689
 
1690
		return "item-wise-indent";
1691
	}
1692
 
27636 tejbeer 1693
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1694
	public String getPartnerInvestment(HttpServletRequest request,
1695
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1696
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
1697
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1698
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1699
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1700
		model.addAttribute("customRetailer", customRetailer);
1701
		return "partner-investment";
1702
	}
27727 tejbeer 1703
 
27704 amit.gupta 1704
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1705
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1706
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1707
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1708
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 1709
 
27704 amit.gupta 1710
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1711
		return "partner-pending-indent-item";
1712
	}
1713
 
27636 tejbeer 1714
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1715
	public String getPartnerActivateStockItem(HttpServletRequest request,
1716
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1717
		List<ActivateItemModel> activateStocks = new ArrayList<>();
1718
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1719
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1720
 
1721
		for (InventoryItem inventoryItem : inventoryItems) {
1722
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1723
			Item item = itemRepository.selectById(inventoryItem.getItemId());
1724
			ActivateItemModel aim = new ActivateItemModel();
1725
			aim.setFofoId(inventoryItem.getFofoId());
1726
			aim.setQuantity(inventoryItem.getGoodQuantity());
1727
			aim.setAmount(tagListing.getSellingPrice());
1728
			aim.setItemDescription(item.getItemDescription());
1729
			aim.setItemId(inventoryItem.getItemId());
1730
			activateStocks.add(aim);
1731
		}
1732
 
1733
		model.addAttribute("activateStocks", activateStocks);
1734
		model.addAttribute("customRetailer", customRetailer);
1735
		return "partner-activate-stock";
1736
	}
1737
 
1738
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1739
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
1740
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1741
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1742
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1743
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
1744
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 1745
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
1746
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 1747
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1748
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 1749
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1750
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1751
 
27636 tejbeer 1752
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1753
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 1754
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 1755
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 1756
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1757
 
27636 tejbeer 1758
		model.addAttribute("customRetailer", customRetailer);
1759
		return "partner-brand-mtd-sale";
1760
	}
1761
 
27637 tejbeer 1762
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1763
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
1764
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1765
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1766
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1767
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1768
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 1769
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1770
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 1771
 
1772
		Double accesorieslmtdsale = fofoOrderRepository
1773
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1774
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
1775
				.get(fofoId);
27638 tejbeer 1776
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1777
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1778
				Optional.of(false)).get(fofoId);
1779
 
27637 tejbeer 1780
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 1781
		model.addAttribute("brandLmtdQty", brandLmtdQty);
1782
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 1783
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1784
		model.addAttribute("customRetailer", customRetailer);
1785
		return "partner-brand-lmtd-sale";
1786
	}
1787
 
27660 tejbeer 1788
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1789
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
1790
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1791
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1792
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1793
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1794
 
1795
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 1796
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1797
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 1798
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1799
 
27893 tejbeer 1800
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1801
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 1802
		Long accesorieslmsqty = fofoOrderRepository
1803
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 1804
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 1805
				.get(fofoId);
1806
 
1807
		model.addAttribute("brandLMSAmount", brandLMSAmount);
1808
		model.addAttribute("brandLmsQty", brandLmsQty);
1809
		model.addAttribute("accesorieslmssale", accesorieslmssale);
1810
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1811
		model.addAttribute("customRetailer", customRetailer);
1812
		return "partner-brand-lms-sale";
1813
	}
1814
 
27640 tejbeer 1815
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1816
	public String getPatnerInStock(HttpServletRequest request,
1817
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1818
 
1819
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1820
 
27660 tejbeer 1821
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 1822
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 1823
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 1824
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
1825
 
27660 tejbeer 1826
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
1827
				.selectInStockItemsByBrand(fofoId);
1828
 
1829
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
1830
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1831
 
1832
		model.addAttribute("stockItemMap", stockItemMap);
1833
		model.addAttribute("mobileStock", mobileStocks);
1834
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 1835
		model.addAttribute("customRetailer", customRetailer);
1836
		return "partner-instock-item";
1837
	}
1838
 
27660 tejbeer 1839
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1840
	public String getOpenTicketByFofoId(HttpServletRequest request,
1841
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1842
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1843
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1844
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
1845
				.collect(Collectors.toList());
1846
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1847
 
1848
		for (TicketAssigned ticketAssign : ticketAssigns) {
1849
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1850
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1851
		}
1852
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1853
		model.addAttribute("ticketAssigns", ticketAssigns);
1854
		model.addAttribute("customRetailer", customRetailer);
1855
		return "open-ticket";
1856
	}
1857
 
27893 tejbeer 1858
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
1859
	public String getPartnerSecondarySale(HttpServletRequest request,
1860
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
1861
			throws Exception {
1862
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1863
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1864
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1865
		LocalDateTime startDate = null;
1866
		LocalDateTime endDate = null;
1867
		List<InStockBrandModel> secondarySale = null;
1868
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
1869
 
1870
		if (timeValue.equals("mtd")) {
1871
			startDate = curDate.withDayOfMonth(1);
1872
			endDate = curDate.with(LocalTime.MAX);
1873
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1874
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1875
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1876
			LOGGER.info("secondarySalemtd" + secondarySale);
1877
		} else if (timeValue.equals("lmtd")) {
1878
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1879
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
1880
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1881
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1882
 
1883
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1884
			LOGGER.info("secondarySalelmtd" + secondarySale);
1885
 
1886
		} else {
1887
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1888
			endDate = curDate.withDayOfMonth(1);
1889
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1890
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1891
 
1892
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1893
			LOGGER.info("secondarySalelms" + secondarySale);
1894
 
1895
		}
1896
 
1897
		LOGGER.info("secondarySale" + secondarySale);
1898
		model.addAttribute("secondarySale", secondarySale);
1899
		model.addAttribute("secondaryItemSale", secondaryItemSale);
1900
		model.addAttribute("customRetailer", customRetailer);
1901
 
1902
		return "partner-secondary-order";
1903
	}
1904
 
21615 kshitij.so 1905
}