Subversion Repositories SmartDukaan

Rev

Rev 28442 | Rev 28444 | 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;
28272 tejbeer 12
import java.time.Month;
27555 tejbeer 13
import java.time.YearMonth;
25649 tejbeer 14
import java.time.ZoneOffset;
27474 tejbeer 15
import java.time.format.DateTimeFormatter;
24339 amit.gupta 16
import java.util.ArrayList;
26027 amit.gupta 17
import java.util.Arrays;
28430 tejbeer 18
import java.util.Collection;
27701 tejbeer 19
import java.util.Comparator;
26011 amit.gupta 20
import java.util.HashMap;
26090 amit.gupta 21
import java.util.HashSet;
25136 amit.gupta 22
import java.util.LinkedHashMap;
28430 tejbeer 23
import java.util.LinkedHashSet;
23884 amit.gupta 24
import java.util.List;
24880 govind 25
import java.util.Map;
26055 tejbeer 26
import java.util.Map.Entry;
26071 tejbeer 27
import java.util.Optional;
26090 amit.gupta 28
import java.util.Set;
28430 tejbeer 29
import java.util.TreeMap;
28443 tejbeer 30
import java.util.stream.Collector;
24880 govind 31
import java.util.stream.Collectors;
23568 govind 32
 
22086 amit.gupta 33
import javax.servlet.http.HttpServletRequest;
25221 amit.gupta 34
import javax.transaction.Transactional;
22086 amit.gupta 35
 
28435 tejbeer 36
import org.apache.commons.collections4.OrderedMap;
23786 amit.gupta 37
import org.apache.logging.log4j.LogManager;
23568 govind 38
import org.apache.logging.log4j.Logger;
28430 tejbeer 39
import org.bouncycastle.crypto.tls.HashAlgorithm;
26158 amit.gupta 40
import org.json.JSONObject;
22481 ashik.ali 41
import org.springframework.beans.factory.annotation.Autowired;
23379 ashik.ali 42
import org.springframework.beans.factory.annotation.Value;
25651 tejbeer 43
import org.springframework.core.io.InputStreamResource;
44
import org.springframework.http.HttpHeaders;
45
import org.springframework.http.HttpStatus;
25649 tejbeer 46
import org.springframework.http.ResponseEntity;
21615 kshitij.so 47
import org.springframework.stereotype.Controller;
22073 ashik.ali 48
import org.springframework.ui.Model;
21615 kshitij.so 49
import org.springframework.web.bind.annotation.RequestMapping;
50
import org.springframework.web.bind.annotation.RequestMethod;
25649 tejbeer 51
import org.springframework.web.bind.annotation.RequestParam;
21615 kshitij.so 52
 
28430 tejbeer 53
import com.google.common.collect.ArrayListMultimap;
54
import com.google.common.collect.Multimap;
25649 tejbeer 55
import com.google.gson.Gson;
25677 amit.gupta 56
import com.mongodb.DBObject;
25651 tejbeer 57
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 58
import com.spice.profitmandi.common.enumuration.MessageType;
26065 amit.gupta 59
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22481 ashik.ali 60
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27636 tejbeer 61
import com.spice.profitmandi.common.model.ActivateItemModel;
27884 tejbeer 62
import com.spice.profitmandi.common.model.Axis;
25677 amit.gupta 63
import com.spice.profitmandi.common.model.BrandStockPrice;
27884 tejbeer 64
import com.spice.profitmandi.common.model.ChartInvestmentModel;
26055 tejbeer 65
import com.spice.profitmandi.common.model.ChartModel;
26005 amit.gupta 66
import com.spice.profitmandi.common.model.CustomRetailer;
27884 tejbeer 67
import com.spice.profitmandi.common.model.Data;
68
import com.spice.profitmandi.common.model.DataInvestmentModel;
26055 tejbeer 69
import com.spice.profitmandi.common.model.DataModel;
28430 tejbeer 70
 
26055 tejbeer 71
import com.spice.profitmandi.common.model.DatasetModel;
28434 tejbeer 72
import com.spice.profitmandi.common.model.HoverModel;
27884 tejbeer 73
import com.spice.profitmandi.common.model.Legend;
26055 tejbeer 74
import com.spice.profitmandi.common.model.LegendModel;
25649 tejbeer 75
import com.spice.profitmandi.common.model.Notification;
28409 tejbeer 76
import com.spice.profitmandi.common.model.OnlineDeliveredOrderSum;
27884 tejbeer 77
import com.spice.profitmandi.common.model.OptionModel;
26055 tejbeer 78
import com.spice.profitmandi.common.model.OptionsModel;
27884 tejbeer 79
import com.spice.profitmandi.common.model.PieLables;
28430 tejbeer 80
import com.spice.profitmandi.common.model.PluginsModel;
24203 amit.gupta 81
import com.spice.profitmandi.common.model.ProfitMandiConstants;
27884 tejbeer 82
import com.spice.profitmandi.common.model.ScalesModel;
26055 tejbeer 83
import com.spice.profitmandi.common.model.TitleModel;
28434 tejbeer 84
import com.spice.profitmandi.common.model.Tooltips;
25651 tejbeer 85
import com.spice.profitmandi.common.web.util.ResponseSender;
25649 tejbeer 86
import com.spice.profitmandi.dao.Interface.Campaign;
26011 amit.gupta 87
import com.spice.profitmandi.dao.entity.auth.AuthUser;
88
import com.spice.profitmandi.dao.entity.auth.Menu;
27355 tejbeer 89
import com.spice.profitmandi.dao.entity.catalog.Item;
27636 tejbeer 90
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26011 amit.gupta 91
import com.spice.profitmandi.dao.entity.cs.Position;
27660 tejbeer 92
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
25651 tejbeer 93
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 94
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
22654 ashik.ali 95
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
27636 tejbeer 96
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
24288 amit.gupta 97
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
25214 amit.gupta 98
import com.spice.profitmandi.dao.entity.fofo.PartnerTargetDetails;
25566 tejbeer 99
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
28409 tejbeer 100
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
101
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
27529 tejbeer 102
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
27586 tejbeer 103
import com.spice.profitmandi.dao.entity.transaction.Order;
26418 tejbeer 104
import com.spice.profitmandi.dao.entity.user.Lead;
26024 amit.gupta 105
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26418 tejbeer 106
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
28409 tejbeer 107
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
27628 tejbeer 108
import com.spice.profitmandi.dao.model.BrandWisePartnerSaleModel;
27670 tejbeer 109
import com.spice.profitmandi.dao.model.BrandWiseUnbilledActivateStockModel;
26674 tejbeer 110
import com.spice.profitmandi.dao.model.CreateOfferRequest;
27660 tejbeer 111
import com.spice.profitmandi.dao.model.InStockBrandItemModel;
27640 tejbeer 112
import com.spice.profitmandi.dao.model.InStockBrandModel;
27579 tejbeer 113
import com.spice.profitmandi.dao.model.ItemWiseTertiaryModel;
27474 tejbeer 114
import com.spice.profitmandi.dao.model.MonthSaleModel;
26418 tejbeer 115
import com.spice.profitmandi.dao.model.PartnerDetailModel;
27599 tejbeer 116
import com.spice.profitmandi.dao.model.PartnerPendingIndentItemModel;
28443 tejbeer 117
import com.spice.profitmandi.dao.model.PriceDropYearMonthModel;
28439 tejbeer 118
import com.spice.profitmandi.dao.model.SecondaryOrderBilledLmsModel;
25649 tejbeer 119
import com.spice.profitmandi.dao.model.SimpleCampaign;
120
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
27670 tejbeer 121
import com.spice.profitmandi.dao.model.WarehouseBrandItemUnbilledActivatedModel;
27556 tejbeer 122
import com.spice.profitmandi.dao.model.WarehouseBrandWiseItemSaleModel;
27628 tejbeer 123
import com.spice.profitmandi.dao.model.WarehouseWiseBrandSaleModel;
27591 tejbeer 124
import com.spice.profitmandi.dao.model.WarehouseWiseBrandStockModel;
27670 tejbeer 125
import com.spice.profitmandi.dao.model.WarehouseWiseBrandUnbilledActivatedModel;
27509 tejbeer 126
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
127
import com.spice.profitmandi.dao.model.WarehouseWiseitemStockModel;
25976 amit.gupta 128
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
26011 amit.gupta 129
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
130
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
27355 tejbeer 131
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
26588 tejbeer 132
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
133
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
134
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
27632 tejbeer 135
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
26090 amit.gupta 136
import com.spice.profitmandi.dao.repository.cs.CsService;
26418 tejbeer 137
import com.spice.profitmandi.dao.repository.cs.PartnersPositionRepository;
26011 amit.gupta 138
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
27660 tejbeer 139
import com.spice.profitmandi.dao.repository.cs.TicketAssignedRepository;
26011 amit.gupta 140
import com.spice.profitmandi.dao.repository.cs.TicketCategoryRepository;
26418 tejbeer 141
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
25651 tejbeer 142
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
22481 ashik.ali 143
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
26418 tejbeer 144
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
24996 amit.gupta 145
import com.spice.profitmandi.dao.repository.dtr.Mongo;
25649 tejbeer 146
import com.spice.profitmandi.dao.repository.dtr.NotificationCampaignRepository;
147
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
148
import com.spice.profitmandi.dao.repository.dtr.UserCampaignRepository;
24203 amit.gupta 149
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
24880 govind 150
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
26071 tejbeer 151
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
25649 tejbeer 152
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
26234 amit.gupta 153
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
24288 amit.gupta 154
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
25214 amit.gupta 155
import com.spice.profitmandi.dao.repository.fofo.PartnerTargetRepository;
27474 tejbeer 156
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
25566 tejbeer 157
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
28409 tejbeer 158
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
159
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
27529 tejbeer 160
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
161
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
27509 tejbeer 162
import com.spice.profitmandi.dao.repository.inventory.SaholicInventorySnapshotRepository;
27893 tejbeer 163
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
28443 tejbeer 164
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
24336 amit.gupta 165
import com.spice.profitmandi.service.PartnerInvestmentService;
26460 amit.gupta 166
import com.spice.profitmandi.service.PartnerStatsService;
23844 amit.gupta 167
import com.spice.profitmandi.service.authentication.RoleManager;
25677 amit.gupta 168
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 169
import com.spice.profitmandi.service.offers.OfferService;
27586 tejbeer 170
import com.spice.profitmandi.service.transaction.TransactionService;
26005 amit.gupta 171
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 172
import com.spice.profitmandi.web.model.LoginDetails;
173
import com.spice.profitmandi.web.util.CookiesProcessor;
27529 tejbeer 174
import com.spice.profitmandi.web.util.MVCResponseSender;
22481 ashik.ali 175
 
21615 kshitij.so 176
@Controller
25222 amit.gupta 177
@Transactional(rollbackOn = Throwable.class)
21615 kshitij.so 178
public class DashboardController {
23923 amit.gupta 179
 
26460 amit.gupta 180
	private static final double ONE_LAC = 1 * 1000 * 100;
181
	private static final double TWO_LAC = 2 * 1000 * 100;
182
	private static final double FOUR_LAC = 4 * 1000 * 100;
183
 
27727 tejbeer 184
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
27778 tejbeer 185
			"niranjan.kala@smartdukaan.com", "hemant.kaura@smartdukaan.com", "amit.gupta@shop2020.in",
186
			"tejbeer.kaur@shop2020.in");
27727 tejbeer 187
 
23379 ashik.ali 188
	@Value("${web.api.host}")
189
	private String webApiHost;
23923 amit.gupta 190
 
24072 amit.gupta 191
	@Value("${web.api.scheme}")
192
	private String webApiScheme;
24288 amit.gupta 193
 
24078 amit.gupta 194
	@Value("${web.api.root}")
195
	private String webApiRoot;
196
 
23379 ashik.ali 197
	@Value("${web.api.port}")
198
	private int webApiPort;
28430 tejbeer 199
 
22481 ashik.ali 200
	@Autowired
28443 tejbeer 201
	private PriceDropRepository priceDropRepository;
202
 
203
	@Autowired
22927 ashik.ali 204
	private CookiesProcessor cookiesProcessor;
26468 amit.gupta 205
 
26460 amit.gupta 206
	@Autowired
28409 tejbeer 207
	private PendingOrderRepository pendingOrderRepository;
208
 
209
	@Autowired
26460 amit.gupta 210
	private PartnerStatsService partnerStatsService;
23923 amit.gupta 211
 
23568 govind 212
	@Autowired
26011 amit.gupta 213
	private MenuRepository menuRepository;
26012 amit.gupta 214
 
26011 amit.gupta 215
	@Autowired
