Subversion Repositories SmartDukaan

Rev

Rev 27895 | Rev 27902 | 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;
27900 tejbeer 64
import com.spice.profitmandi.common.model.LineChartModel;
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);
27900 tejbeer 813
		mtdActivatedImeis.setBackgroundColor("#4169E1");
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);
27884 tejbeer 830
 
831
		DatasetModel LmtdActivatedImeis = new DatasetModel();
832
		LmtdActivatedImeis.setLabel("LMTD Activation");
27900 tejbeer 833
		LmtdActivatedImeis.setBackgroundColor("#6e7ecb");
27884 tejbeer 834
		LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
835
		LmtdActivatedImeis.setStack("stack1");
27900 tejbeer 836
		LmtdActivatedImeis.setOrder(1);
837
 
838
 
839
		DatasetModel linemtdChart = new DatasetModel();
840
		linemtdChart.setLabel("MTD");
841
		linemtdChart.setBackgroundColor("#DCDCDC");
842
		linemtdChart.setData(mtdValues);
843
		linemtdChart.setType("line");
844
		linemtdChart.setOrder(2);
845
 
846
		DatasetModel lineLmtdChart = new DatasetModel();
847
		lineLmtdChart.setLabel("LMTD");
848
		lineLmtdChart.setBackgroundColor("#DCDCDC");
849
		lineLmtdChart.setData(lmtdValues);
850
		lineLmtdChart.setType("line");
851
		lineLmtdChart.setOrder(2);
852
 
27884 tejbeer 853
 
26055 tejbeer 854
		List<DatasetModel> datasets = new ArrayList<>();
855
 
27884 tejbeer 856
		datasets.add(dsmUnactivated);
857
		datasets.add(mtdActivatedImeis);
858
 
859
		datasets.add(lmtdUnActivated);
860
		datasets.add(LmtdActivatedImeis);
27900 tejbeer 861
		datasets.add(linemtdChart);
862
		datasets.add(lineLmtdChart);
27884 tejbeer 863
 
26055 tejbeer 864
		DataModel dm = new DataModel();
865
		dm.setDatasets(datasets);
866
		dm.setLabels(labels);
867
 
868
		LegendModel lm = new LegendModel();
27703 amit.gupta 869
		lm.setPosition("top");
26055 tejbeer 870
 
871
		TitleModel tm = new TitleModel();
27703 amit.gupta 872
		tm.setText("Brand Wise Sales");
26055 tejbeer 873
		tm.setDisplay(true);
874
 
27884 tejbeer 875
		List<Axis> xAxes = new ArrayList<>();
876
		Axis xAxis = new Axis();
877
		xAxis.setStacked(true);
878
		xAxes.add(xAxis);
879
 
880
		List<Axis> yAxes = new ArrayList<>();
881
		Axis yAxis = new Axis();
882
		yAxis.setStacked(true);
883
		yAxes.add(yAxis);
884
 
885
		ScalesModel sm = new ScalesModel();
886
		sm.setxAxes(xAxes);
887
		sm.setyAxes(yAxes);
888
 
26055 tejbeer 889
		OptionsModel om = new OptionsModel();
890
		om.setLegend(lm);
891
		om.setTitle(tm);
27884 tejbeer 892
		om.setScales(sm);
26055 tejbeer 893
 
894
		cm.setType("bar");
895
		cm.setData(dm);
896
		cm.setOptions(om);
897
 
27884 tejbeer 898
		LOGGER.info("cm" + cm);
899
 
26055 tejbeer 900
		return cm;
901
 
902
	}
903
 
26418 tejbeer 904
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 905
		List<Menu> menus = null;
26011 amit.gupta 906
		try {
907
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
908
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 909
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 910
			ReporticoCacheTable rctSaholic = null;
911
			ReporticoCacheTable rctPartneStat = null;
912
 
27509 tejbeer 913
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 914
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
915
 
27509 tejbeer 916
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 917
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 918
 
27670 tejbeer 919
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 920
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 921
 
27819 tejbeer 922
			Map<AuthUser, Long> authUserTicketCount = null;
923
 
27539 tejbeer 924
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
925
				wm.put(entry.getKey(), entry.getValue());
926
			}
