Subversion Repositories SmartDukaan

Rev

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