216
	private MenuCategoryRepository menuCategoryRepository;
217
 
218
	@Autowired
26090 amit.gupta 219
	private CsService csService;
220
 
221
	@Autowired
25214 amit.gupta 222
	private PartnerTargetRepository partnerTargetRepository;
223
 
224
	@Autowired
25653 amit.gupta 225
	private ResponseSender<?> responseSender;
26012 amit.gupta 226
 
26005 amit.gupta 227
	@Autowired
228
	RetailerService retailerService;
25214 amit.gupta 229
 
230
	@Autowired
23786 amit.gupta 231
	private RoleManager roleManager;
23923 amit.gupta 232
 
23838 ashik.ali 233
	@Autowired
234
	private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 235
 
236
	@Autowired
24880 govind 237
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
23923 amit.gupta 238
 
23884 amit.gupta 239
	@Autowired
24880 govind 240
	private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 241
 
23884 amit.gupta 242
	@Autowired
25653 amit.gupta 243
	DocumentRepository documentRepository;
26236 amit.gupta 244
 
26234 amit.gupta 245
	@Autowired
246
	InventoryItemRepository inventoryItemRepository;
25683 tejbeer 247
 
25677 amit.gupta 248
	@Autowired
249
	InventoryService inventoryService;
23923 amit.gupta 250
 
23884 amit.gupta 251
	@Autowired
28409 tejbeer 252
	private PendingOrderItemRepository pendingOrderItemRepository;
253
 
254
	@Autowired
24203 amit.gupta 255
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
256
 
24880 govind 257
	@Autowired
258
	private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 259
 
26011 amit.gupta 260
	@Autowired
261
	private TicketCategoryRepository ticketCategoryRepository;
24880 govind 262
 
263
	@Autowired
25566 tejbeer 264
	private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 265
 
24996 amit.gupta 266
	@Autowired
25649 tejbeer 267
	private HygieneDataRepository hygieneDataRepository;
268
 
269
	@Autowired
270
	private UserCampaignRepository userCampaignRepository;
26012 amit.gupta 271
 
26011 amit.gupta 272
	@Autowired
273
	private PositionRepository positionRepository;
27474 tejbeer 274
	@Autowired
275
	private PartnerTypeChangeRepository partnerTypeChangeRepository;
25649 tejbeer 276
 
277
	@Autowired
26418 tejbeer 278
	private PartnersPositionRepository partnerPositionRepository;
279
 
280
	@Autowired
25649 tejbeer 281
	private UserAccountRepository userAccountRepository;
282
 
283
	@Autowired
284
	private NotificationCampaignRepository notificationCampaignRepository;
285
 
286
	@Autowired
24996 amit.gupta 287
	private Mongo mongoClient;
26012 amit.gupta 288
 
25976 amit.gupta 289
	@Autowired
290
	private AuthRepository authRepository;
24880 govind 291
 
25649 tejbeer 292
	@Autowired
26071 tejbeer 293
	private FofoOrderRepository fofoOrderRepository;
294
 
295
	@Autowired
25649 tejbeer 296
	private Gson gson;
297
 
26418 tejbeer 298
	@Autowired
299
	TicketRepository ticketRepository;
300
 
301
	@Autowired
302
	private LeadRepository leadRepository;
303
 
26588 tejbeer 304
	@Autowired
305
	private OfferRepository offerRepository;
306
 
307
	@Autowired
308
	private OfferPartnerRepository offerPartnerRepository;
309
 
310
	@Autowired
27876 amit.gupta 311
	private OfferService offerService;
312
 
313
	@Autowired
26588 tejbeer 314
	private OfferMarginRepository offerMarginRepository;
27529 tejbeer 315
 
27355 tejbeer 316
	@Autowired
317
	private ItemRepository itemRepository;
26588 tejbeer 318
 
27509 tejbeer 319
	@Autowired
320
	private SaholicInventorySnapshotRepository saholicInventorySnapshotRepository;
27529 tejbeer 321
 
322
	@Autowired
323
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
324
 
325
	@Autowired
326
	private MVCResponseSender mvcResponseSender;
327
 
328
	@Autowired
329
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
330
 
27586 tejbeer 331
	@Autowired
332
	private TransactionService transactionService;
333
 
27632 tejbeer 334
	@Autowired
335
	private TagListingRepository tagListingRepository;
336
 
27660 tejbeer 337
	@Autowired
338
	private TicketAssignedRepository ticketAssignedRepository;
339
 
27893 tejbeer 340
	@Autowired
341
	private OrderRepository orderRepository;
23568 govind 342
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
23923 amit.gupta 343
 
25136 amit.gupta 344
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
25726 amit.gupta 345
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
25740 amit.gupta 346
		boolean isAdmin = false;
347
		model.addAttribute("isAdmin", isAdmin);
348
 
349
		model.addAttribute("webApiHost", webApiHost);
350
		model.addAttribute("webApiPort", webApiPort);
351
		model.addAttribute("webApiScheme", webApiScheme);
352
		model.addAttribute("webApiRoot", webApiRoot);
353
		if (isAdmin) {
354
			return "dashboard1";
26236 amit.gupta 355
		}
356
 
357
		FofoStore fofoStore = null;
26234 amit.gupta 358
		try {
359
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
360
			fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
361
			if (!fofoStore.isActive()) {
362
				return "redirect:/login";
363
			}
25740 amit.gupta 364
 
26234 amit.gupta 365
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
366
			model.addAttribute("partnerType", partnerType);
367
			model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
368
			model.addAttribute("fofoStore", customRetailer);
369
			model.addAttribute("partnerType", partnerType);
370
			model.addAttribute("hasGift", hasGift(fofoId));
371
			model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
25740 amit.gupta 372
 
27884 tejbeer 373
			model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26234 amit.gupta 374
			model.addAttribute("salesMap", this.getSales(fofoId));
375
			model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
376
			// this.setInvestments
377
			//
28272 tejbeer 378
			Map<Integer, String> monthValueMap = new HashMap<>();
379
			for (int i = 0; i <= 5; i++) {
380
				LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
381
				monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
382
			}
383
			LOGGER.info("monthValueMap" + monthValueMap);
384
			model.addAttribute("monthValueMap", monthValueMap);
26234 amit.gupta 385
			model.addAttribute("investments", this.getInvestments(fofoId));
386
			model.addAttribute("isInvestmentOk",
387
					partnerInvestmentService.isInvestmentOk(fofoId, 10, ProfitMandiConstants.CUTOFF_INVESTMENT));
388
		} catch (ProfitMandiBusinessException e) {
389
			LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
25740 amit.gupta 390
 
391
		}
392
 
28430 tejbeer 393
		return "12dashboard34";
28272 tejbeer 394
	}
25740 amit.gupta 395
 
28272 tejbeer 396
	private Map<String, Object> getInvestments(int fofoId) throws Exception {
397
		Map<String, Object> investments = new LinkedHashMap<>();
398
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
399
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1);
400
		LocalDate yesterDate = LocalDate.now().minusDays(1);
401
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
402
		if (yesterdayInvestment == null) {
403
			yesterdayInvestment = new PartnerDailyInvestment();
25740 amit.gupta 404
		}
26460 amit.gupta 405
 
28272 tejbeer 406
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
407
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
408
 
409
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
410
				.collect(Collectors.counting());
411
		investments.put("today", investment.getTotalInvestment());
412
		investments.put("investment", investment);
413
		investments.put("inStock", investment.getInStockAmount());
414
		investments.put("minimum", investment.getMinInvestmentString());
415
		investments.put("short", investment.getShortPercentage());
416
		investments.put("activated_stock", investment.getActivatedStockAmount());
417
		investments.put("okDays", okInvestmentDays);
418
		return investments;
25136 amit.gupta 419
	}
420
 
28272 tejbeer 421
	private Map<String, Object> getInvestmentsMonths(int fofoId, int month) throws Exception {
25136 amit.gupta 422
		Map<String, Object> investments = new LinkedHashMap<>();
26233 amit.gupta 423
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
28272 tejbeer 424
		LocalDate currentMonthStart = LocalDate.now().withDayOfMonth(1).minusMonths(month);
425
 
25136 amit.gupta 426
		LocalDate yesterDate = LocalDate.now().minusDays(1);
427
		PartnerDailyInvestment yesterdayInvestment = partnerDailyInvestmentRepository.select(fofoId, yesterDate);
428
		if (yesterdayInvestment == null) {
429
			yesterdayInvestment = new PartnerDailyInvestment();
430
		}
431
 
432
		List<PartnerDailyInvestment> currentMonthInvestments = partnerDailyInvestmentRepository.selectAll(fofoId,
433
				currentMonthStart, currentMonthStart.withDayOfMonth(currentMonthStart.lengthOfMonth()));
434
 
25140 amit.gupta 435
		long okInvestmentDays = currentMonthInvestments.stream().filter(x -> x.getShortPercentage() <= 10)
25136 amit.gupta 436
				.collect(Collectors.counting());
25140 amit.gupta 437
		investments.put("today", investment.getTotalInvestment());
438
		investments.put("investment", investment);
439
		investments.put("inStock", investment.getInStockAmount());
25182 amit.gupta 440
		investments.put("minimum", investment.getMinInvestmentString());
25140 amit.gupta 441
		investments.put("short", investment.getShortPercentage());
26267 amit.gupta 442
		investments.put("activated_stock", investment.getActivatedStockAmount());
25649 tejbeer 443
		investments.put("okDays", okInvestmentDays);
25136 amit.gupta 444
		return investments;
445
	}
446
 
25221 amit.gupta 447
	private Map<String, Object> getSales(int fofoId) {
25653 amit.gupta 448
 
25221 amit.gupta 449
		Map<String, Object> salesMap = new LinkedHashMap<>();
28442 amit.gupta 450
		LocalDateTime now = LocalDateTime.now();
451
		LocalDateTime startOfToday= LocalDate.now().atStartOfDay();
25214 amit.gupta 452
		int monthLength = LocalDate.now().lengthOfMonth();
28442 amit.gupta 453
		int daysGone = now.getDayOfMonth() - 1;
454
		int daysRemaining = monthLength - daysGone; 
26012 amit.gupta 455
		Double todaySale = fofoOrderItemRepository
28442 amit.gupta 456
				.selectSumMopGroupByRetailer(startOfToday, now, fofoId, false).get(fofoId);
457
		Double mtdSaleTillYesterDay = fofoOrderItemRepository
458
				.selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1), startOfToday, fofoId, false)
26012 amit.gupta 459
				.get(fofoId);
28442 amit.gupta 460
		Double mtdSale = mtdSaleTillYesterDay + todaySale;
461
		Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1).minusMonths(1),
462
				now.minusMonths(1), fofoId, false).get(fofoId);
25214 amit.gupta 463
 
464
		List<PartnerTargetDetails> partnerTargetDetails = partnerTargetRepository
465
				.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now());
25544 amit.gupta 466
		if (partnerTargetDetails.isEmpty()) {
25372 tejbeer 467
			partnerTargetDetails = partnerTargetRepository
25653 amit.gupta 468
					.selectAllGeEqAndLeEqStartDateAndEndDate(LocalDateTime.now().minusMonths(3));
25372 tejbeer 469
		}
25214 amit.gupta 470
 
25653 amit.gupta 471
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
25214 amit.gupta 472
 
28442 amit.gupta 473
		int currentRate = 0;
474
		if(mtdSaleTillYesterDay> 0) {
475
			currentRate = (int) (mtdSaleTillYesterDay / daysGone);
476
		}
25653 amit.gupta 477
 
478
		salesMap.put("requiredType", partnerType.next());
479
		float reqdAmount = partnerTypeChangeService.getMinimumAmount(partnerType.next());
28442 amit.gupta 480
		int requiredRate = (int) ((reqdAmount - mtdSaleTillYesterDay) / daysRemaining);
27859 tejbeer 481
		if (partnerType.equals(PartnerType.PLATINUM) && requiredRate < currentRate) {
482
			requiredRate = currentRate;
483
		}
25653 amit.gupta 484
		salesMap.put("requiredRate", requiredRate);
485
		salesMap.put("requiredTypeImage", PartnerType.imageMap.get(partnerType.next()));
486
 
25858 amit.gupta 487
		salesMap.put("todaySale", todaySale == null ? 0 : todaySale);
488
		salesMap.put("mtdSale", mtdSale == null ? 0 : mtdSale);
26012 amit.gupta 489
		salesMap.put("lmtdSale", lmtdSale == null ? 0 : lmtdSale);
26065 amit.gupta 490
 
27352 tejbeer 491
		PartnerType currentType = partnerTypeChangeService.getPartnerTypeByAmount(currentRate * monthLength);