927
 
928
			wm.put(0, "Total Values");
929
			long stockValue = 0;
930
			long stockQty = 0;
931
			long pendingIndent = 0;
27542 tejbeer 932
			long tertiary = 0;
26418 tejbeer 933
 
27701 tejbeer 934
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 935
 
27701 tejbeer 936
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 937
			if (emails.contains(authUser.getEmailId())) {
938
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
939
			}
27556 tejbeer 940
 
27701 tejbeer 941
			LOGGER.info("fofoIds" + fofoIds);
27352 tejbeer 942
 
27701 tejbeer 943
			if (fofoIds != null) {
27539 tejbeer 944
 
27701 tejbeer 945
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
946
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
947
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
948
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
949
				// warehouseStock
950
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
951
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
952
 
953
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
954
 
955
				if (!warehouseStockMap.isEmpty()) {
956
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
957
						stockValue += warehouseStock.getValue().getStockValue();
958
						stockQty += warehouseStock.getValue().getStockQty();
959
						pendingIndent += warehouseStock.getValue().getPendingIndent();
960
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 961
					}
27701 tejbeer 962
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
963
					ws.setStockQty(stockQty);
964
					ws.setStockValue(stockValue);
965
					ws.setPendingIndent(pendingIndent);
966
					ws.setTertiary(tertiary);
967
					ws.setWarehouseId(0);
968
					warehouseStockMap.put(0, ws);
27591 tejbeer 969
 
27701 tejbeer 970
				}
27670 tejbeer 971
 
27701 tejbeer 972
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
973
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 974
 
27701 tejbeer 975
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
976
 
977
				// warehouseStock
978
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
979
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
980
 
981
				partnersBrandSaleMap = fofoStoreRepository
982
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
983
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
984
 
985
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
986
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
987
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
988
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
989
					if (bpt != null) {
990
						bpt.setAmtd(un.getUnbilledMtd());
991
						bpt.setUamtdQty(un.getUnbilledMTDQty());
992
					} else {
993
						bpt = new BrandWisePartnerSaleModel();
994
						bpt.setBrand(un.getBrand());
995
						bpt.setAmtd(un.getUnbilledMtd());
996
						bpt.setUamtdQty(un.getUnbilledMTDQty());
997
						bpt.setLms(0);
998
						bpt.setLmtd(0);
999
						bpt.setMtd(0);
1000
						bpt.setMtdQty(0);
1001
						bpt.setLmtd(0);
1002
						bpt.setLmtdQty(0);
1003
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 1004
					}
26418 tejbeer 1005
				}
27701 tejbeer 1006
				accessoriesBrandSales = fofoStoreRepository
1007
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
1008
 
26418 tejbeer 1009
			}
1010
 
27819 tejbeer 1011
			if (positions.size() > 0) {
1012
				if (positions.stream()
1013
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1014
								|| x.getEscalationType().equals(EscalationType.L4)
1015
								|| x.getEscalationType().equals(EscalationType.L5))
1016
						.count() > 0) {
1017
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1018
				}
1019
			}
1020
 
27415 tejbeer 1021
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
27701 tejbeer 1022
					.contains(email))
1023
 
1024
			{
26029 amit.gupta 1025
				menus = menuRepository.selectAll();
1026
			} else if (positions.size() > 0) {
27108 amit.gupta 1027
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1028
					menus = menuRepository.selectAll();
27893 tejbeer 1029
				} else {
1030
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1031
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1032
					if (menuIds.size() > 0) {
1033
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1034
					}
26022 amit.gupta 1035
				}
26090 amit.gupta 1036
				List<Position> salesPositions = positions.stream()
1037
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1038
						.collect(Collectors.toList());
1039
				if (salesPositions.size() > 0) {
1040
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26100 amit.gupta 1041
					csService.getPositionCustomRetailerMap(salesPositions).values().forEach(customRetailers -> {
26090 amit.gupta 1042
						positionRetailers.addAll(customRetailers);
1043
					});
1044
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1045
					model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
26152 amit.gupta 1046
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 1047
				}
