Subversion Repositories SmartDukaan

Rev

Rev 27876 | Rev 27884 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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