Subversion Repositories SmartDukaan

Rev

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