Subversion Repositories SmartDukaan

Rev

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