25653 amit.gupta 492
		salesMap.put("currentRate", currentRate);
493
		salesMap.put("currentType", currentType);
494
		salesMap.put("currentTypeImage", PartnerType.imageMap.get(currentType));
25136 amit.gupta 495
		return salesMap;
496
	}
497
 
27474 tejbeer 498
	@RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
499
	public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
500
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
501
		int fofoId = loginDetails.getFofoId();
502
		Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
503
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
504
		int dayOfMonth = curDate.getDayOfMonth();
505
		for (int i = 1; i <= 6; i++) {
506
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
27555 tejbeer 507
			int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
27474 tejbeer 508
			double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
509
					startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
510
 
27574 tejbeer 511
			double mtdSales = fofoOrderItemRepository
512
					.selectSumMopGroupByRetailer(startOfMonth,
513
							startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false)
514
					.get(fofoId);
27474 tejbeer 515
 
516
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
517
 
518
			MonthSaleModel ms = new MonthSaleModel();
519
			ms.setMtdSales(this.format((long) mtdSales));
520
			ms.setMonthlySales(this.format(((long) monthSales)));
521
			ms.setPartnerType(partnerType);
27476 tejbeer 522
			ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
27474 tejbeer 523
			monthSaleMap.put(i, ms);
524
 
525
		}
526
		model.addAttribute("monthSales", monthSaleMap);
527
		return "monthSales";
528
	}
529
 
530
	private String format(long value) {
531
		String finalval = null;
532
 
533
		if (value >= 100000 && value < 10000000) {
534
			long reminder = value / 100000;
535
			long quitonent = value % 100000;
536
			finalval = reminder + "." + quitonent;
537
			String secondval = String.valueOf(quitonent);
538
			if (secondval.length() >= 2) {
539
				secondval = secondval.substring(0, 2);
540
				finalval = reminder + "." + secondval;
541
			}
542
			return String.valueOf(finalval) + " Lacs";
543
		} else if (value >= 1000 && value < 100000) {
544
			long reminder = value / 1000;
545
			long quitonent = value % 1000;
546
			finalval = reminder + "." + quitonent;
547
			String secondval = String.valueOf(quitonent);
548
			if (secondval.length() >= 2) {
549
				secondval = secondval.substring(0, 2);
550
				finalval = reminder + "." + secondval;
551
			}
552
			return String.valueOf(finalval) + " K";
553
		} else if (value >= 10000000 && value < 1000000000) {
554
			long reminder = value / 10000000;
555
			long quitonent = value % 10000000;
556
			finalval = reminder + "." + quitonent;
557
			String secondval = String.valueOf(quitonent);
558
			if (secondval.length() >= 2) {
559
				secondval = secondval.substring(0, 2);
560
				finalval = reminder + "." + secondval;
561
			}
562
			return String.valueOf(finalval) + " Cr";
563
		}
564
		return String.valueOf(finalval);
565
 
566
	}
567
 
27702 tejbeer 568
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
569
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25175 amit.gupta 570
 
27702 tejbeer 571
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
572
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
573
 
574
		mobileBrands.stream().forEach(x -> {
575
			String brand = (String) x.get("name");
576
			if (brandStockPricesMap.containsKey(brand)) {
577
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
578
				brandStockPrice.setBrandUrl((String) x.get("url"));
579
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
580
				brandStockPrices.add(brandStockPrice);
581
			}
582
		});
583
 
584
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
585
				.collect(Collectors.toList());
586
	}
587
 
21615 kshitij.so 588
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 589
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 590
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 591
		String email = loginDetails.getEmailId();
28430 tejbeer 592
		int fofoId = loginDetails.getFofoId();
28409 tejbeer 593
 
28430 tejbeer 594
		LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
595
		LocalDateTime endtDate = LocalDateTime.now();
596
		OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository
597
				.selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);
28409 tejbeer 598
 
28430 tejbeer 599
		LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());
600
 
601
		long countOrder = pendingOrderRepository.pendingOrderCount(fofoId, OrderStatus.PROCESSING);
602
		LOGGER.info("countOrder" + countOrder);
603
 
28409 tejbeer 604
		model.addAttribute("countOrder", countOrder);
605
		model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());
25180 amit.gupta 606
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
607
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 608
 
25274 amit.gupta 609
		model.addAttribute("webApiHost", webApiHost);
610
		model.addAttribute("webApiPort", webApiPort);
611
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 612
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 613
		if (isAdmin) {
26011 amit.gupta 614
			return adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 615
		} else {
25740 amit.gupta 616
			FofoStore fofoStore = null;
25180 amit.gupta 617
			try {
618
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 619
				if (!fofoStore.isActive()) {
620
					return "redirect:/login";
621
				}
25649 tejbeer 622
 
25740 amit.gupta 623
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 624
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 625
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 626
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 627
				model.addAttribute("partnerType", partnerType);
25180 amit.gupta 628
				model.addAttribute("hasGift", hasGift(loginDetails.getFofoId()));
629
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26222 tejbeer 630
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
26162 amit.gupta 631
						.append("partnerId", fofoStore.getId()).toString());
26460 amit.gupta 632
				model.addAttribute("activatedImeis",
633
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
26071 tejbeer 634
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
635
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
636
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
637
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27701 tejbeer 638
 
26071 tejbeer 639
				Double accesoriesStock = currentInventorySnapshotRepository
640
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
641
								Optional.of(false))
642
						.get(loginDetails.getFofoId());
25180 amit.gupta 643
 
26071 tejbeer 644
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
27702 tejbeer 645
				model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
25180 amit.gupta 646
				model.addAttribute("salesMap", this.getSales(loginDetails.getFofoId()));
26055 tejbeer 647
				ChartModel cm = this.getBrandChart(loginDetails.getFofoId());
648
 
649
				LOGGER.info("chartMap" + gson.toJson(cm));
650
				model.addAttribute("chartMap", gson.toJson(cm));
27701 tejbeer 651
 
27876 amit.gupta 652
				List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(),
653
						YearMonth.from(LocalDateTime.now()));
654
				model.addAttribute("publishedOffers", publishedOffers);
25180 amit.gupta 655
				model.addAttribute("investments", this.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 656
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
657
						10, ProfitMandiConstants.CUTOFF_INVESTMENT));
26460 amit.gupta 658
 
25180 amit.gupta 659
			} catch (ProfitMandiBusinessException e) {
660
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
661
 
662
			}
22481 ashik.ali 663
		}
25649 tejbeer 664
 
665
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
25747 amit.gupta 666
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
25653 amit.gupta 667
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
668
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
25677 amit.gupta 669
				currentMonthEnd) / 2;
25747 amit.gupta 670
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
671
				currentMonthStart) / 2;
672
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
25677 amit.gupta 673
				currentMonthEnd) / 2;
674
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
675
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
676
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
25649 tejbeer 677
 
25653 amit.gupta 678
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart,
679
				currentMonthEnd);
25651 tejbeer 680
 
25653 amit.gupta 681
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
682
				currentMonthStart, currentMonthEnd);
683
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
684
			invalidHygieneCount = 1;
685
		}
28272 tejbeer 686
		Map<Integer, String> monthValueMap = new HashMap<>();
687
		for (int i = 0; i <= 5; i++) {
688
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
689
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
690
		}
691
 
692
		model.addAttribute("monthValueMap", monthValueMap);
693
		model.addAttribute("month", 0);
694
 
25653 amit.gupta 695
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
25651 tejbeer 696
 
25197 amit.gupta 697
		model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
698
		model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
27884 tejbeer 699
		/*
700
		 * if (loginDetails.isReadOnly()) { return "dashboard-readonly"; } else { }
701
		 */
28430 tejbeer 702
 
27882 amit.gupta 703
		return "dashboard1";
28272 tejbeer 704
 
21615 kshitij.so 705
	}
23923 amit.gupta 706
 
28272 tejbeer 707
	@RequestMapping(value = "/getMonthsInvestment", method = RequestMethod.GET)
708
	public String getMonthsInvestment(HttpServletRequest request,
709
			@RequestParam(name = "month", required = true, defaultValue = "0") int month, Model model)
710
			throws Exception {
711
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
712
		int fofoId = loginDetails.getFofoId();
713
		Map<String, Object> investment = getInvestmentsMonths(fofoId, month);
28430 tejbeer 714
 
28272 tejbeer 715
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
716
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
717
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
718
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
719
				currentMonthEnd) / 2;
720
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
721
				currentMonthStart) / 2;
722
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
723
				currentMonthEnd) / 2;
724
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
725
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
726
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
727
 
28430 tejbeer 728
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true,
729
				currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
28272 tejbeer 730
 
731
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
28430 tejbeer 732
				currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
28272 tejbeer 733
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
734
			invalidHygieneCount = 1;
735
		}
736
		Map<Integer, String> monthValueMap = new HashMap<>();
737
		for (int i = 0; i <= 5; i++) {
738
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
739
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
740
		}
741
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
28430 tejbeer 742
		model.addAttribute("monthValueMap", monthValueMap);
28272 tejbeer 743
		model.addAttribute("investments", investment);
744
		model.addAttribute("monthDays", LocalDate.now().minusMonths(month).lengthOfMonth());
745
		model.addAttribute("dayOfMonth", LocalDate.now().minusMonths(month).lengthOfMonth());
28430 tejbeer 746
		model.addAttribute("month", month);
28272 tejbeer 747
		return "performance";
748
	}
749
 
27884 tejbeer 750
	@RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
751
	public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
752
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
753
		int fofoId = loginDetails.getFofoId();
754
		ChartInvestmentModel cm = this.getInvestmentChart(fofoId);
755
		model.addAttribute("chartPieMap", gson.toJson(cm));
756
 
757
		LOGGER.info("InvestmentChart" + gson.toJson(cm));
758
		LOGGER.info("InvestmentChart" + cm);
759
		return "investmentdetails";
760
	}
761
 
28430 tejbeer 762
	@RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
763
	public String getlmsLineChart(HttpServletRequest request, Model model) throws Exception {
764
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
765
		int fofoId = loginDetails.getFofoId();
766
		ChartModel cm = this.getLmsLineChart(loginDetails.getFofoId());
767
 
768
		LOGGER.info("linechartMap" + gson.toJson(cm));
769
		model.addAttribute("linechartMap", gson.toJson(cm));
770
 
771
		return "lmsLineChart";
772
	}
773
 
28439 tejbeer 774
	@RequestMapping(value = "/getMonthlyPurchaseLineChart", method = RequestMethod.GET)
775
	public String getMonthlyPurchaseLineChart(HttpServletRequest request, Model model) throws Exception {
776
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
777
		int fofoId = loginDetails.getFofoId();
778
		ChartModel cm = this.getPurchaseOrderChart(fofoId);
779
 
780
		LOGGER.info("chartMap" + gson.toJson(cm));
781
		model.addAttribute("chartMap", gson.toJson(cm));
782
 
783
		return "purchase_chart";
784
	}
785
 
28430 tejbeer 786
	@RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
787
	public String getBarChart(HttpServletRequest request, Model model) throws Exception {
788
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
789
		int fofoId = loginDetails.getFofoId();
790
		ChartModel cm = this.getBrandChart(fofoId);
791
 
792
		LOGGER.info("chartMap" + gson.toJson(cm));
793
		model.addAttribute("chartMap", gson.toJson(cm));
794
 
795
		return "bar_chart";
796
	}
797
 
28443 tejbeer 798
	@RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
799
	public String getMonthlyPriceDrop(HttpServletRequest request, Model model) throws Exception {
800
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
801
		int fofoId = loginDetails.getFofoId();
802
		ChartModel cm = this.getMonthlyPriceDrop(fofoId);
803
 
804
		LOGGER.info("chartMap" + gson.toJson(cm));
805
		model.addAttribute("chartMap", gson.toJson(cm));
806
 
807
		return "price_drop_chart";
808
	}
809
 
