Subversion Repositories SmartDukaan

Rev

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