Subversion Repositories SmartDukaan

Rev

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

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