810
	private ChartModel getMonthlyPriceDrop(int fofoId) throws ProfitMandiBusinessException {
811
 
812
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
813
 
814
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(20);
815
 
816
		List<PriceDropYearMonthModel> priceDropYearMonthModels = priceDropRepository
817
				.selectBrandPendingPriceDropByYearMonth(fofoId, startOfMonth);
818
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
819
 
820
		Map<YearMonth, Map<String, Double>> monthBrandValue = new HashMap<>();
821
 
822
		for (PriceDropYearMonthModel priceDropYearMonthModel : priceDropYearMonthModels) {
823
 
824
			Map<String, Double> brandValue = new HashMap<>();
825
			brandValue.put(priceDropYearMonthModel.getBrand(), (double) priceDropYearMonthModel.getAmount());
826
			monthBrandValue.put(YearMonth.parse(priceDropYearMonthModel.getYearMonth(), dateTimeFormatter), brandValue);
827
		}
828
		Map<YearMonth, Map<String, Double>> sortedMonthBrandValue = new TreeMap<>(monthBrandValue);
829
		List<String> brands = new ArrayList<>();
830
 
831
		brands.add("Accessories");
832
		brands.add("Oppo");
833
		brands.add("Vivo");
834
		brands.add("Samsung");
835
		brands.add("Realme");
836
		brands.add("Mi");
837
		brands.add("Tecno");
838
		brands.add("Itel");
839
		brands.add("Lava");
840
		brands.add("Nokia");
841
		for (int i = 6; i >= 1; i--) {
842
 
843
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
844
			Map<String, Double> valbrand = sortedMonthBrandValue.get(YearMonth.from(startMonth));
845
			for (String brand : brands) {
846
				if (valbrand != null) {
847
					if (!valbrand.containsKey(brand)) {
848
						valbrand.put(brand, 0.0);
849
					} else {
850
						valbrand.put(brand, valbrand.get(brand));
851
					}
852
 
853
				} else {
854
					valbrand = new HashMap<String, Double>();
855
					valbrand.put(brand, 0.0);
856
				}
857
			}
858
 
859
			sortedMonthBrandValue.put(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)), valbrand);
860
 
861
		}
862
		Multimap<String, Map<YearMonth, Double>> brandMonthValueMap = ArrayListMultimap.create();
863
 
864
		for (Entry<YearMonth, Map<String, Double>> month : sortedMonthBrandValue.entrySet()) {
865
			for (Entry<String, Double> val : month.getValue().entrySet()) {
866
				Map<YearMonth, Double> yearValue = new HashMap<>();
867
 
868
				yearValue.put(month.getKey(), val.getValue() == null ? 0 : val.getValue());
869
 
870
				brandMonthValueMap.put(val.getKey(), yearValue);
871
 
872
			}
873
		}
874
 
875
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
876
 
877
		for (String brand : brands) {
878
			Collection<Map<YearMonth, Double>> coll = brandMonthValueMap.get(brand);
879
 
880
			List<Double> valueList = new ArrayList<>();
881
			for (Map<YearMonth, Double> col : coll) {
882
 
883
				valueList.addAll(col.values());
884
			}
885
			sortedBrandValue.put(brand, valueList);
886
		}
887
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
888
 
889
		for (int i = 6; i >= 1; i--) {
890
 
891
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
892
			labels.add(startMonth.format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
893
		}
894
 
895
		List<DatasetModel> datasets = new ArrayList<>();
896
		List<String> colorList = new ArrayList<>();
897
		colorList.add("papayawhip");
898
		colorList.add("darkgreen");
899
		colorList.add("dodgerblue");
900
		colorList.add("darkblue");
901
		colorList.add("gold");
902
 
903
		colorList.add("coral");
904
 
905
		colorList.add("steelblue");
906
		colorList.add("red");
907
		colorList.add("crimson");
908
		colorList.add("midnightblue");
909
		colorList.add("cornsilk");
910
 
911
		List<String> borderList = new ArrayList<>();
912
		borderList.add("pink");
913
		borderList.add("mediumseagreen");
914
		borderList.add("lightblue");
915
		borderList.add("#0000cd");
916
		borderList.add("#f7e98e");
917
 
918
		borderList.add("#ff8c69");
919
 
920
		borderList.add("#0000cd");
921
		borderList.add("lightsalmon");
922
		borderList.add("lightsalmon");
923
		borderList.add("#0000cd");
924
		borderList.add("cornsilk");
925
 
926
		int i = 0;
927
 
928
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
929
 
930
			DatasetModel purchaseModel = new DatasetModel();
931
			purchaseModel.setLabel(brandValue.getKey());
932
			purchaseModel.setBackgroundColor(colorList.get(i));
933
			if (brandValue.getValue().isEmpty()) {
934
 
935
				purchaseModel.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
936
			} else {
937
				purchaseModel.setData(brandValue.getValue());
938
			}
939
			purchaseModel.setType("line");
940
			purchaseModel.setOrder(1);
941
			purchaseModel.setFill("false");
942
			purchaseModel.setBorderColor(borderList.get(i));
943
			datasets.add(purchaseModel);
944
 
945
			i++;
946
		}
947
 
948
		DataModel dm = new DataModel();
949
		dm.setDatasets(datasets);
950
		dm.setLabels(labels);
951
 
952
		LegendModel lm = new LegendModel();
953
		lm.setPosition("top");
954
 
955
		Tooltips tooltips = new Tooltips();
956
		tooltips.setBodyFontSize(15);
957
		tooltips.setTitleFontSize(15);
958
		tooltips.setMode("index");
959
		tooltips.setIntersect(false);
960
 
961
		HoverModel hover = new HoverModel();
962
		hover.setIntersect(false);
963
		hover.setMode("index");
964
 
965
		TitleModel tm = new TitleModel();
966
		tm.setText("Brand Wise Monthly Price-Drop");
967
		tm.setDisplay(true);
968
		tm.setFontSize(20);
969
		tm.setFontColor("#111");
970
 
971
		OptionsModel om = new OptionsModel();
972
		om.setResponsive(true);
973
		om.setLegend(lm);
974
		om.setTitle(tm);
975
		om.setTooltips(tooltips);
976
		om.setHover(hover);
977
 
978
		ChartModel cm = new ChartModel();
979
 
980
		cm.setType("line");
981
		cm.setData(dm);
982
		cm.setOptions(om);
983
 
984
		LOGGER.info("cm" + cm);
985
 
986
		return cm;
987
	}
988
 
27884 tejbeer 989
	private ChartInvestmentModel getInvestmentChart(int fofoId) throws ProfitMandiBusinessException {
990
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
27900 tejbeer 991
 
27884 tejbeer 992
		Map<String, Float> investmentWalletAmount = new HashMap<>();
993
		investmentWalletAmount.put("Wallet", investment.getWalletAmount());
28272 tejbeer 994
		investmentWalletAmount.put("InStocks", investment.getInStockAmount() - investment.getActivatedStockAmount());
27900 tejbeer 995
		investmentWalletAmount.put("Unbilled Order", investment.getUnbilledAmount());
27884 tejbeer 996
		investmentWalletAmount.put("GrnPending", investment.getGrnPendingAmount());
997
		investmentWalletAmount.put("ReturnInTransit", investment.getReturnInTransitAmount());
998
 
27900 tejbeer 999
		if (investment.getShortInvestment() > 0) {
1000
			investmentWalletAmount.put("Short Investment", investment.getShortInvestment());
1001
		}
1002
 
27884 tejbeer 1003
		ChartInvestmentModel cm = new ChartInvestmentModel();
1004
 
1005
		HashSet<String> labels = new HashSet<String>();
1006
		labels.addAll(investmentWalletAmount.keySet());
1007
 
1008
		List<String> labelList = new ArrayList<>(labels);
1009
		List<String> backgroundColor = new ArrayList<>();
27900 tejbeer 1010
		List<Float> labelsValue = new ArrayList<>();
27884 tejbeer 1011
		List<Float> values = new ArrayList<>();
1012
		for (String label : labelList) {
1013
			values.add(investmentWalletAmount.get(label));
1014
			if (label.equals("Wallet")) {
1015
				backgroundColor.add("pink");
1016
			}
27900 tejbeer 1017
			if (label.equals("Short Investment")) {
1018
				backgroundColor.add("red");
1019
			}
28015 tejbeer 1020
			if (label.equals("InStocks")) {
27900 tejbeer 1021
				backgroundColor.add("#9ACD32");
27884 tejbeer 1022
			}
27900 tejbeer 1023
			if (label.equals("Unbilled Order")) {
1024
				backgroundColor.add("blue");
27884 tejbeer 1025
			}
1026
 
1027
			if (label.equals("ReturnInTransit")) {
1028
				backgroundColor.add("orange");
1029
			}
1030
			if (label.equals("GrnPending")) {
1031
				backgroundColor.add("yellow");
1032
			}
1033
 
1034
		}
1035
 
1036
		Data data = new Data();
1037
		data.setData(values);
1038
		data.setBackgroundColor(backgroundColor);
1039
		data.setLabel("DataSet 1");
1040
 
1041
		PieLables label = new PieLables();
1042
		label.setFontColor("White");
1043
		label.setFontSize(15);
1044
 
1045
		Legend legend = new Legend();
1046
		legend.setLabels(label);
1047
		legend.setPosition("left");
1048
 
1049
		List<Data> dataList = new ArrayList<>();
1050
		dataList.add(data);
1051
 
1052
		DataInvestmentModel datasets = new DataInvestmentModel();
1053
		datasets.setDatasets(dataList);
1054
		datasets.setLabels(labels);
1055
 
1056
		OptionModel om = new OptionModel();
1057
		om.setLegend(legend);
1058
		cm.setType("pie");
1059
		cm.setData(datasets);
1060
		cm.setOptions(om);
1061
 
1062
		return cm;
1063
	}
1064
 
28439 tejbeer 1065
	private ChartModel getPurchaseOrderChart(int fofoId) throws ProfitMandiBusinessException {
1066
 
1067
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1068
 
1069
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(1);
1070
 
1071
		List<SecondaryOrderBilledLmsModel> soblms = orderRepository.selectAllBilledOrderGroupByBrandFofoId(fofoId,
1072
				curDate.withDayOfMonth(1).minusMonths(6));
1073
 
1074
		LOGGER.info("soblms" + soblms);
1075
		Map<String, Map<YearMonth, Double>> brandMonthValueMap = new HashMap<>();
1076
		for (SecondaryOrderBilledLmsModel orderBilledLmsMode : soblms) {
1077
			Map<YearMonth, Double> yearMonthMap = new HashMap<>();
1078
			yearMonthMap.put(YearMonth.from(startOfMonth), (double) orderBilledLmsMode.getFirstMonthValue());
28443 tejbeer 1079
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(1)),
28439 tejbeer 1080
					(double) orderBilledLmsMode.getSecondMonthValue());
1081
 
1082
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(2)),
1083
					(double) orderBilledLmsMode.getThirdMonthValue());
1084
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(3)),
1085
					(double) orderBilledLmsMode.getFourthMonthValue());
1086
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(4)),
1087
					(double) orderBilledLmsMode.getFifthMonthValue());
1088
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(5)),
1089
					(double) orderBilledLmsMode.getSixthMonthValue());
1090
			Map<YearMonth, Double> sortedYearMonthMap = new TreeMap<YearMonth, Double>(yearMonthMap);
1091
			brandMonthValueMap.put(orderBilledLmsMode.getBrand(), sortedYearMonthMap);
1092
 
1093
		}
1094
		LOGGER.info("brandMonthValueMap" + brandMonthValueMap);
1095
 
1096
		List<String> brands = new ArrayList<>();
1097
		brands.add("Accessories");
1098
		brands.add("Oppo");
1099
		brands.add("Vivo");
1100
		brands.add("Samsung");
1101
		brands.add("Realme");
1102
		brands.add("Mi");
1103
		brands.add("Tecno");
1104
		brands.add("Itel");
1105
		brands.add("Lava");
1106
		brands.add("Nokia");
1107
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
1108
 
1109
		for (String brand : brands) {
1110
			Map<YearMonth, Double> coll = brandMonthValueMap.get(brand);
1111
			LOGGER.info("coll" + coll);
1112
			List<Double> valueList = new ArrayList<>();
1113
 
1114
			if (coll != null) {
1115
 
1116
				valueList.addAll(coll.values());
1117
			}
1118
			sortedBrandValue.put(brand, valueList);
1119
 
1120
		}
1121
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
28443 tejbeer 1122
 