26114 amit.gupta 1048
				List<Position> warehousePositions = positions.stream()
1049
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1050
						.collect(Collectors.toList());
1051
				if (warehousePositions.size() > 0) {
1052
					Set<CustomRetailer> positionRetailers = new HashSet<>();
26123 amit.gupta 1053
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26114 amit.gupta 1054
						positionRetailers.addAll(customRetailers);
1055
					});
1056
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1057
					model.addAttribute("retailers", gson.toJson(positionRetailers));
26123 amit.gupta 1058
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26114 amit.gupta 1059
				}
26142 amit.gupta 1060
				model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1061
 
26022 amit.gupta 1062
			}
27628 tejbeer 1063
			model.addAttribute("rctPartneStat", rctPartneStat);
1064
 
1065
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1066
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1067
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1068
 
1069
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1070
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1071
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1072
 
27594 tejbeer 1073
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1074
 
26012 amit.gupta 1075
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1076
		}
26028 amit.gupta 1077
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1078
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1079
		model.addAttribute("menu", menuList);
26012 amit.gupta 1080
		return "admin";
1081
	}
1082
 
26468 amit.gupta 1083
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1084
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1085
			throws Exception {
1086
 
1087
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1088
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1089
 
26468 amit.gupta 1090
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1091
		if (authId != 0) {
1092
			List<Integer> fofoIds = pp.get(authId);
1093
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1094
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1095
		} else {
26418 tejbeer 1096
		}
1097
 
1098
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1099
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1100
 
1101
		return "auth_user_partner_detail";
26468 amit.gupta 1102
	}
26418 tejbeer 1103
 
27545 tejbeer 1104
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1105
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1106
			throws Exception {
27701 tejbeer 1107
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1108
		String email = loginDetails.getEmailId();
1109
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1110
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1111
 
27701 tejbeer 1112
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1113
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1114
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1115
 
27545 tejbeer 1116
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1117
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1118
		if (warehouseId != 0) {
27701 tejbeer 1119
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1120
			/*
1121
			 * List<Integer> fofoIds =
1122
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1123
			 * .map(x -> x.getId()).collect(Collectors.toList());
1124
			 */
27545 tejbeer 1125
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1126
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1127
		} else {
27701 tejbeer 1128
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1129
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1130
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1131
		}
1132
 
1133
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1134
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1135
 
1136
		return "auth_user_partner_detail";
1137
	}
1138
 
27509 tejbeer 1139
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1140
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1141
			@RequestParam List<Integer> warehouseId) throws Exception {
1142
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1143
		String email = loginDetails.getEmailId();
1144
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1145
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1146
 
27701 tejbeer 1147
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1148
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1149
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1150
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1151
		if (!warehouseId.contains(0)) {
1152
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1153
		} else {
1154
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1155
			warehouseWiseBrandStock = saholicInventoryCISRepository
1156
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1157
 
1158
		}
27542 tejbeer 1159
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1160
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1161
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1162
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1163
 
27509 tejbeer 1164
		return "warehouse_brand_stock";
1165
	}
1166
 
27529 tejbeer 1167
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1168
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1169
		inventoryService.getItemAvailabilityAndIndent();
1170
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1171
		return "response";
1172
	}
1173
 
27701 tejbeer 1174
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1175
			throws Exception {
27628 tejbeer 1176
 
1177
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1178
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1179
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1180
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1181
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1182
		if (partnerStats != null) {
27701 tejbeer 1183
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1184
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1185
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1186
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1187
						.collect(Collectors.toList());
27634 tejbeer 1188
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1189
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1190
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1191
				}
27628 tejbeer 1192
 
1193
			}
27701 tejbeer 1194
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1195
					.collect(Collectors.toList());
1196
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1197
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1198
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1199
			warehouseIdAndallValues.put(0, partnerDetailModel);
1200
		}
1201
		return warehouseIdAndallValues;
1202
	}
1203
 
1204
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1205
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1206
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1207
		ObjectOutputStream oos = null;
1208
		FileOutputStream fout = null;
