Subversion Repositories SmartDukaan

Rev

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