28439 tejbeer 1123
		for (int i = 6; i >= 1; i--) {
1124
 
1125
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
1126
			labels.add(startMonth.format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
1127
 
1128
			LOGGER.info("labels" + labels);
1129
		}
1130
 
1131
		LOGGER.info("labels" + labels);
28443 tejbeer 1132
 
28439 tejbeer 1133
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
1134
		List<DatasetModel> datasets = new ArrayList<>();
1135
		List<String> colorList = new ArrayList<>();
28443 tejbeer 1136
		colorList.add("papayawhip");
28439 tejbeer 1137
		colorList.add("darkgreen");
28443 tejbeer 1138
		colorList.add("dodgerblue");
1139
		colorList.add("darkblue");
1140
		colorList.add("gold");
28439 tejbeer 1141
 
28443 tejbeer 1142
		colorList.add("coral");
28439 tejbeer 1143
 
28443 tejbeer 1144
		colorList.add("steelblue");
1145
		colorList.add("red");
1146
		colorList.add("crimson");
1147
		colorList.add("midnightblue");
28439 tejbeer 1148
		colorList.add("cornsilk");
1149
 
1150
		List<String> borderList = new ArrayList<>();
1151
		borderList.add("pink");
28443 tejbeer 1152
		borderList.add("mediumseagreen");
1153
		borderList.add("lightblue");
1154
		borderList.add("#0000cd");
1155
		borderList.add("#f7e98e");
28439 tejbeer 1156
 
28443 tejbeer 1157
		borderList.add("#ff8c69");
1158
 
1159
		borderList.add("#0000cd");
1160
		borderList.add("lightsalmon");
1161
		borderList.add("lightsalmon");
1162
		borderList.add("#0000cd");
28439 tejbeer 1163
		borderList.add("cornsilk");
1164
 
1165
		int i = 0;
1166
 
1167
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
1168
 
1169
			DatasetModel purchaseModel = new DatasetModel();
1170
			purchaseModel.setLabel(brandValue.getKey());
28443 tejbeer 1171
			purchaseModel.setBackgroundColor(colorList.get(i));
28439 tejbeer 1172
			if (brandValue.getValue().isEmpty()) {
1173
 
1174
				purchaseModel.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
1175
			} else {
1176
				purchaseModel.setData(brandValue.getValue());
1177
			}
1178
			purchaseModel.setType("line");
1179
			purchaseModel.setOrder(1);
1180
			purchaseModel.setFill("false");
28443 tejbeer 1181
			purchaseModel.setBorderColor(borderList.get(i));
28439 tejbeer 1182
			datasets.add(purchaseModel);
1183
 
1184
			i++;
1185
		}
1186
 
1187
		DataModel dm = new DataModel();
1188
		dm.setDatasets(datasets);
1189
		dm.setLabels(labels);
1190
 
1191
		LegendModel lm = new LegendModel();
1192
		lm.setPosition("top");
1193
 
1194
		Tooltips tooltips = new Tooltips();
1195
		tooltips.setBodyFontSize(15);
1196
		tooltips.setTitleFontSize(15);
1197
		tooltips.setMode("index");
1198
		tooltips.setIntersect(false);
1199
 
1200
		HoverModel hover = new HoverModel();
1201
		hover.setIntersect(false);
1202
		hover.setMode("index");
1203
 
1204
		TitleModel tm = new TitleModel();
1205
		tm.setText("Brand Wise Monthly Purchase");
1206
		tm.setDisplay(true);
1207
		tm.setFontSize(20);
1208
		tm.setFontColor("#111");
1209
 
1210
		OptionsModel om = new OptionsModel();
1211
		om.setResponsive(true);
1212
		om.setLegend(lm);
1213
		om.setTitle(tm);
1214
		om.setTooltips(tooltips);
1215
		om.setHover(hover);
1216
 
1217
		ChartModel cm = new ChartModel();
1218
		cm.setType("line");
1219
		cm.setData(dm);
1220
		cm.setOptions(om);
1221
 
1222
		LOGGER.info("cm" + cm);
1223
 
1224
		return cm;
1225
 
1226
	}
1227
 
28430 tejbeer 1228
	private ChartModel getLmsLineChart(int fofoId) throws ProfitMandiBusinessException {
1229
 
1230
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1231
 
1232
		Map<YearMonth, Map<String, Double>> monthValueMap = new HashMap<>();
1233
 
1234
		for (int i = 1; i <= 6; i++) {
1235
 
1236
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
1237
 
1238
			Map<String, Double> lmsBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1239
					curDate.withDayOfMonth(1).minusMonths(i), curDate.withDayOfMonth(1).minusMonths(i - 1), fofoId);
1240
 
1241
			Map<Integer, Double> accesorieslmsSale = fofoOrderRepository
1242
					.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(i),
1243
							curDate.withDayOfMonth(1).minusMonths(i - 1), Optional.of(false));
1244
			LOGGER.info("lmsBrandWiseSale" + lmsBrandWiseSale);
1245
 
1246
			lmsBrandWiseSale.put("Accessories", accesorieslmsSale.get(fofoId));
1247
 
1248
			monthValueMap.put(YearMonth.from(startOfMonth), lmsBrandWiseSale);
1249
		}
1250
		LOGGER.info("monthmap" + monthValueMap);
1251
 
1252
		Map<YearMonth, Map<String, Double>> sortedMonthValueMap = new TreeMap(monthValueMap);
1253
		LOGGER.info("monthmap" + sortedMonthValueMap);
1254
 
1255
		Multimap<String, Map<YearMonth, Double>> brandMonthValueMap = ArrayListMultimap.create();
1256
 
1257
		for (Entry<YearMonth, Map<String, Double>> month : sortedMonthValueMap.entrySet()) {
1258
 
1259
			for (Entry<String, Double> val : month.getValue().entrySet()) {
1260
				Map<YearMonth, Double> yearValue = new HashMap<>();
1261
 
1262
				yearValue.put(month.getKey(), val.getValue() == null ? 0 : val.getValue());
1263
				brandMonthValueMap.put(val.getKey(), yearValue);
1264
 
1265
			}
1266
		}
1267
 
1268
		LOGGER.info("map" + brandMonthValueMap);
28435 tejbeer 1269
 
28430 tejbeer 1270
		List<String> brands = new ArrayList<>();
28435 tejbeer 1271
		brands.add("Accessories");
1272
		brands.add("Oppo");
1273
		brands.add("Vivo");
1274
		brands.add("Samsung");
1275
		brands.add("Realme");
1276
		brands.add("Mi");
1277
		brands.add("Tecno");
1278
		brands.add("Itel");
1279
		brands.add("Lava");
1280
		brands.add("Nokia");
1281
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28430 tejbeer 1282
 
1283
		for (String brand : brands) {
1284
			Collection<Map<YearMonth, Double>> coll = brandMonthValueMap.get(brand);
1285
			LOGGER.info("coll" + coll);
1286
 
1287
			List<Double> valueList = new ArrayList<>();
1288
			for (Map<YearMonth, Double> col : coll) {
1289
 
1290
				valueList.addAll(col.values());
1291
			}
1292
 
28435 tejbeer 1293
			sortedBrandValue.put(brand, valueList);
28430 tejbeer 1294
 
1295
		}
1296
 
28435 tejbeer 1297
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
28430 tejbeer 1298
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
1299
		for (Entry<YearMonth, Map<String, Double>> val : sortedMonthValueMap.entrySet()) {
1300
			labels.add(val.getKey().format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
28435 tejbeer 1301
 
28430 tejbeer 1302
		}
1303
 
1304
		List<String> labelList = new ArrayList<>(labels);
1305
		List<Double> lmsValues = new ArrayList<>();
28439 tejbeer 1306
 
28430 tejbeer 1307
		List<DatasetModel> datasets = new ArrayList<>();
1308
		List<String> colorList = new ArrayList<>();
28443 tejbeer 1309
		colorList.add("papayawhip");
1310
		colorList.add("mediumseagreen");
1311
		colorList.add("dodgerblue");
1312
		colorList.add("darkblue");
1313
		colorList.add("gold");
28439 tejbeer 1314
 
28443 tejbeer 1315
		colorList.add("coral");
28439 tejbeer 1316
 
28443 tejbeer 1317
		colorList.add("steelblue");
1318
		colorList.add("red");
1319
		colorList.add("crimson");
1320
		colorList.add("midnightblue");
28432 tejbeer 1321
		colorList.add("cornsilk");
28435 tejbeer 1322
 
28430 tejbeer 1323
		List<String> borderList = new ArrayList<>();
1324
		borderList.add("pink");
28443 tejbeer 1325
		borderList.add("lawngreen");
1326
		borderList.add("lightblue");
1327
		borderList.add("#0000cd");
1328
		borderList.add("#f7e98e");
28439 tejbeer 1329
 
28443 tejbeer 1330
		borderList.add("lightcoral");
1331
 
1332
		borderList.add("#0000cd");
1333
		borderList.add("lightsalmon");
1334
		borderList.add("lightsalmon");
1335
		borderList.add("#0000cd");
28433 tejbeer 1336
		borderList.add("cornsilk");
28430 tejbeer 1337
 
28435 tejbeer 1338
		int i = 0;
28430 tejbeer 1339
 
28435 tejbeer 1340
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
1341
 
28430 tejbeer 1342
			DatasetModel lineLmsChart = new DatasetModel();
1343
			lineLmsChart.setLabel(brandValue.getKey());
28443 tejbeer 1344
			lineLmsChart.setBackgroundColor(colorList.get(i));
28435 tejbeer 1345
			if (brandValue.getValue().isEmpty()) {
1346
 
28439 tejbeer 1347
				lineLmsChart.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
28435 tejbeer 1348
			} else {
1349
				lineLmsChart.setData(brandValue.getValue());
1350
			}
28430 tejbeer 1351
			lineLmsChart.setType("line");
1352
			lineLmsChart.setOrder(1);
1353
			lineLmsChart.setFill("false");
28443 tejbeer 1354
			lineLmsChart.setBorderColor(borderList.get(i));
28430 tejbeer 1355
			datasets.add(lineLmsChart);
28435 tejbeer 1356
 
28430 tejbeer 1357
			i++;
1358
		}
1359
 
1360
		DataModel dm = new DataModel();
1361
		dm.setDatasets(datasets);
1362
		dm.setLabels(labels);
1363
 
1364
		LegendModel lm = new LegendModel();
1365
		lm.setPosition("top");
28435 tejbeer 1366
 
28434 tejbeer 1367
		Tooltips tooltips = new Tooltips();
1368
		tooltips.setBodyFontSize(15);
1369
		tooltips.setTitleFontSize(15);
1370
		tooltips.setMode("index");
1371
		tooltips.setIntersect(false);
28435 tejbeer 1372
 
28434 tejbeer 1373
		HoverModel hover = new HoverModel();
1374
		hover.setIntersect(false);
1375
		hover.setMode("index");
28435 tejbeer 1376
 
28430 tejbeer 1377
		TitleModel tm = new TitleModel();
1378
		tm.setText("Brand Wise LMS");
1379
		tm.setDisplay(true);
28434 tejbeer 1380
		tm.setFontSize(20);
28435 tejbeer 1381
		tm.setFontColor("#111");
1382
 
1383
		OptionsModel om = new OptionsModel();
28430 tejbeer 1384
		om.setResponsive(true);
1385
		om.setLegend(lm);
1386
		om.setTitle(tm);
28434 tejbeer 1387
		om.setTooltips(tooltips);
1388
		om.setHover(hover);
28430 tejbeer 1389
 
1390
		ChartModel cm = new ChartModel();
1391
		cm.setType("line");
1392
		cm.setData(dm);
1393
		cm.setOptions(om);
1394
 
1395
		LOGGER.info("cm" + cm);
1396
 
1397
		return cm;
1398
 
1399
	}
1400
 
26055 tejbeer 1401
	private ChartModel getBrandChart(int fofoId) {
1402
 
1403
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1404
 
1405
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
1406
 
1407
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
1408
 
27900 tejbeer 1409
		Map<String, Double> brandwisesale = fofoOrderItemRepository
28435 tejbeer 1410
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 1411
 
27900 tejbeer 1412
		LOGGER.info("brandwisesale" + brandwisesale);
27884 tejbeer 1413
 
26244 tejbeer 1414
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
28435 tejbeer 1415
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27900 tejbeer 1416
		brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
28272 tejbeer 1417
 
27884 tejbeer 1418
		Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
28435 tejbeer 1419
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
1420
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
27900 tejbeer 1421
 
27978 tejbeer 1422
		activatedImeisWithSellingPriceMTD.put("Lava", brandwisesale.get("Lava"));
1423
 
27884 tejbeer 1424
		Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
28435 tejbeer 1425
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
1426
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
1427
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26055 tejbeer 1428
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
28435 tejbeer 1429
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27978 tejbeer 1430
		activatedImeisWithSellingPriceLMTD.put("Lava", lmtdBrandWiseSale.get("Lava"));
26055 tejbeer 1431
 
26244 tejbeer 1432
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
28435 tejbeer 1433
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1434
				Optional.of(false));
27884 tejbeer 1435
 
1436
		lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));
1437
 
26055 tejbeer 1438
		ChartModel cm = new ChartModel();
1439
 
28435 tejbeer 1440
		HashSet<String> labels = new HashSet<String>();
1441
		labels.addAll(brandwisesale.keySet());
1442
		labels.addAll(lmtdBrandWiseSale.keySet());