1209
		try {
1210
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1211
			oos = new ObjectOutputStream(fout);
1212
			oos.writeObject(partnerStats);
1213
 
1214
		} catch (Exception ex) {
1215
			ex.printStackTrace();
1216
		} finally {
1217
			if (oos != null) {
1218
				oos.close();
1219
			}
1220
		}
1221
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1222
		if (rct == null) {
1223
			rct = new ReporticoCacheTable();
1224
			rct.setTableName("partnerStat");
1225
 
1226
		}
1227
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1228
		reporticoCacheTableRepository.persist(rct);
1229
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1230
		return "response";
1231
	}
1232
 
1233
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1234
		ObjectInputStream objectinputstream = null;
1235
		Map<Integer, PartnerDetailModel> partnerStat = null;
1236
		try {
1237
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1238
			objectinputstream = new ObjectInputStream(streamIn);
1239
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1240
 
1241
			LOGGER.info("partnerStat" + partnerStat);
1242
			objectinputstream.close();
1243
 
1244
		} catch (Exception e) {
1245
			LOGGER.info("exceptionddd" + e);
1246
 
1247
			e.printStackTrace();
1248
 
1249
		} finally {
1250
			if (objectinputstream != null) {
1251
				objectinputstream.close();
1252
				LOGGER.info("clofddd" + partnerStat);
1253
 
1254
			}
1255
		}
1256
		return partnerStat;
1257
 
1258
	}
1259
 
27539 tejbeer 1260
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1261
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1262
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1263
			throws Exception {
27509 tejbeer 1264
 
1265
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1266
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1267
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1268
 
27509 tejbeer 1269
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1270
		model.addAttribute("brands", listbrands);
27538 tejbeer 1271
		model.addAttribute("listCategory", listCategory);
1272
 
27529 tejbeer 1273
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1274
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1275
		model.addAttribute("selectedCategory", category);
1276
 
27509 tejbeer 1277
		return "warehouse_brand_item_stock";
1278
	}
1279
 
27538 tejbeer 1280
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1281
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1282
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1283
			throws Exception {
27539 tejbeer 1284
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1285
		if (warehouseId.contains(0)) {
1286
			warehouseId.addAll(warehouseMap.keySet());
1287
		}
27538 tejbeer 1288
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1289
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1290
 
27538 tejbeer 1291
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1292
		model.addAttribute("warehouseMap", warehouseMap);
1293
		return "warehouse_item_details";
1294
	}
1295
 
26114 amit.gupta 1296
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1297
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1298
		positionRetailers.stream().forEach(x -> {
1299
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1300
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1301
			}
1302
		});
26114 amit.gupta 1303
		return gson.toJson(warehouses);
1304
 
1305
	}
1306
 
27556 tejbeer 1307
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1308
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1309
			throws Exception {
27701 tejbeer 1310
 
1311
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1312
		String email = loginDetails.getEmailId();
1313
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1314
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1315
 
27670 tejbeer 1316
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1317
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1318
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1319
 
1320
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1321
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1322
 
1323
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1324
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1325
			if (bpt != null) {
1326
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 1327
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1328
			} else {
1329
				bpt = new WarehouseWiseBrandSaleModel();
1330
				bpt.setWarehouseId(un.getWarehouseId());
1331
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 1332
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1333
				bpt.setLms(0);
1334
				bpt.setLmtd(0);
1335
				bpt.setMtd(0);
1336
				bpt.setMtdQty(0);
1337
				bpt.setLmtd(0);
1338
				bpt.setLmtdQty(0);
1339
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1340
			}
1341
		}
27556 tejbeer 1342
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1343
 
1344
		Set<String> brands = inventoryService.getAllTagListingBrands();
1345
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1346
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1347
		model.addAttribute("brands", brands);
1348
		model.addAttribute("selectedbrand", brand);
1349
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1350
	}
1351
 
27594 tejbeer 1352
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1353
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1354
			@RequestParam String brand) throws Exception {
27701 tejbeer 1355
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1356
		String email = loginDetails.getEmailId();
1357
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1358
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1359
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1360
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1361
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1362
 
1363
		Set<String> brands = inventoryService.getAllTagListingBrands();
1364
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1365
		model.addAttribute("warehouseMap", warehouseMap);
1366
		model.addAttribute("brands", brands);
1367
		model.addAttribute("selectedbrand", brand);
1368
		return "warehousewise_accessoriesbrand_sale";
1369
	}