26055 tejbeer 1443
 
28435 tejbeer 1444
		List<String> labelList = new ArrayList<>(labels);
27884 tejbeer 1445
 
28435 tejbeer 1446
		List<Double> mtdActivatedImeisValues = new ArrayList<>();
27884 tejbeer 1447
 
28435 tejbeer 1448
		List<Double> mtdValues = new ArrayList<>();
1449
		List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
1450
		List<Double> lmtdActivatedImeisValues = new ArrayList<>();
1451
		List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
1452
		List<Double> lmtdValues = new ArrayList<>();
1453
		for (String label : labelList) {
1454
			mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
1455
					: activatedImeisWithSellingPriceMTD.get(label));
1456
			lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
1457
					: activatedImeisWithSellingPriceLMTD.get(label));
26055 tejbeer 1458
 
28435 tejbeer 1459
			mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
1460
			if (brandwisesale.get(label) != null) {
1461
				mtdUnActivatedImeisValues
1462
						.add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
1463
								: activatedImeisWithSellingPriceMTD.get(label)));
1464
			} else {
1465
				mtdUnActivatedImeisValues.add(0.0);
1466
			}
1467
			if (lmtdBrandWiseSale.get(label) != null) {
1468
				lmtdUnActivatedImeisValues
1469
						.add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
1470
								: activatedImeisWithSellingPriceLMTD.get(label)));
1471
			} else {
1472
				lmtdUnActivatedImeisValues.add(0.0);
1473
			}
26055 tejbeer 1474
 
28435 tejbeer 1475
			lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
1476
		}
1477
		DatasetModel dsmtotal = new DatasetModel();
1478
		dsmtotal.setLabel("MTD");
1479
		dsmtotal.setBackgroundColor("blue");
1480
		dsmtotal.setBorderColor("blue");
1481
		dsmtotal.setData(mtdValues);
1482
		dsmtotal.setStack("stack0");
1483
		dsmtotal.setOrder(1);
26055 tejbeer 1484
 
28435 tejbeer 1485
		DatasetModel dsmUnactivated = new DatasetModel();
1486
		dsmUnactivated.setLabel("MTD Unactivated");
1487
		dsmUnactivated.setBackgroundColor("red");
1488
		dsmUnactivated.setBorderColor("red");
1489
		dsmUnactivated.setData(mtdUnActivatedImeisValues);
1490
		dsmUnactivated.setStack("stack0");
1491
		dsmUnactivated.setOrder(1);
27884 tejbeer 1492
 
28435 tejbeer 1493
		LOGGER.info("mtdValuesMoney" + mtdValues);
27884 tejbeer 1494
 
28435 tejbeer 1495
		DatasetModel mtdActivatedImeis = new DatasetModel();
1496
		mtdActivatedImeis.setLabel("MTD Activation");
1497
		mtdActivatedImeis.setBorderColor("#00008b");
1498
		mtdActivatedImeis.setData(mtdActivatedImeisValues);
1499
		mtdActivatedImeis.setBackgroundColor("#00008b");
1500
		mtdActivatedImeis.setStack("stack0");
1501
		mtdActivatedImeis.setOrder(1);
27884 tejbeer 1502
 
28435 tejbeer 1503
		DatasetModel lmtddsmtotal = new DatasetModel();
1504
		lmtddsmtotal.setLabel("LMTD");
1505
		lmtddsmtotal.setBackgroundColor("blue");
1506
		lmtddsmtotal.setData(lmtdValues);
1507
		lmtddsmtotal.setBorderColor("blue");
1508
		lmtddsmtotal.setStack("stack1");
1509
		lmtddsmtotal.setOrder(1);
27884 tejbeer 1510
 
28435 tejbeer 1511
		DatasetModel lmtdUnActivated = new DatasetModel();
1512
		lmtdUnActivated.setLabel("LMTD Unactivation");
1513
		lmtdUnActivated.setBackgroundColor("red");
1514
		lmtdUnActivated.setBorderColor("red");
1515
		lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
1516
		lmtdUnActivated.setStack("stack1");
1517
		lmtdUnActivated.setOrder(1);
27884 tejbeer 1518
 
28435 tejbeer 1519
		DatasetModel LmtdActivatedImeis = new DatasetModel();
1520
		LmtdActivatedImeis.setLabel("LMTD Activation");
1521
		LmtdActivatedImeis.setBackgroundColor("#87ceeb");
1522
		LmtdActivatedImeis.setBorderColor("#87ceeb");
1523
		LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
1524
		LmtdActivatedImeis.setStack("stack1");
1525
		LmtdActivatedImeis.setOrder(1);
27930 amit.gupta 1526
 
28435 tejbeer 1527
		DatasetModel linemtdChart = new DatasetModel();
1528
		linemtdChart.setLabel("MTD");
1529
		linemtdChart.setBackgroundColor("#006400");
1530
		linemtdChart.setBorderColor("#006400");
1531
		linemtdChart.setData(mtdValues);
1532
		linemtdChart.setType("line");
1533
		linemtdChart.setOrder(2);
1534
		linemtdChart.setFill("false");
27930 amit.gupta 1535
 
28435 tejbeer 1536
		DatasetModel lineLmtdChart = new DatasetModel();
1537
		lineLmtdChart.setLabel("LMTD");
1538
		lineLmtdChart.setBackgroundColor("hotpink");
1539
		lineLmtdChart.setBorderColor("hotpink");
1540
		lineLmtdChart.setData(lmtdValues);
1541
		lineLmtdChart.setType("line");
1542
		lineLmtdChart.setOrder(3);
1543
		lineLmtdChart.setFill("false");
27930 amit.gupta 1544
 
28435 tejbeer 1545
		List<DatasetModel> datasets = new ArrayList<>();
1546
		datasets.add(mtdActivatedImeis);
1547
		datasets.add(dsmUnactivated);
1548
		datasets.add(LmtdActivatedImeis);
1549
		datasets.add(lmtdUnActivated);
1550
		datasets.add(linemtdChart);
1551
		datasets.add(lineLmtdChart);
27884 tejbeer 1552
 
28435 tejbeer 1553
		DataModel dm = new DataModel();
1554
		dm.setDatasets(datasets);
1555
		dm.setLabels(labels);
27884 tejbeer 1556
 
28435 tejbeer 1557
		Tooltips tooltips = new Tooltips();
1558
		tooltips.setBodyFontSize(10);
1559
		tooltips.setTitleFontSize(10);
1560
		tooltips.setMode("index");
1561
		tooltips.setIntersect(false);
26055 tejbeer 1562
 
28435 tejbeer 1563
		HoverModel hover = new HoverModel();
1564
		hover.setIntersect(false);
1565
		hover.setMode("index");
26055 tejbeer 1566
 
28435 tejbeer 1567
		LegendModel lm = new LegendModel();
1568
		lm.setPosition("top");
26055 tejbeer 1569
 
28435 tejbeer 1570
		TitleModel tm = new TitleModel();
1571
		tm.setText("Brand Wise Sales");
1572
		tm.setDisplay(true);
1573
		tm.setFontSize(20);
1574
		tm.setFontColor("#111");
27884 tejbeer 1575
 
28435 tejbeer 1576
		List<Axis> xAxes = new ArrayList<>();
1577
		Axis xAxis = new Axis();
1578
		xAxis.setStacked(true);
1579
		xAxes.add(xAxis);
27884 tejbeer 1580
 
28435 tejbeer 1581
		List<Axis> yAxes = new ArrayList<>();
1582
		Axis yAxis = new Axis();
1583
		yAxis.setStacked(false);
1584
		yAxes.add(yAxis);
27884 tejbeer 1585
 
28435 tejbeer 1586
		ScalesModel sm = new ScalesModel();
1587
		sm.setxAxes(xAxes);
26055 tejbeer 1588
 
28435 tejbeer 1589
		OptionsModel om = new OptionsModel();
1590
		om.setLegend(lm);
1591
		om.setTitle(tm);
1592
		om.setScales(sm);
1593
		om.setHover(hover);
1594
		om.setTooltips(tooltips);
26055 tejbeer 1595
 
28435 tejbeer 1596
		cm.setType("bar");
1597
		cm.setData(dm);
1598
		cm.setOptions(om);
27884 tejbeer 1599
 
28435 tejbeer 1600
		LOGGER.info("cm" + cm);
26055 tejbeer 1601
 
28435 tejbeer 1602
		return cm;
26055 tejbeer 1603
 
28435 tejbeer 1604
	}
1605
 
26418 tejbeer 1606
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 1607
		List<Menu> menus = null;
26011 amit.gupta 1608
		try {
1609
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1610
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 1611
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 1612
			ReporticoCacheTable rctSaholic = null;
1613
			ReporticoCacheTable rctPartneStat = null;
1614
 
27509 tejbeer 1615
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 1616
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
1617
 
27509 tejbeer 1618
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 1619
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 1620
 
27670 tejbeer 1621
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 1622
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 1623
 
27819 tejbeer 1624
			Map<AuthUser, Long> authUserTicketCount = null;
1625
 
27539 tejbeer 1626
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
1627
				wm.put(entry.getKey(), entry.getValue());
1628
			}
1629
 
1630
			wm.put(0, "Total Values");
1631
			long stockValue = 0;
1632
			long stockQty = 0;
1633
			long pendingIndent = 0;
27542 tejbeer 1634
			long tertiary = 0;
26418 tejbeer 1635
 
27701 tejbeer 1636
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 1637
 
27701 tejbeer 1638
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 1639
			if (emails.contains(authUser.getEmailId())) {
1640
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
27930 amit.gupta 1641
				LOGGER.info("fofoIds" + fofoIds);
27727 tejbeer 1642
			}
27556 tejbeer 1643
 
27701 tejbeer 1644
			if (fofoIds != null) {
27539 tejbeer 1645
 
27701 tejbeer 1646
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1647
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
1648
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
1649
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
1650
				// warehouseStock
1651
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
1652
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1653
 
1654
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1655
 
1656
				if (!warehouseStockMap.isEmpty()) {
1657
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
1658
						stockValue += warehouseStock.getValue().getStockValue();
1659
						stockQty += warehouseStock.getValue().getStockQty();
1660
						pendingIndent += warehouseStock.getValue().getPendingIndent();
1661
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 1662
					}
27701 tejbeer 1663
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
1664
					ws.setStockQty(stockQty);
1665
					ws.setStockValue(stockValue);
1666
					ws.setPendingIndent(pendingIndent);
1667
					ws.setTertiary(tertiary);
1668
					ws.setWarehouseId(0);
1669
					warehouseStockMap.put(0, ws);
27591 tejbeer 1670
 
27701 tejbeer 1671
				}
27670 tejbeer 1672
 
27701 tejbeer 1673
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
1674
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 1675
 
27701 tejbeer 1676
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
1677
 
1678
				// warehouseStock
1679
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
1680
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
1681
 
1682
				partnersBrandSaleMap = fofoStoreRepository
1683
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
1684
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1685
 
1686
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
1687
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
1688
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
1689
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
1690
					if (bpt != null) {
1691
						bpt.setAmtd(un.getUnbilledMtd());
1692
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1693
					} else {
1694
						bpt = new BrandWisePartnerSaleModel();
1695
						bpt.setBrand(un.getBrand());
1696
						bpt.setAmtd(un.getUnbilledMtd());
1697
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1698
						bpt.setLms(0);
1699
						bpt.setLmtd(0);
1700
						bpt.setMtd(0);
1701
						bpt.setMtdQty(0);
1702
						bpt.setLmtd(0);
1703
						bpt.setLmtdQty(0);
1704
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 1705
					}
26418 tejbeer 1706
				}
27701 tejbeer 1707
				accessoriesBrandSales = fofoStoreRepository
1708
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
28272 tejbeer 1709
				Set<CustomRetailer> positionRetailers = fofoIds.stream()
1710
						.map(x -> retailerService.getAllFofoRetailers().get(x)).filter(x -> x != null)
1711
						.collect(Collectors.toSet());
27931 amit.gupta 1712
				model.addAttribute("retailers", gson.toJson(positionRetailers));
1713
				model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
1714
				model.addAttribute("warehouses", getWarehouses(positionRetailers));
28442 amit.gupta 1715
			} else {
1716
				List<Position> warehousePositions = positions.stream()
1717
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1718
						.collect(Collectors.toList());
1719
				if (warehousePositions.size() > 0) {
1720
					Set<CustomRetailer> positionRetailers = new HashSet<>();
1721
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
1722
						positionRetailers.addAll(customRetailers);
1723
					});
1724
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1725
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1726
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
1727
				}
26418 tejbeer 1728
			}
1729
 
27819 tejbeer 1730
			if (positions.size() > 0) {
1731
				if (positions.stream()
1732
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1733
								|| x.getEscalationType().equals(EscalationType.L4)
1734
								|| x.getEscalationType().equals(EscalationType.L5))
1735
						.count() > 0) {
1736
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1737
				}
1738
			}
1739
 
27415 tejbeer 1740
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
28442 amit.gupta 1741
					.contains(email)) {
26029 amit.gupta 1742
				menus = menuRepository.selectAll();
1743
			} else if (positions.size() > 0) {
27108 amit.gupta 1744
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1745
					menus = menuRepository.selectAll();
27893 tejbeer 1746
				} else {
1747
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1748
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1749
					if (menuIds.size() > 0) {
1750
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1751
					}
26022 amit.gupta 1752
				}
27930 amit.gupta 1753
			}
28272 tejbeer 1754
			model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1755
 
27628 tejbeer 1756
			model.addAttribute("rctPartneStat", rctPartneStat);
1757
 
1758
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1759
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1760
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1761
 
1762
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1763
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1764
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1765
 
27594 tejbeer 1766
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1767
 
26012 amit.gupta 1768
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1769
		}
26028 amit.gupta 1770
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1771
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1772
		model.addAttribute("menu", menuList);
26012 amit.gupta 1773
		return "admin";
1774
	}
1775
 
26468 amit.gupta 1776
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1777
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1778
			throws Exception {
1779
 
1780
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1781
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1782
 
26468 amit.gupta 1783
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1784
		if (authId != 0) {
1785
			List<Integer> fofoIds = pp.get(authId);
1786
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1787
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1788
		} else {
26418 tejbeer 1789
		}
1790
 
1791
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1792
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1793
 
1794
		return "auth_user_partner_detail";
26468 amit.gupta 1795
	}
26418 tejbeer 1796
 
27545 tejbeer 1797
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1798
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1799
			throws Exception {
27701 tejbeer 1800
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1801
		String email = loginDetails.getEmailId();
1802
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1803
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1804
 
27701 tejbeer 1805
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1806
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1807
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1808
 
27545 tejbeer 1809
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1810
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1811
		if (warehouseId != 0) {
27701 tejbeer 1812
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1813
			/*
1814
			 * List<Integer> fofoIds =
1815
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1816
			 * .map(x -> x.getId()).collect(Collectors.toList());
1817
			 */
27545 tejbeer 1818
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1819
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1820
		} else {
27701 tejbeer 1821
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1822
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1823
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1824
		}
1825
 
1826
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1827
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1828
 
1829
		return "auth_user_partner_detail";
1830
	}
1831
 
27509 tejbeer 1832
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1833
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1834
			@RequestParam List<Integer> warehouseId) throws Exception {
1835
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1836
		String email = loginDetails.getEmailId();
1837
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1838
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1839
 
27701 tejbeer 1840
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1841
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1842
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1843
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1844
		if (!warehouseId.contains(0)) {
1845
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1846
		} else {
1847
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1848
			warehouseWiseBrandStock = saholicInventoryCISRepository
1849
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1850
 
1851
		}
27542 tejbeer 1852
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1853
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1854
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1855
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1856
 
27509 tejbeer 1857
		return "warehouse_brand_stock";
1858
	}
1859
 
27529 tejbeer 1860
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1861
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1862
		inventoryService.getItemAvailabilityAndIndent();
1863
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1864
		return "response";
1865
	}
1866
 
27701 tejbeer 1867
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1868
			throws Exception {
27628 tejbeer 1869
 
1870
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1871
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1872
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1873
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1874
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1875
		if (partnerStats != null) {
27701 tejbeer 1876
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1877
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1878
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1879
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1880
						.collect(Collectors.toList());
27634 tejbeer 1881
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1882
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1883
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1884
				}
27628 tejbeer 1885
 
1886
			}
27701 tejbeer 1887
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1888
					.collect(Collectors.toList());
1889
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1890
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1891
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1892
			warehouseIdAndallValues.put(0, partnerDetailModel);
1893
		}
1894
		return warehouseIdAndallValues;
1895
	}
1896
 
1897
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1898
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1899
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1900
		ObjectOutputStream oos = null;
1901
		FileOutputStream fout = null;
1902
		try {
1903
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1904
			oos = new ObjectOutputStream(fout);
1905
			oos.writeObject(partnerStats);
1906
 
1907
		} catch (Exception ex) {
1908
			ex.printStackTrace();
1909
		} finally {
1910
			if (oos != null) {
1911
				oos.close();
1912
			}
1913
		}
1914
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1915
		if (rct == null) {
1916
			rct = new ReporticoCacheTable();
1917
			rct.setTableName("partnerStat");
1918
 
1919
		}
1920
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1921
		reporticoCacheTableRepository.persist(rct);
1922
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1923
		return "response";
1924
	}
1925
 
1926
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1927
		ObjectInputStream objectinputstream = null;
1928
		Map<Integer, PartnerDetailModel> partnerStat = null;
1929
		try {
1930
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1931
			objectinputstream = new ObjectInputStream(streamIn);
1932
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1933
 
1934
			LOGGER.info("partnerStat" + partnerStat);
1935
			objectinputstream.close();
1936
 
1937
		} catch (Exception e) {
1938
			LOGGER.info("exceptionddd" + e);
1939
 
1940
			e.printStackTrace();
1941
 
1942
		} finally {
1943
			if (objectinputstream != null) {
1944
				objectinputstream.close();
1945
				LOGGER.info("clofddd" + partnerStat);
1946
 
1947
			}
1948
		}
1949
		return partnerStat;
1950
 
1951
	}
1952
 
27539 tejbeer 1953
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1954
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1955
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1956
			throws Exception {
27509 tejbeer 1957
 
1958
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1959
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1960
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1961
 
27509 tejbeer 1962
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1963
		model.addAttribute("brands", listbrands);
27538 tejbeer 1964
		model.addAttribute("listCategory", listCategory);
1965
 
27529 tejbeer 1966
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1967
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1968
		model.addAttribute("selectedCategory", category);
1969
 
27509 tejbeer 1970
		return "warehouse_brand_item_stock";
1971
	}
1972
 
27538 tejbeer 1973
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1974
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1975
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1976
			throws Exception {
27539 tejbeer 1977
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1978
		if (warehouseId.contains(0)) {
1979
			warehouseId.addAll(warehouseMap.keySet());
1980
		}
27538 tejbeer 1981
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1982
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1983
 
27538 tejbeer 1984
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1985
		model.addAttribute("warehouseMap", warehouseMap);
1986
		return "warehouse_item_details";
1987
	}
1988
 
26114 amit.gupta 1989
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1990
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1991
		positionRetailers.stream().forEach(x -> {
1992
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1993
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1994
			}
1995
		});
26114 amit.gupta 1996
		return gson.toJson(warehouses);
1997
 
1998
	}
1999
 
27556 tejbeer 2000
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 2001
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
2002
			throws Exception {
27701 tejbeer 2003
 
2004
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2005
		String email = loginDetails.getEmailId();
2006
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2007
		Set<Integer> authfofoIds = storeGuyMap.get(email);
2008
 
27670 tejbeer 2009
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 2010
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 2011
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
2012
 
2013
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 2014
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 2015
 
2016
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
2017
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
2018
			if (bpt != null) {
2019
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 2020
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 2021
			} else {
2022
				bpt = new WarehouseWiseBrandSaleModel();
2023
				bpt.setWarehouseId(un.getWarehouseId());
2024
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 2025
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 2026
				bpt.setLms(0);
2027
				bpt.setLmtd(0);
2028
				bpt.setMtd(0);
2029
				bpt.setMtdQty(0);
2030
				bpt.setLmtd(0);
2031
				bpt.setLmtdQty(0);
2032
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
2033
			}
2034
		}
27556 tejbeer 2035
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 2036
 
2037
		Set<String> brands = inventoryService.getAllTagListingBrands();
2038
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 2039
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 2040
		model.addAttribute("brands", brands);
2041
		model.addAttribute("selectedbrand", brand);
2042
		return "warehousewise_brand_partners_sale";
27556 tejbeer 2043
	}
2044
 
27594 tejbeer 2045
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
2046
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
2047
			@RequestParam String brand) throws Exception {
27701 tejbeer 2048
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2049
		String email = loginDetails.getEmailId();
2050
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2051
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 2052
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 2053
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 2054
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2055
 
2056
		Set<String> brands = inventoryService.getAllTagListingBrands();
2057
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
2058
		model.addAttribute("warehouseMap", warehouseMap);
2059
		model.addAttribute("brands", brands);
2060
		model.addAttribute("selectedbrand", brand);
2061
		return "warehousewise_accessoriesbrand_sale";
2062
	}
2063
 
27556 tejbeer 2064
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
2065
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
2066
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
2067
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 2068
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2069
		String email = loginDetails.getEmailId();
2070
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2071
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 2072
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 2073
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 2074
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
2075
 
2076
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 2077
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 2078
 
2079
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
2080
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
2081
			if (bpt != null) {
2082
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 2083
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 2084
			} else {
2085
				bpt = new WarehouseBrandWiseItemSaleModel();
2086
				bpt.setWarehouseId(un.getWarehouseId());
2087
				bpt.setItemId(un.getItemId());
2088
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 2089
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 2090
				bpt.setBrand(un.getBrand());
2091
				bpt.setModelName(un.getModelName());
2092
				bpt.setModelNumber(un.getModelNumber());
2093
				bpt.setColor(un.getColor());
2094
				bpt.setLms(0);
2095
				bpt.setLmtd(0);
2096
				bpt.setMtd(0);
2097
				bpt.setMtdQty(0);
2098
				bpt.setLmtd(0);
2099
				bpt.setLmtdQty(0);
2100
				branditemSalesMap.put(un.getItemId(), bpt);
2101
			}
2102
		}
2103
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 2104
		model.addAttribute("warehouseMap", warehouseMap);
2105
		return "warehouse_partner_itemwise_sale";
2106
	}
2107
 
27594 tejbeer 2108
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
2109
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
2110
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
2111
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 2112
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2113
		String email = loginDetails.getEmailId();
2114
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2115
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 2116
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 2117
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 2118
		model.addAttribute("branditemSales", branditemSales);
2119
		model.addAttribute("warehouseMap", warehouseMap);
2120
		return "warehouse_accessories_itemwsie_sale";
2121
	}
2122
 
26012 amit.gupta 2123
	private List<Menu> prepareMenu(List<Menu> menus) {
2124
		List<Menu> returnMenu = new ArrayList<>();
2125
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
2126
		for (Menu menu : menus) {
2127
			if (menu.get_parent() == null) {
26014 amit.gupta 2128
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 2129
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 2130
				}
2131
			} else {
26012 amit.gupta 2132
				Menu parentMenu = menu.get_parent();
2133
				if (!subMenuMap.containsKey(parentMenu)) {
2134
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 2135
				}
26012 amit.gupta 2136
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 2137
			}
2138
		}
26012 amit.gupta 2139
		subMenuMap.entrySet().stream().forEach(entry -> {
2140
			entry.getKey().setSubMenus(entry.getValue());
2141
			returnMenu.add(entry.getKey());
2142
		});
2143
		return returnMenu;
26005 amit.gupta 2144
	}
2145
 
24288 amit.gupta 2146
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 2147
	private boolean hasGift(int fofoId) {
2148
		try {
24288 amit.gupta 2149
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
2150
					.getAvailability() > 0;
24203 amit.gupta 2151
		} catch (ProfitMandiBusinessException e) {
2152
			return false;
2153
		}
2154
	}
24288 amit.gupta 2155
 
22354 ashik.ali 2156
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 2157
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 2158
		model.addAttribute("appContextPath", request.getContextPath());
2159
		return "contact-us";
2160
	}
23923 amit.gupta 2161
 
25649 tejbeer 2162
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 2163
	public String getNotificationsWithType(HttpServletRequest request,
2164
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 2165
			@RequestParam(name = "offset", defaultValue = "0") int offset,
2166
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
2167
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 2168
		int userId = 0;
2169
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
2170
		if (isAdmin) {
2171
			userId = loginDetails.getFofoId();
2172
		} else {
2173
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
2174
		}
25683 tejbeer 2175
		List<Notification> notifications = null;
2176
 
26086 tejbeer 2177
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
2178
				userId, offset, limit);
2179
		LOGGER.info("messageType" + messageType);
2180
		notifications = getNotifications(notificationCampaigns, messageType);
2181
 
25683 tejbeer 2182
		model.addAttribute("notifications", notifications);
2183
 
2184
		LOGGER.info("notifications" + notifications);
2185
		return "notification-template";