1370
 
27556 tejbeer 1371
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1372
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1373
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1374
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1375
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1376
		String email = loginDetails.getEmailId();
1377
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1378
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 1379
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 1380
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1381
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1382
 
1383
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 1384
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1385
 
1386
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1387
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1388
			if (bpt != null) {
1389
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 1390
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1391
			} else {
1392
				bpt = new WarehouseBrandWiseItemSaleModel();
1393
				bpt.setWarehouseId(un.getWarehouseId());
1394
				bpt.setItemId(un.getItemId());
1395
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 1396
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1397
				bpt.setBrand(un.getBrand());
1398
				bpt.setModelName(un.getModelName());
1399
				bpt.setModelNumber(un.getModelNumber());
1400
				bpt.setColor(un.getColor());
1401
				bpt.setLms(0);
1402
				bpt.setLmtd(0);
1403
				bpt.setMtd(0);
1404
				bpt.setMtdQty(0);
1405
				bpt.setLmtd(0);
1406
				bpt.setLmtdQty(0);
1407
				branditemSalesMap.put(un.getItemId(), bpt);
1408
			}
1409
		}
1410
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 1411
		model.addAttribute("warehouseMap", warehouseMap);
1412
		return "warehouse_partner_itemwise_sale";
1413
	}
1414
 
27594 tejbeer 1415
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1416
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1417
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1418
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1419
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1420
		String email = loginDetails.getEmailId();
1421
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1422
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1423
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 1424
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1425
		model.addAttribute("branditemSales", branditemSales);
1426
		model.addAttribute("warehouseMap", warehouseMap);
1427
		return "warehouse_accessories_itemwsie_sale";
1428
	}
1429
 
26012 amit.gupta 1430
	private List<Menu> prepareMenu(List<Menu> menus) {
1431
		List<Menu> returnMenu = new ArrayList<>();
1432
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1433
		for (Menu menu : menus) {
1434
			if (menu.get_parent() == null) {
26014 amit.gupta 1435
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1436
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1437
				}
1438
			} else {
26012 amit.gupta 1439
				Menu parentMenu = menu.get_parent();
1440
				if (!subMenuMap.containsKey(parentMenu)) {
1441
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1442
				}
26012 amit.gupta 1443
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1444
			}
1445
		}
26012 amit.gupta 1446
		subMenuMap.entrySet().stream().forEach(entry -> {
1447
			entry.getKey().setSubMenus(entry.getValue());
1448
			returnMenu.add(entry.getKey());
1449
		});
1450
		return returnMenu;
26005 amit.gupta 1451
	}
1452
 
24288 amit.gupta 1453
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1454
	private boolean hasGift(int fofoId) {
1455
		try {
24288 amit.gupta 1456
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1457
					.getAvailability() > 0;
24203 amit.gupta 1458
		} catch (ProfitMandiBusinessException e) {
1459
			return false;
1460
		}
1461
	}
24288 amit.gupta 1462
 
22354 ashik.ali 1463
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1464
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1465
		model.addAttribute("appContextPath", request.getContextPath());
1466
		return "contact-us";
1467
	}
23923 amit.gupta 1468
 
25649 tejbeer 1469
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1470
	public String getNotificationsWithType(HttpServletRequest request,
1471
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1472
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1473
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1474
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1475
		int userId = 0;
1476
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1477
		if (isAdmin) {
1478
			userId = loginDetails.getFofoId();
1479
		} else {
1480
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1481
		}
25683 tejbeer 1482
		List<Notification> notifications = null;
1483
 
26086 tejbeer 1484
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1485
				userId, offset, limit);
1486
		LOGGER.info("messageType" + messageType);
1487
		notifications = getNotifications(notificationCampaigns, messageType);
1488
 
25683 tejbeer 1489
		model.addAttribute("notifications", notifications);
1490
 
1491
		LOGGER.info("notifications" + notifications);
1492
		return "notification-template";
1493
	}
1494
 
1495
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1496
			throws ProfitMandiBusinessException {
1497
		List<Notification> notifications = new ArrayList<>();
1498
		Document document = null;
1499
		if (messageType != null) {
1500
			for (NotificationCampaign notificationCampaign : nc) {
1501
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1502
					Notification ns = new Notification();
1503
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1504
							SimpleCampaignParams.class);
1505
					Campaign campaign = new SimpleCampaign(scp);
1506
					LocalDateTime expire = campaign.getExpireTimestamp();
1507
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1508
					ns.setType(campaign.getType());
1509
					ns.setMessage(campaign.getMessage());
1510
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1511
					if (notificationCampaign.getDocumentId() != null) {
1512
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1513
						ns.setDocumentName(document.getDisplayName());
1514
					}
25683 tejbeer 1515
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1516
					ns.setShowImage(campaign.getShowImage());
1517
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1518
					ns.setDocumentId(notificationCampaign.getDocumentId());
1519
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1520
					ns.setCreated(
1521
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1522
									* 1000);
1523
					if (LocalDateTime.now().isAfter(expire)) {
1524
						ns.setExpired(true);
1525
					} else {
1526
						ns.setExpired(false);
1527
					}
1528
					notifications.add(ns);
1529
				}
1530
			}
25683 tejbeer 1531
		} else {
1532
			for (NotificationCampaign notificationCampaign : nc) {
1533
 
1534
				Notification ns = new Notification();
1535
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1536
						SimpleCampaignParams.class);
1537
				Campaign campaign = new SimpleCampaign(scp);
1538
				LocalDateTime expire = campaign.getExpireTimestamp();
1539
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1540
				ns.setType(campaign.getType());
1541
				ns.setMessage(campaign.getMessage());
1542
				ns.setTitle(campaign.getTitle());
1543
				if (notificationCampaign.getDocumentId() != null) {
1544
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1545
					ns.setDocumentName(document.getDisplayName());
1546
				}
1547
				ns.setUrl(campaign.getUrl());
1548
				ns.setShowImage(campaign.getShowImage());
1549
				ns.setImageUrl(campaign.getImageUrl());
1550
				ns.setDocumentId(notificationCampaign.getDocumentId());
1551
				ns.setMessageType(notificationCampaign.getMessageType());
1552
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1553
						* 1000);
1554
				if (LocalDateTime.now().isAfter(expire)) {
1555
					ns.setExpired(true);
1556
				} else {
1557
					ns.setExpired(false);
1558
				}
1559
				notifications.add(ns);
1560
			}
1561
 
25649 tejbeer 1562
		}
25683 tejbeer 1563
		return notifications;
25651 tejbeer 1564
 
1565
	}
25649 tejbeer 1566
 
25651 tejbeer 1567
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1568
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1569
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1570
			throws ProfitMandiBusinessException {
1571
		Document document = documentRepository.selectById(documentId);
1572
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1573
		if (nc.getDocumentId() == null) {
1574
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1575
		}
1576
		if (nc.getDocumentId() != documentId) {
1577
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1578
		}
1579
		return responseSender.ok(document);
25649 tejbeer 1580
	}
1581
 
25651 tejbeer 1582
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1583
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1584
			throws ProfitMandiBusinessException {
1585
 
1586
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1587
 
1588
		if (nc.getDocumentId() == null) {
1589
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1590
		}
1591
 
1592
		Document document = documentRepository.selectById(nc.getDocumentId());
1593
 
1594
		FileInputStream file = null;
1595
		try {
1596
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1597
		} catch (FileNotFoundException e) {
1598
			LOGGER.error("Retailer Document file not found : ", e);
1599
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1600
		}
1601
		// ByteArrayOutputStream byteArrayOutputStream = new
1602
		// ByteArrayOutputStream();
1603
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1604
 
1605
		final HttpHeaders headers = new HttpHeaders();
1606
		String contentType = "";
1607
		if (document.getContentType() == ContentType.JPEG) {
1608
			contentType = "image/jpeg";
1609
		} else if (document.getContentType() == ContentType.PNG) {
1610
			contentType = "image/png";
1611
		} else if (document.getContentType() == ContentType.PDF) {
1612
			contentType = "application/pdf";
1613
		}
1614
		headers.set("Content-Type", contentType);
1615
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1616
		headers.setContentLength(document.getSize());
1617
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1618
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1619
	}