2186
	}
2187
 
2188
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
2189
			throws ProfitMandiBusinessException {
2190
		List<Notification> notifications = new ArrayList<>();
2191
		Document document = null;
2192
		if (messageType != null) {
2193
			for (NotificationCampaign notificationCampaign : nc) {
2194
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 2195
					Notification ns = new Notification();
2196
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2197
							SimpleCampaignParams.class);
2198
					Campaign campaign = new SimpleCampaign(scp);
2199
					LocalDateTime expire = campaign.getExpireTimestamp();
2200
					ns.setCid(Integer.toString(notificationCampaign.getId()));
2201
					ns.setType(campaign.getType());
2202
					ns.setMessage(campaign.getMessage());
2203
					ns.setTitle(campaign.getTitle());
25651 tejbeer 2204
					if (notificationCampaign.getDocumentId() != null) {
2205
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
2206
						ns.setDocumentName(document.getDisplayName());
2207
					}
25683 tejbeer 2208
					ns.setUrl(campaign.getUrl());
25649 tejbeer 2209
					ns.setShowImage(campaign.getShowImage());
2210
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 2211
					ns.setDocumentId(notificationCampaign.getDocumentId());
2212
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 2213
					ns.setCreated(
2214
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
2215
									* 1000);
2216
					if (LocalDateTime.now().isAfter(expire)) {
2217
						ns.setExpired(true);
2218
					} else {
2219
						ns.setExpired(false);
2220
					}
2221
					notifications.add(ns);
2222
				}
2223
			}
25683 tejbeer 2224
		} else {
2225
			for (NotificationCampaign notificationCampaign : nc) {
2226
 
2227
				Notification ns = new Notification();
2228
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2229
						SimpleCampaignParams.class);
2230
				Campaign campaign = new SimpleCampaign(scp);
2231
				LocalDateTime expire = campaign.getExpireTimestamp();
2232
				ns.setCid(Integer.toString(notificationCampaign.getId()));
2233
				ns.setType(campaign.getType());
2234
				ns.setMessage(campaign.getMessage());
2235
				ns.setTitle(campaign.getTitle());
2236
				if (notificationCampaign.getDocumentId() != null) {
2237
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
2238
					ns.setDocumentName(document.getDisplayName());
2239
				}
2240
				ns.setUrl(campaign.getUrl());
2241
				ns.setShowImage(campaign.getShowImage());
2242
				ns.setImageUrl(campaign.getImageUrl());
2243
				ns.setDocumentId(notificationCampaign.getDocumentId());
2244
				ns.setMessageType(notificationCampaign.getMessageType());
2245
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
2246
						* 1000);
2247
				if (LocalDateTime.now().isAfter(expire)) {
2248
					ns.setExpired(true);
2249
				} else {
2250
					ns.setExpired(false);
2251
				}
2252
				notifications.add(ns);
2253
			}
2254
 
25649 tejbeer 2255
		}
25683 tejbeer 2256
		return notifications;
25651 tejbeer 2257
 
2258
	}
25649 tejbeer 2259
 
25651 tejbeer 2260
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
2261
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
2262
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
2263
			throws ProfitMandiBusinessException {
2264
		Document document = documentRepository.selectById(documentId);
2265
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
2266
		if (nc.getDocumentId() == null) {
2267
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
2268
		}
2269
		if (nc.getDocumentId() != documentId) {
2270
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
2271
		}
2272
		return responseSender.ok(document);
25649 tejbeer 2273
	}
2274
 
25651 tejbeer 2275
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
2276
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
2277
			throws ProfitMandiBusinessException {
2278
 
2279
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
2280
 
2281
		if (nc.getDocumentId() == null) {
2282
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
2283
		}
2284
 
2285
		Document document = documentRepository.selectById(nc.getDocumentId());
2286
 
2287
		FileInputStream file = null;
2288
		try {
2289
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
2290
		} catch (FileNotFoundException e) {
2291
			LOGGER.error("Retailer Document file not found : ", e);
2292
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
2293
		}
2294
		// ByteArrayOutputStream byteArrayOutputStream = new
2295
		// ByteArrayOutputStream();
2296
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
2297
 
2298
		final HttpHeaders headers = new HttpHeaders();
2299
		String contentType = "";
2300
		if (document.getContentType() == ContentType.JPEG) {
2301
			contentType = "image/jpeg";
2302
		} else if (document.getContentType() == ContentType.PNG) {
2303
			contentType = "image/png";
2304
		} else if (document.getContentType() == ContentType.PDF) {
2305
			contentType = "application/pdf";
2306
		}
2307
		headers.set("Content-Type", contentType);
2308
		headers.set("Content-disposition", "inline; filename=" + document.getName());
2309
		headers.setContentLength(document.getSize());
2310
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
2311
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
2312
	}
26460 amit.gupta 2313
 
2314
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 2315
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 2316
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 2317
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
2318
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
2319
			List<Integer> authIds = l2l1.getValue();
2320
			authIds.add(l2l1.getKey());
2321
 
2322
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 2323
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 2324
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 2325
			if (!leads.isEmpty()) {
2326
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
2327
			} else {
2328
				authIdAndleadsCountMap.put(auth.getId(), 0);
2329
			}
26422 tejbeer 2330
		}
26468 amit.gupta 2331
 
26460 amit.gupta 2332
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 2333
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
2334
				.collect(Collectors.toList());
26433 tejbeer 2335
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 2336
 
26460 amit.gupta 2337
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 2338
 
26460 amit.gupta 2339
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
2340
		for (int authUserId : pp.keySet()) {
2341
			if (L2L1Mapping.keySet().contains(authUserId)) {
2342
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 2343
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 2344
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
2345
						.collect(Collectors.toList());
27632 tejbeer 2346
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 2347
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
2348
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 2349
			}
2350
		}
26997 amit.gupta 2351
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
2352
				.collect(Collectors.toList());
26468 amit.gupta 2353
		PartnerDetailModel partnerDetailModel = partnerStatsService
2354
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 2355
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 2356
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 2357
		return authIdAndallValues;
2358
	}
2359
 
27579 tejbeer 2360
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
2361
	public String getItemWiseTertiary(HttpServletRequest request,
2362
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
2363
			throws ProfitMandiBusinessException {
2364
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
2365
 
2366
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 2367
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2368
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 2369
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
2370
		return "item-wise-tertiary";
2371
	}
2372
 
27586 tejbeer 2373
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
2374
	public String getItemWiseIndent(HttpServletRequest request,
2375
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
2376
			throws ProfitMandiBusinessException {
2377
 
2378
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
2379
		model.addAttribute("unbilledOrders", unbilledOrders);
2380
 
2381
		return "item-wise-indent";
2382
	}
2383
 
27636 tejbeer 2384
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
2385
	public String getPartnerInvestment(HttpServletRequest request,
2386
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2387
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
2388
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
2389
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2390
		model.addAttribute("partnerDetailModel", partnerDetailModel);
2391
		model.addAttribute("customRetailer", customRetailer);
2392
		return "partner-investment";
2393
	}
27727 tejbeer 2394
 
27704 amit.gupta 2395
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
2396
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
2397
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
2398
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
2399
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 2400
 
27704 amit.gupta 2401
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
2402
		return "partner-pending-indent-item";
2403
	}
2404
 
27636 tejbeer 2405
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
2406
	public String getPartnerActivateStockItem(HttpServletRequest request,
2407
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2408
		List<ActivateItemModel> activateStocks = new ArrayList<>();
2409
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2410
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2411
 
2412
		for (InventoryItem inventoryItem : inventoryItems) {
2413
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
2414
			Item item = itemRepository.selectById(inventoryItem.getItemId());
2415
			ActivateItemModel aim = new ActivateItemModel();
2416
			aim.setFofoId(inventoryItem.getFofoId());
2417
			aim.setQuantity(inventoryItem.getGoodQuantity());
2418
			aim.setAmount(tagListing.getSellingPrice());
2419
			aim.setItemDescription(item.getItemDescription());
2420
			aim.setItemId(inventoryItem.getItemId());
2421
			activateStocks.add(aim);
2422
		}
2423
 
2424
		model.addAttribute("activateStocks", activateStocks);
2425
		model.addAttribute("customRetailer", customRetailer);
2426
		return "partner-activate-stock";
2427
	}
2428
 
2429
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
2430
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
2431
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2432
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2433
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2434
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
2435
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 2436
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
2437
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 2438
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2439
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 2440
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2441
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
2442
 
27636 tejbeer 2443
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
2444
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 2445
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 2446
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 2447
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
2448
 
27636 tejbeer 2449
		model.addAttribute("customRetailer", customRetailer);
2450
		return "partner-brand-mtd-sale";
2451
	}
2452
 
27637 tejbeer 2453
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
2454
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
2455
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2456
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2457
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2458
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
2459
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 2460
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
2461
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 2462
 
2463
		Double accesorieslmtdsale = fofoOrderRepository
2464
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
2465
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
2466
				.get(fofoId);
27638 tejbeer 2467
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2468
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
2469
				Optional.of(false)).get(fofoId);
2470
 
27637 tejbeer 2471
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 2472
		model.addAttribute("brandLmtdQty", brandLmtdQty);
2473
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 2474
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
2475
		model.addAttribute("customRetailer", customRetailer);
2476
		return "partner-brand-lmtd-sale";
2477
	}
2478
 
27660 tejbeer 2479
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
2480
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
2481
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2482
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2483
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2484
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2485
 
2486
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 2487
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2488
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 2489
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2490
 
27893 tejbeer 2491
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2492
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 2493
		Long accesorieslmsqty = fofoOrderRepository
2494
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 2495
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 2496
				.get(fofoId);
2497
 
2498
		model.addAttribute("brandLMSAmount", brandLMSAmount);
2499
		model.addAttribute("brandLmsQty", brandLmsQty);
2500
		model.addAttribute("accesorieslmssale", accesorieslmssale);
2501
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
2502
		model.addAttribute("customRetailer", customRetailer);
2503
		return "partner-brand-lms-sale";
2504
	}
2505
 
27640 tejbeer 2506
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
2507
	public String getPatnerInStock(HttpServletRequest request,
2508
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2509
 
2510
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2511
 
27660 tejbeer 2512
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 2513
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 2514
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 2515
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
2516
 
27660 tejbeer 2517
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
2518
				.selectInStockItemsByBrand(fofoId);
2519
 
2520
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
2521
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2522
 
2523
		model.addAttribute("stockItemMap", stockItemMap);
2524
		model.addAttribute("mobileStock", mobileStocks);
2525
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 2526
		model.addAttribute("customRetailer", customRetailer);
2527
		return "partner-instock-item";
2528
	}
2529
 
27660 tejbeer 2530
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
2531
	public String getOpenTicketByFofoId(HttpServletRequest request,
2532
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2533
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
2534
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2535
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
2536
				.collect(Collectors.toList());
2537
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
2538
 
2539
		for (TicketAssigned ticketAssign : ticketAssigns) {
2540
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
2541
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
2542
		}
2543
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
2544
		model.addAttribute("ticketAssigns", ticketAssigns);
2545
		model.addAttribute("customRetailer", customRetailer);
2546
		return "open-ticket";
2547
	}
2548
 
27893 tejbeer 2549
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
2550
	public String getPartnerSecondarySale(HttpServletRequest request,
2551
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
2552
			throws Exception {
2553
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2554
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2555
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2556
		LocalDateTime startDate = null;
2557
		LocalDateTime endDate = null;
2558
		List<InStockBrandModel> secondarySale = null;
2559
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
2560
 
2561
		if (timeValue.equals("mtd")) {
2562
			startDate = curDate.withDayOfMonth(1);
2563
			endDate = curDate.with(LocalTime.MAX);
2564
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2565
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2566
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2567
			LOGGER.info("secondarySalemtd" + secondarySale);
2568
		} else if (timeValue.equals("lmtd")) {
2569
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2570
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
2571
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2572
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2573
 
2574
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2575
			LOGGER.info("secondarySalelmtd" + secondarySale);
2576
 
2577
		} else {
2578
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2579
			endDate = curDate.withDayOfMonth(1);
2580
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2581
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2582
 
2583
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2584
			LOGGER.info("secondarySalelms" + secondarySale);
2585
 
2586
		}
2587
 
2588
		LOGGER.info("secondarySale" + secondarySale);
2589
		model.addAttribute("secondarySale", secondarySale);
2590
		model.addAttribute("secondaryItemSale", secondaryItemSale);
2591
		model.addAttribute("customRetailer", customRetailer);
2592
 
2593
		return "partner-secondary-order";
2594
	}
2595
 
21615 kshitij.so 2596
}