26460 amit.gupta 1620
 
1621
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1622
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1623
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1624
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1625
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1626
			List<Integer> authIds = l2l1.getValue();
1627
			authIds.add(l2l1.getKey());
1628
 
1629
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1630
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1631
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1632
			if (!leads.isEmpty()) {
1633
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1634
			} else {
1635
				authIdAndleadsCountMap.put(auth.getId(), 0);
1636
			}
26422 tejbeer 1637
		}
26468 amit.gupta 1638
 
26460 amit.gupta 1639
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1640
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1641
				.collect(Collectors.toList());
26433 tejbeer 1642
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1643
 
26460 amit.gupta 1644
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1645
 
26460 amit.gupta 1646
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1647
		for (int authUserId : pp.keySet()) {
1648
			if (L2L1Mapping.keySet().contains(authUserId)) {
1649
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1650
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1651
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1652
						.collect(Collectors.toList());
27632 tejbeer 1653
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 1654
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1655
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1656
			}
1657
		}
26997 amit.gupta 1658
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1659
				.collect(Collectors.toList());
26468 amit.gupta 1660
		PartnerDetailModel partnerDetailModel = partnerStatsService
1661
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1662
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1663
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1664
		return authIdAndallValues;
1665
	}
1666
 
27579 tejbeer 1667
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1668
	public String getItemWiseTertiary(HttpServletRequest request,
1669
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1670
			throws ProfitMandiBusinessException {
1671
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1672
 
1673
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1674
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1675
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1676
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1677
		return "item-wise-tertiary";
1678
	}
1679
 
27586 tejbeer 1680
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1681
	public String getItemWiseIndent(HttpServletRequest request,
1682
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1683
			throws ProfitMandiBusinessException {
1684
 
1685
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1686
		model.addAttribute("unbilledOrders", unbilledOrders);
1687
 
1688
		return "item-wise-indent";
1689
	}
1690
 
27636 tejbeer 1691
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1692
	public String getPartnerInvestment(HttpServletRequest request,
1693
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1694
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
1695
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1696
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1697
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1698
		model.addAttribute("customRetailer", customRetailer);
1699
		return "partner-investment";
1700
	}
27727 tejbeer 1701
 
27704 amit.gupta 1702
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1703
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1704
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1705
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1706
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 1707
 
27704 amit.gupta 1708
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1709
		return "partner-pending-indent-item";
1710
	}
1711
 
27636 tejbeer 1712
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1713
	public String getPartnerActivateStockItem(HttpServletRequest request,
1714
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1715
		List<ActivateItemModel> activateStocks = new ArrayList<>();
1716
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1717
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1718
 
1719
		for (InventoryItem inventoryItem : inventoryItems) {
1720
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1721
			Item item = itemRepository.selectById(inventoryItem.getItemId());
1722
			ActivateItemModel aim = new ActivateItemModel();
1723
			aim.setFofoId(inventoryItem.getFofoId());
1724
			aim.setQuantity(inventoryItem.getGoodQuantity());
1725
			aim.setAmount(tagListing.getSellingPrice());
1726
			aim.setItemDescription(item.getItemDescription());
1727
			aim.setItemId(inventoryItem.getItemId());
1728
			activateStocks.add(aim);
1729
		}
1730
 
1731
		model.addAttribute("activateStocks", activateStocks);
1732
		model.addAttribute("customRetailer", customRetailer);
1733
		return "partner-activate-stock";
1734
	}
1735
 
1736
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1737
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
1738
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1739
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1740
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1741
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
1742
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 1743
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
1744
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 1745
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1746
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 1747
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1748
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1749
 
27636 tejbeer 1750
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1751
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 1752
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 1753
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 1754
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1755
 
27636 tejbeer 1756
		model.addAttribute("customRetailer", customRetailer);
1757
		return "partner-brand-mtd-sale";
1758
	}
1759
 
27637 tejbeer 1760
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1761
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
1762
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1763
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1764
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1765
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1766
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 1767
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1768
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 1769
 
1770
		Double accesorieslmtdsale = fofoOrderRepository
1771
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1772
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
1773
				.get(fofoId);
27638 tejbeer 1774
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1775
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1776
				Optional.of(false)).get(fofoId);
1777
 
27637 tejbeer 1778
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 1779
		model.addAttribute("brandLmtdQty", brandLmtdQty);
1780
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 1781
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1782
		model.addAttribute("customRetailer", customRetailer);
1783
		return "partner-brand-lmtd-sale";
1784
	}
1785
 
27660 tejbeer 1786
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1787
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
1788
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1789
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1790
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1791
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1792
 
1793
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 1794
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1795
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 1796
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1797
 
27893 tejbeer 1798
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1799
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 1800
		Long accesorieslmsqty = fofoOrderRepository
1801
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 1802
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 1803
				.get(fofoId);
1804
 
1805
		model.addAttribute("brandLMSAmount", brandLMSAmount);
1806
		model.addAttribute("brandLmsQty", brandLmsQty);
1807
		model.addAttribute("accesorieslmssale", accesorieslmssale);
1808
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1809
		model.addAttribute("customRetailer", customRetailer);
1810
		return "partner-brand-lms-sale";
1811
	}
1812
 
27640 tejbeer 1813
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1814
	public String getPatnerInStock(HttpServletRequest request,
1815
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1816
 
1817
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1818
 
27660 tejbeer 1819
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 1820
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 1821
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 1822
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
1823
 
27660 tejbeer 1824
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
1825
				.selectInStockItemsByBrand(fofoId);
1826
 
1827
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
1828
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1829
 
1830
		model.addAttribute("stockItemMap", stockItemMap);
1831
		model.addAttribute("mobileStock", mobileStocks);
1832
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 1833
		model.addAttribute("customRetailer", customRetailer);
1834
		return "partner-instock-item";
1835
	}
1836
 
27660 tejbeer 1837
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1838
	public String getOpenTicketByFofoId(HttpServletRequest request,
1839
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1840
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1841
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1842
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
1843
				.collect(Collectors.toList());
1844
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1845
 
1846
		for (TicketAssigned ticketAssign : ticketAssigns) {
1847
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1848
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1849
		}
1850
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1851
		model.addAttribute("ticketAssigns", ticketAssigns);
1852
		model.addAttribute("customRetailer", customRetailer);
1853
		return "open-ticket";
1854
	}
1855
 
27893 tejbeer 1856
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
1857
	public String getPartnerSecondarySale(HttpServletRequest request,
1858
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
1859
			throws Exception {
1860
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1861
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1862
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1863
		LocalDateTime startDate = null;
1864
		LocalDateTime endDate = null;
1865
		List<InStockBrandModel> secondarySale = null;
1866
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
1867
 
1868
		if (timeValue.equals("mtd")) {
1869
			startDate = curDate.withDayOfMonth(1);
1870
			endDate = curDate.with(LocalTime.MAX);
1871
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1872
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1873
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1874
			LOGGER.info("secondarySalemtd" + secondarySale);
1875
		} else if (timeValue.equals("lmtd")) {
1876
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1877
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
1878
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1879
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1880
 
1881
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1882
			LOGGER.info("secondarySalelmtd" + secondarySale);
1883
 
1884
		} else {
1885
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1886
			endDate = curDate.withDayOfMonth(1);
1887
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1888
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1889
 
1890
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1891
			LOGGER.info("secondarySalelms" + secondarySale);
1892
 
1893
		}
1894
 
1895
		LOGGER.info("secondarySale" + secondarySale);
1896
		model.addAttribute("secondarySale", secondarySale);
1897
		model.addAttribute("secondaryItemSale", secondaryItemSale);
1898
		model.addAttribute("customRetailer", customRetailer);
1899
 
1900
		return "partner-secondary-order";
1901
	}
1902
 
21615 kshitij.so 1903
}