Subversion Repositories SmartDukaan

Rev

Rev 28446 | Rev 28451 | 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
 
28444 tejbeer 814
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
28443 tejbeer 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<>();
28444 tejbeer 821
        LOGGER.info("priceDropYearMonthModels"+priceDropYearMonthModels);
28443 tejbeer 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);
28444 tejbeer 829
 
830
		LOGGER.info("sortedMonthBrandValue"+sortedMonthBrandValue);
28443 tejbeer 831
		List<String> brands = new ArrayList<>();
832
 
833
		brands.add("Accessories");
834
		brands.add("Oppo");
835
		brands.add("Vivo");
836
		brands.add("Samsung");
837
		brands.add("Realme");
838
		brands.add("Mi");
839
		brands.add("Tecno");
840
		brands.add("Itel");
28448 tejbeer 841
 
28443 tejbeer 842
		brands.add("Nokia");
843
		for (int i = 6; i >= 1; i--) {
844
 
845
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
28444 tejbeer 846
 
847
			LOGGER.info("getStartMonth"+sortedMonthBrandValue.get(YearMonth.from(startMonth)));
28443 tejbeer 848
			Map<String, Double> valbrand = sortedMonthBrandValue.get(YearMonth.from(startMonth));
849
			for (String brand : brands) {
850
				if (valbrand != null) {
851
					if (!valbrand.containsKey(brand)) {
852
						valbrand.put(brand, 0.0);
28444 tejbeer 853
					} 
854
					else {
28443 tejbeer 855
						valbrand.put(brand, valbrand.get(brand));
856
					}
857
 
858
				} else {
859
					valbrand = new HashMap<String, Double>();
860
					valbrand.put(brand, 0.0);
861
				}
862
			}
863
 
864
			sortedMonthBrandValue.put(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)), valbrand);
865
 
866
		}
867
		Multimap<String, Map<YearMonth, Double>> brandMonthValueMap = ArrayListMultimap.create();
868
 
869
		for (Entry<YearMonth, Map<String, Double>> month : sortedMonthBrandValue.entrySet()) {
870
			for (Entry<String, Double> val : month.getValue().entrySet()) {
871
				Map<YearMonth, Double> yearValue = new HashMap<>();
872
 
873
				yearValue.put(month.getKey(), val.getValue() == null ? 0 : val.getValue());
874
 
875
				brandMonthValueMap.put(val.getKey(), yearValue);
876
 
877
			}
878
		}
879
 
880
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
881
 
882
		for (String brand : brands) {
883
			Collection<Map<YearMonth, Double>> coll = brandMonthValueMap.get(brand);
884
 
885
			List<Double> valueList = new ArrayList<>();
886
			for (Map<YearMonth, Double> col : coll) {
887
 
888
				valueList.addAll(col.values());
889
			}
890
			sortedBrandValue.put(brand, valueList);
891
		}
892
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
893
 
894
		for (int i = 6; i >= 1; i--) {
895
 
896
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
897
			labels.add(startMonth.format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
898
		}
899
 
900
		List<DatasetModel> datasets = new ArrayList<>();
901
		List<String> colorList = new ArrayList<>();
902
		colorList.add("papayawhip");
903
		colorList.add("darkgreen");
904
		colorList.add("dodgerblue");
905
		colorList.add("darkblue");
906
		colorList.add("gold");
907
 
908
		colorList.add("coral");
909
 
910
		colorList.add("steelblue");
911
		colorList.add("red");
28448 tejbeer 912
 
28443 tejbeer 913
		colorList.add("midnightblue");
914
		colorList.add("cornsilk");
915
 
916
		List<String> borderList = new ArrayList<>();
917
		borderList.add("pink");
918
		borderList.add("mediumseagreen");
919
		borderList.add("lightblue");
920
		borderList.add("#0000cd");
921
		borderList.add("#f7e98e");
922
 
923
		borderList.add("#ff8c69");
924
 
925
		borderList.add("#0000cd");
926
		borderList.add("lightsalmon");
28448 tejbeer 927
 
28443 tejbeer 928
		borderList.add("#0000cd");
929
		borderList.add("cornsilk");
930
 
931
		int i = 0;
932
 
933
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
28448 tejbeer 934
 
28443 tejbeer 935
			DatasetModel purchaseModel = new DatasetModel();
936
			purchaseModel.setLabel(brandValue.getKey());
937
			purchaseModel.setBackgroundColor(colorList.get(i));
938
			if (brandValue.getValue().isEmpty()) {
939
 
940
				purchaseModel.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
941
			} else {
942
				purchaseModel.setData(brandValue.getValue());
943
			}
944
			purchaseModel.setType("line");
945
			purchaseModel.setOrder(1);
946
			purchaseModel.setFill("false");
947
			purchaseModel.setBorderColor(borderList.get(i));
948
			datasets.add(purchaseModel);
949
 
950
			i++;
951
		}
952
 
953
		DataModel dm = new DataModel();
954
		dm.setDatasets(datasets);
955
		dm.setLabels(labels);
956
 
957
		LegendModel lm = new LegendModel();
958
		lm.setPosition("top");
959
 
960
		Tooltips tooltips = new Tooltips();
961
		tooltips.setBodyFontSize(15);
962
		tooltips.setTitleFontSize(15);
963
		tooltips.setMode("index");
964
		tooltips.setIntersect(false);
28446 tejbeer 965
		tooltips.setBackgroundColor("rgba(0, 0, 0, .5)");
28443 tejbeer 966
 
967
		HoverModel hover = new HoverModel();
968
		hover.setIntersect(false);
969
		hover.setMode("index");
970
 
971
		TitleModel tm = new TitleModel();
972
		tm.setText("Brand Wise Monthly Price-Drop");
973
		tm.setDisplay(true);
974
		tm.setFontSize(20);
975
		tm.setFontColor("#111");
976
 
977
		OptionsModel om = new OptionsModel();
978
		om.setResponsive(true);
979
		om.setLegend(lm);
980
		om.setTitle(tm);
981
		om.setTooltips(tooltips);
982
		om.setHover(hover);
983
 
984
		ChartModel cm = new ChartModel();
985
 
986
		cm.setType("line");
987
		cm.setData(dm);
988
		cm.setOptions(om);
989
 
990
		LOGGER.info("cm" + cm);
991
 
992
		return cm;
993
	}
994
 
27884 tejbeer 995
	private ChartInvestmentModel getInvestmentChart(int fofoId) throws ProfitMandiBusinessException {
996
		PartnerDailyInvestment investment = partnerInvestmentService.getInvestment(fofoId, 0);
27900 tejbeer 997
 
27884 tejbeer 998
		Map<String, Float> investmentWalletAmount = new HashMap<>();
999
		investmentWalletAmount.put("Wallet", investment.getWalletAmount());
28272 tejbeer 1000
		investmentWalletAmount.put("InStocks", investment.getInStockAmount() - investment.getActivatedStockAmount());
27900 tejbeer 1001
		investmentWalletAmount.put("Unbilled Order", investment.getUnbilledAmount());
27884 tejbeer 1002
		investmentWalletAmount.put("GrnPending", investment.getGrnPendingAmount());
1003
		investmentWalletAmount.put("ReturnInTransit", investment.getReturnInTransitAmount());
1004
 
27900 tejbeer 1005
		if (investment.getShortInvestment() > 0) {
1006
			investmentWalletAmount.put("Short Investment", investment.getShortInvestment());
1007
		}
1008
 
27884 tejbeer 1009
		ChartInvestmentModel cm = new ChartInvestmentModel();
1010
 
1011
		HashSet<String> labels = new HashSet<String>();
1012
		labels.addAll(investmentWalletAmount.keySet());
1013
 
1014
		List<String> labelList = new ArrayList<>(labels);
1015
		List<String> backgroundColor = new ArrayList<>();
27900 tejbeer 1016
		List<Float> labelsValue = new ArrayList<>();
27884 tejbeer 1017
		List<Float> values = new ArrayList<>();
1018
		for (String label : labelList) {
1019
			values.add(investmentWalletAmount.get(label));
1020
			if (label.equals("Wallet")) {
1021
				backgroundColor.add("pink");
1022
			}
27900 tejbeer 1023
			if (label.equals("Short Investment")) {
1024
				backgroundColor.add("red");
1025
			}
28015 tejbeer 1026
			if (label.equals("InStocks")) {
27900 tejbeer 1027
				backgroundColor.add("#9ACD32");
27884 tejbeer 1028
			}
27900 tejbeer 1029
			if (label.equals("Unbilled Order")) {
1030
				backgroundColor.add("blue");
27884 tejbeer 1031
			}
1032
 
1033
			if (label.equals("ReturnInTransit")) {
1034
				backgroundColor.add("orange");
1035
			}
1036
			if (label.equals("GrnPending")) {
1037
				backgroundColor.add("yellow");
1038
			}
1039
 
1040
		}
1041
 
1042
		Data data = new Data();
1043
		data.setData(values);
1044
		data.setBackgroundColor(backgroundColor);
1045
		data.setLabel("DataSet 1");
1046
 
1047
		PieLables label = new PieLables();
1048
		label.setFontColor("White");
1049
		label.setFontSize(15);
1050
 
1051
		Legend legend = new Legend();
1052
		legend.setLabels(label);
1053
		legend.setPosition("left");
1054
 
1055
		List<Data> dataList = new ArrayList<>();
1056
		dataList.add(data);
1057
 
1058
		DataInvestmentModel datasets = new DataInvestmentModel();
1059
		datasets.setDatasets(dataList);
1060
		datasets.setLabels(labels);
1061
 
1062
		OptionModel om = new OptionModel();
1063
		om.setLegend(legend);
1064
		cm.setType("pie");
1065
		cm.setData(datasets);
1066
		cm.setOptions(om);
1067
 
1068
		return cm;
1069
	}
1070
 
28439 tejbeer 1071
	private ChartModel getPurchaseOrderChart(int fofoId) throws ProfitMandiBusinessException {
1072
 
1073
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1074
 
1075
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(1);
1076
 
1077
		List<SecondaryOrderBilledLmsModel> soblms = orderRepository.selectAllBilledOrderGroupByBrandFofoId(fofoId,
1078
				curDate.withDayOfMonth(1).minusMonths(6));
1079
 
1080
		LOGGER.info("soblms" + soblms);
1081
		Map<String, Map<YearMonth, Double>> brandMonthValueMap = new HashMap<>();
1082
		for (SecondaryOrderBilledLmsModel orderBilledLmsMode : soblms) {
1083
			Map<YearMonth, Double> yearMonthMap = new HashMap<>();
1084
			yearMonthMap.put(YearMonth.from(startOfMonth), (double) orderBilledLmsMode.getFirstMonthValue());
28443 tejbeer 1085
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(1)),
28439 tejbeer 1086
					(double) orderBilledLmsMode.getSecondMonthValue());
1087
 
1088
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(2)),
1089
					(double) orderBilledLmsMode.getThirdMonthValue());
1090
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(3)),
1091
					(double) orderBilledLmsMode.getFourthMonthValue());
1092
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(4)),
1093
					(double) orderBilledLmsMode.getFifthMonthValue());
1094
			yearMonthMap.put(YearMonth.from(startOfMonth.minusMonths(5)),
1095
					(double) orderBilledLmsMode.getSixthMonthValue());
1096
			Map<YearMonth, Double> sortedYearMonthMap = new TreeMap<YearMonth, Double>(yearMonthMap);
1097
			brandMonthValueMap.put(orderBilledLmsMode.getBrand(), sortedYearMonthMap);
1098
 
1099
		}
1100
		LOGGER.info("brandMonthValueMap" + brandMonthValueMap);
1101
 
1102
		List<String> brands = new ArrayList<>();
1103
		brands.add("Accessories");
1104
		brands.add("Oppo");
1105
		brands.add("Vivo");
1106
		brands.add("Samsung");
1107
		brands.add("Realme");
1108
		brands.add("Mi");
1109
		brands.add("Tecno");
1110
		brands.add("Itel");
1111
		brands.add("Lava");
1112
		brands.add("Nokia");
1113
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
1114
 
1115
		for (String brand : brands) {
1116
			Map<YearMonth, Double> coll = brandMonthValueMap.get(brand);
1117
			LOGGER.info("coll" + coll);
1118
			List<Double> valueList = new ArrayList<>();
1119
 
1120
			if (coll != null) {
1121
 
1122
				valueList.addAll(coll.values());
1123
			}
1124
			sortedBrandValue.put(brand, valueList);
1125
 
1126
		}
1127
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
28443 tejbeer 1128
 
28439 tejbeer 1129
		for (int i = 6; i >= 1; i--) {
1130
 
1131
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
1132
			labels.add(startMonth.format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
1133
 
1134
			LOGGER.info("labels" + labels);
1135
		}
1136
 
1137
		LOGGER.info("labels" + labels);
28443 tejbeer 1138
 
28439 tejbeer 1139
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
1140
		List<DatasetModel> datasets = new ArrayList<>();
1141
		List<String> colorList = new ArrayList<>();
28443 tejbeer 1142
		colorList.add("papayawhip");
28439 tejbeer 1143
		colorList.add("darkgreen");
28443 tejbeer 1144
		colorList.add("dodgerblue");
1145
		colorList.add("darkblue");
1146
		colorList.add("gold");
28439 tejbeer 1147
 
28443 tejbeer 1148
		colorList.add("coral");
28439 tejbeer 1149
 
28443 tejbeer 1150
		colorList.add("steelblue");
1151
		colorList.add("red");
28448 tejbeer 1152
		colorList.add("deeppink");
28443 tejbeer 1153
		colorList.add("midnightblue");
28439 tejbeer 1154
		colorList.add("cornsilk");
1155
 
1156
		List<String> borderList = new ArrayList<>();
1157
		borderList.add("pink");
28443 tejbeer 1158
		borderList.add("mediumseagreen");
1159
		borderList.add("lightblue");
1160
		borderList.add("#0000cd");
1161
		borderList.add("#f7e98e");
28439 tejbeer 1162
 
28443 tejbeer 1163
		borderList.add("#ff8c69");
1164
 
1165
		borderList.add("#0000cd");
1166
		borderList.add("lightsalmon");
28448 tejbeer 1167
		borderList.add("pink");
28443 tejbeer 1168
		borderList.add("#0000cd");
28439 tejbeer 1169
		borderList.add("cornsilk");
1170
 
1171
		int i = 0;
1172
 
1173
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
1174
 
1175
			DatasetModel purchaseModel = new DatasetModel();
1176
			purchaseModel.setLabel(brandValue.getKey());
28443 tejbeer 1177
			purchaseModel.setBackgroundColor(colorList.get(i));
28439 tejbeer 1178
			if (brandValue.getValue().isEmpty()) {
1179
 
1180
				purchaseModel.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
1181
			} else {
1182
				purchaseModel.setData(brandValue.getValue());
1183
			}
1184
			purchaseModel.setType("line");
1185
			purchaseModel.setOrder(1);
1186
			purchaseModel.setFill("false");
28443 tejbeer 1187
			purchaseModel.setBorderColor(borderList.get(i));
28439 tejbeer 1188
			datasets.add(purchaseModel);
1189
 
1190
			i++;
1191
		}
1192
 
1193
		DataModel dm = new DataModel();
1194
		dm.setDatasets(datasets);
1195
		dm.setLabels(labels);
1196
 
1197
		LegendModel lm = new LegendModel();
1198
		lm.setPosition("top");
1199
 
1200
		Tooltips tooltips = new Tooltips();
1201
		tooltips.setBodyFontSize(15);
1202
		tooltips.setTitleFontSize(15);
1203
		tooltips.setMode("index");
1204
		tooltips.setIntersect(false);
28446 tejbeer 1205
        tooltips.setBackgroundColor("rgba(0, 0, 0, .5)");
28439 tejbeer 1206
		HoverModel hover = new HoverModel();
1207
		hover.setIntersect(false);
1208
		hover.setMode("index");
1209
 
1210
		TitleModel tm = new TitleModel();
1211
		tm.setText("Brand Wise Monthly Purchase");
1212
		tm.setDisplay(true);
1213
		tm.setFontSize(20);
1214
		tm.setFontColor("#111");
1215
 
1216
		OptionsModel om = new OptionsModel();
1217
		om.setResponsive(true);
1218
		om.setLegend(lm);
1219
		om.setTitle(tm);
1220
		om.setTooltips(tooltips);
1221
		om.setHover(hover);
1222
 
1223
		ChartModel cm = new ChartModel();
1224
		cm.setType("line");
1225
		cm.setData(dm);
1226
		cm.setOptions(om);
1227
 
1228
		LOGGER.info("cm" + cm);
1229
 
1230
		return cm;
1231
 
1232
	}
1233
 
28430 tejbeer 1234
	private ChartModel getLmsLineChart(int fofoId) throws ProfitMandiBusinessException {
1235
 
1236
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1237
 
1238
		Map<YearMonth, Map<String, Double>> monthValueMap = new HashMap<>();
1239
 
1240
		for (int i = 1; i <= 6; i++) {
1241
 
1242
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
1243
 
1244
			Map<String, Double> lmsBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1245
					curDate.withDayOfMonth(1).minusMonths(i), curDate.withDayOfMonth(1).minusMonths(i - 1), fofoId);
1246
 
1247
			Map<Integer, Double> accesorieslmsSale = fofoOrderRepository
1248
					.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(i),
1249
							curDate.withDayOfMonth(1).minusMonths(i - 1), Optional.of(false));
1250
			LOGGER.info("lmsBrandWiseSale" + lmsBrandWiseSale);
1251
 
1252
			lmsBrandWiseSale.put("Accessories", accesorieslmsSale.get(fofoId));
1253
 
1254
			monthValueMap.put(YearMonth.from(startOfMonth), lmsBrandWiseSale);
1255
		}
1256
		LOGGER.info("monthmap" + monthValueMap);
1257
 
1258
		Map<YearMonth, Map<String, Double>> sortedMonthValueMap = new TreeMap(monthValueMap);
1259
		LOGGER.info("monthmap" + sortedMonthValueMap);
1260
 
1261
		Multimap<String, Map<YearMonth, Double>> brandMonthValueMap = ArrayListMultimap.create();
1262
 
1263
		for (Entry<YearMonth, Map<String, Double>> month : sortedMonthValueMap.entrySet()) {
1264
 
1265
			for (Entry<String, Double> val : month.getValue().entrySet()) {
1266
				Map<YearMonth, Double> yearValue = new HashMap<>();
1267
 
1268
				yearValue.put(month.getKey(), val.getValue() == null ? 0 : val.getValue());
1269
				brandMonthValueMap.put(val.getKey(), yearValue);
1270
 
1271
			}
1272
		}
1273
 
1274
		LOGGER.info("map" + brandMonthValueMap);
28435 tejbeer 1275
 
28430 tejbeer 1276
		List<String> brands = new ArrayList<>();
28435 tejbeer 1277
		brands.add("Accessories");
1278
		brands.add("Oppo");
1279
		brands.add("Vivo");
1280
		brands.add("Samsung");
1281
		brands.add("Realme");
1282
		brands.add("Mi");
1283
		brands.add("Tecno");
1284
		brands.add("Itel");
1285
		brands.add("Lava");
1286
		brands.add("Nokia");
1287
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28430 tejbeer 1288
 
1289
		for (String brand : brands) {
1290
			Collection<Map<YearMonth, Double>> coll = brandMonthValueMap.get(brand);
1291
			LOGGER.info("coll" + coll);
1292
 
1293
			List<Double> valueList = new ArrayList<>();
1294
			for (Map<YearMonth, Double> col : coll) {
1295
 
1296
				valueList.addAll(col.values());
1297
			}
1298
 
28435 tejbeer 1299
			sortedBrandValue.put(brand, valueList);
28430 tejbeer 1300
 
1301
		}
1302
 
28435 tejbeer 1303
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
28430 tejbeer 1304
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
1305
		for (Entry<YearMonth, Map<String, Double>> val : sortedMonthValueMap.entrySet()) {
1306
			labels.add(val.getKey().format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
28435 tejbeer 1307
 
28430 tejbeer 1308
		}
1309
 
1310
		List<String> labelList = new ArrayList<>(labels);
1311
		List<Double> lmsValues = new ArrayList<>();
28439 tejbeer 1312
 
28430 tejbeer 1313
		List<DatasetModel> datasets = new ArrayList<>();
1314
		List<String> colorList = new ArrayList<>();
28443 tejbeer 1315
		colorList.add("papayawhip");
1316
		colorList.add("mediumseagreen");
1317
		colorList.add("dodgerblue");
1318
		colorList.add("darkblue");
1319
		colorList.add("gold");
28439 tejbeer 1320
 
28443 tejbeer 1321
		colorList.add("coral");
28439 tejbeer 1322
 
28443 tejbeer 1323
		colorList.add("steelblue");
1324
		colorList.add("red");
28448 tejbeer 1325
		colorList.add("deeppink");
28443 tejbeer 1326
		colorList.add("midnightblue");
28432 tejbeer 1327
		colorList.add("cornsilk");
28435 tejbeer 1328
 
28430 tejbeer 1329
		List<String> borderList = new ArrayList<>();
1330
		borderList.add("pink");
28443 tejbeer 1331
		borderList.add("lawngreen");
1332
		borderList.add("lightblue");
1333
		borderList.add("#0000cd");
1334
		borderList.add("#f7e98e");
28439 tejbeer 1335
 
28443 tejbeer 1336
		borderList.add("lightcoral");
1337
 
1338
		borderList.add("#0000cd");
1339
		borderList.add("lightsalmon");
28448 tejbeer 1340
		borderList.add("pink");
28443 tejbeer 1341
		borderList.add("#0000cd");
28433 tejbeer 1342
		borderList.add("cornsilk");
28430 tejbeer 1343
 
28435 tejbeer 1344
		int i = 0;
28430 tejbeer 1345
 
28435 tejbeer 1346
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
1347
 
28430 tejbeer 1348
			DatasetModel lineLmsChart = new DatasetModel();
1349
			lineLmsChart.setLabel(brandValue.getKey());
28443 tejbeer 1350
			lineLmsChart.setBackgroundColor(colorList.get(i));
28435 tejbeer 1351
			if (brandValue.getValue().isEmpty()) {
1352
 
28439 tejbeer 1353
				lineLmsChart.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
28435 tejbeer 1354
			} else {
1355
				lineLmsChart.setData(brandValue.getValue());
1356
			}
28430 tejbeer 1357
			lineLmsChart.setType("line");
1358
			lineLmsChart.setOrder(1);
1359
			lineLmsChart.setFill("false");
28443 tejbeer 1360
			lineLmsChart.setBorderColor(borderList.get(i));
28430 tejbeer 1361
			datasets.add(lineLmsChart);
28435 tejbeer 1362
 
28430 tejbeer 1363
			i++;
1364
		}
1365
 
1366
		DataModel dm = new DataModel();
1367
		dm.setDatasets(datasets);
1368
		dm.setLabels(labels);
1369
 
1370
		LegendModel lm = new LegendModel();
1371
		lm.setPosition("top");
28435 tejbeer 1372
 
28434 tejbeer 1373
		Tooltips tooltips = new Tooltips();
1374
		tooltips.setBodyFontSize(15);
1375
		tooltips.setTitleFontSize(15);
1376
		tooltips.setMode("index");
1377
		tooltips.setIntersect(false);
28446 tejbeer 1378
		tooltips.setBackgroundColor("rgba(0, 0, 0, .5)");
1379
 
28434 tejbeer 1380
		HoverModel hover = new HoverModel();
1381
		hover.setIntersect(false);
1382
		hover.setMode("index");
28435 tejbeer 1383
 
28430 tejbeer 1384
		TitleModel tm = new TitleModel();
1385
		tm.setText("Brand Wise LMS");
1386
		tm.setDisplay(true);
28434 tejbeer 1387
		tm.setFontSize(20);
28435 tejbeer 1388
		tm.setFontColor("#111");
1389
 
1390
		OptionsModel om = new OptionsModel();
28430 tejbeer 1391
		om.setResponsive(true);
1392
		om.setLegend(lm);
1393
		om.setTitle(tm);
28434 tejbeer 1394
		om.setTooltips(tooltips);
1395
		om.setHover(hover);
28430 tejbeer 1396
 
1397
		ChartModel cm = new ChartModel();
1398
		cm.setType("line");
1399
		cm.setData(dm);
1400
		cm.setOptions(om);
1401
 
1402
		LOGGER.info("cm" + cm);
1403
 
1404
		return cm;
1405
 
1406
	}
1407
 
26055 tejbeer 1408
	private ChartModel getBrandChart(int fofoId) {
1409
 
1410
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1411
 
1412
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
1413
 
1414
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
1415
 
27900 tejbeer 1416
		Map<String, Double> brandwisesale = fofoOrderItemRepository
28435 tejbeer 1417
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 1418
 
27900 tejbeer 1419
		LOGGER.info("brandwisesale" + brandwisesale);
27884 tejbeer 1420
 
26244 tejbeer 1421
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
28435 tejbeer 1422
				fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27900 tejbeer 1423
		brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
28272 tejbeer 1424
 
27884 tejbeer 1425
		Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
28435 tejbeer 1426
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
1427
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
27900 tejbeer 1428
 
27978 tejbeer 1429
		activatedImeisWithSellingPriceMTD.put("Lava", brandwisesale.get("Lava"));
1430
 
27884 tejbeer 1431
		Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
28435 tejbeer 1432
				.selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
1433
						curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
1434
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26055 tejbeer 1435
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
28435 tejbeer 1436
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27978 tejbeer 1437
		activatedImeisWithSellingPriceLMTD.put("Lava", lmtdBrandWiseSale.get("Lava"));
26055 tejbeer 1438
 
26244 tejbeer 1439
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
28435 tejbeer 1440
				fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1441
				Optional.of(false));
27884 tejbeer 1442
 
1443
		lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));
1444
 
26055 tejbeer 1445
		ChartModel cm = new ChartModel();
1446
 
28435 tejbeer 1447
		HashSet<String> labels = new HashSet<String>();
1448
		labels.addAll(brandwisesale.keySet());
1449
		labels.addAll(lmtdBrandWiseSale.keySet());
26055 tejbeer 1450
 
28435 tejbeer 1451
		List<String> labelList = new ArrayList<>(labels);
27884 tejbeer 1452
 
28435 tejbeer 1453
		List<Double> mtdActivatedImeisValues = new ArrayList<>();
27884 tejbeer 1454
 
28435 tejbeer 1455
		List<Double> mtdValues = new ArrayList<>();
1456
		List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
1457
		List<Double> lmtdActivatedImeisValues = new ArrayList<>();
1458
		List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
1459
		List<Double> lmtdValues = new ArrayList<>();
1460
		for (String label : labelList) {
1461
			mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
1462
					: activatedImeisWithSellingPriceMTD.get(label));
1463
			lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
1464
					: activatedImeisWithSellingPriceLMTD.get(label));
26055 tejbeer 1465
 
28435 tejbeer 1466
			mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
1467
			if (brandwisesale.get(label) != null) {
1468
				mtdUnActivatedImeisValues
1469
						.add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
1470
								: activatedImeisWithSellingPriceMTD.get(label)));
1471
			} else {
1472
				mtdUnActivatedImeisValues.add(0.0);
1473
			}
1474
			if (lmtdBrandWiseSale.get(label) != null) {
1475
				lmtdUnActivatedImeisValues
1476
						.add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
1477
								: activatedImeisWithSellingPriceLMTD.get(label)));
1478
			} else {
1479
				lmtdUnActivatedImeisValues.add(0.0);
1480
			}
26055 tejbeer 1481
 
28435 tejbeer 1482
			lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
1483
		}
1484
		DatasetModel dsmtotal = new DatasetModel();
1485
		dsmtotal.setLabel("MTD");
1486
		dsmtotal.setBackgroundColor("blue");
1487
		dsmtotal.setBorderColor("blue");
1488
		dsmtotal.setData(mtdValues);
1489
		dsmtotal.setStack("stack0");
1490
		dsmtotal.setOrder(1);
26055 tejbeer 1491
 
28435 tejbeer 1492
		DatasetModel dsmUnactivated = new DatasetModel();
1493
		dsmUnactivated.setLabel("MTD Unactivated");
1494
		dsmUnactivated.setBackgroundColor("red");
1495
		dsmUnactivated.setBorderColor("red");
1496
		dsmUnactivated.setData(mtdUnActivatedImeisValues);
1497
		dsmUnactivated.setStack("stack0");
1498
		dsmUnactivated.setOrder(1);
27884 tejbeer 1499
 
28435 tejbeer 1500
		LOGGER.info("mtdValuesMoney" + mtdValues);
27884 tejbeer 1501
 
28435 tejbeer 1502
		DatasetModel mtdActivatedImeis = new DatasetModel();
1503
		mtdActivatedImeis.setLabel("MTD Activation");
1504
		mtdActivatedImeis.setBorderColor("#00008b");
1505
		mtdActivatedImeis.setData(mtdActivatedImeisValues);
1506
		mtdActivatedImeis.setBackgroundColor("#00008b");
1507
		mtdActivatedImeis.setStack("stack0");
1508
		mtdActivatedImeis.setOrder(1);
27884 tejbeer 1509
 
28435 tejbeer 1510
		DatasetModel lmtddsmtotal = new DatasetModel();
1511
		lmtddsmtotal.setLabel("LMTD");
1512
		lmtddsmtotal.setBackgroundColor("blue");
1513
		lmtddsmtotal.setData(lmtdValues);
1514
		lmtddsmtotal.setBorderColor("blue");
1515
		lmtddsmtotal.setStack("stack1");
1516
		lmtddsmtotal.setOrder(1);
27884 tejbeer 1517
 
28435 tejbeer 1518
		DatasetModel lmtdUnActivated = new DatasetModel();
1519
		lmtdUnActivated.setLabel("LMTD Unactivation");
1520
		lmtdUnActivated.setBackgroundColor("red");
1521
		lmtdUnActivated.setBorderColor("red");
1522
		lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
1523
		lmtdUnActivated.setStack("stack1");
1524
		lmtdUnActivated.setOrder(1);
27884 tejbeer 1525
 
28435 tejbeer 1526
		DatasetModel LmtdActivatedImeis = new DatasetModel();
1527
		LmtdActivatedImeis.setLabel("LMTD Activation");
1528
		LmtdActivatedImeis.setBackgroundColor("#87ceeb");
1529
		LmtdActivatedImeis.setBorderColor("#87ceeb");
1530
		LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
1531
		LmtdActivatedImeis.setStack("stack1");
1532
		LmtdActivatedImeis.setOrder(1);
27930 amit.gupta 1533
 
28435 tejbeer 1534
		DatasetModel linemtdChart = new DatasetModel();
1535
		linemtdChart.setLabel("MTD");
1536
		linemtdChart.setBackgroundColor("#006400");
1537
		linemtdChart.setBorderColor("#006400");
1538
		linemtdChart.setData(mtdValues);
1539
		linemtdChart.setType("line");
1540
		linemtdChart.setOrder(2);
1541
		linemtdChart.setFill("false");
27930 amit.gupta 1542
 
28435 tejbeer 1543
		DatasetModel lineLmtdChart = new DatasetModel();
1544
		lineLmtdChart.setLabel("LMTD");
1545
		lineLmtdChart.setBackgroundColor("hotpink");
1546
		lineLmtdChart.setBorderColor("hotpink");
1547
		lineLmtdChart.setData(lmtdValues);
1548
		lineLmtdChart.setType("line");
1549
		lineLmtdChart.setOrder(3);
1550
		lineLmtdChart.setFill("false");
27930 amit.gupta 1551
 
28435 tejbeer 1552
		List<DatasetModel> datasets = new ArrayList<>();
1553
		datasets.add(mtdActivatedImeis);
1554
		datasets.add(dsmUnactivated);
1555
		datasets.add(LmtdActivatedImeis);
1556
		datasets.add(lmtdUnActivated);
1557
		datasets.add(linemtdChart);
1558
		datasets.add(lineLmtdChart);
27884 tejbeer 1559
 
28435 tejbeer 1560
		DataModel dm = new DataModel();
1561
		dm.setDatasets(datasets);
1562
		dm.setLabels(labels);
27884 tejbeer 1563
 
28435 tejbeer 1564
		Tooltips tooltips = new Tooltips();
1565
		tooltips.setBodyFontSize(10);
1566
		tooltips.setTitleFontSize(10);
1567
		tooltips.setMode("index");
1568
		tooltips.setIntersect(false);
28446 tejbeer 1569
		tooltips.setBackgroundColor("rgba(0, 0, 0, .5)");
28435 tejbeer 1570
		HoverModel hover = new HoverModel();
1571
		hover.setIntersect(false);
1572
		hover.setMode("index");
26055 tejbeer 1573
 
28435 tejbeer 1574
		LegendModel lm = new LegendModel();
1575
		lm.setPosition("top");
26055 tejbeer 1576
 
28435 tejbeer 1577
		TitleModel tm = new TitleModel();
1578
		tm.setText("Brand Wise Sales");
1579
		tm.setDisplay(true);
1580
		tm.setFontSize(20);
1581
		tm.setFontColor("#111");
27884 tejbeer 1582
 
28435 tejbeer 1583
		List<Axis> xAxes = new ArrayList<>();
1584
		Axis xAxis = new Axis();
1585
		xAxis.setStacked(true);
1586
		xAxes.add(xAxis);
27884 tejbeer 1587
 
28435 tejbeer 1588
		List<Axis> yAxes = new ArrayList<>();
1589
		Axis yAxis = new Axis();
1590
		yAxis.setStacked(false);
1591
		yAxes.add(yAxis);
27884 tejbeer 1592
 
28435 tejbeer 1593
		ScalesModel sm = new ScalesModel();
1594
		sm.setxAxes(xAxes);
26055 tejbeer 1595
 
28435 tejbeer 1596
		OptionsModel om = new OptionsModel();
1597
		om.setLegend(lm);
1598
		om.setTitle(tm);
1599
		om.setScales(sm);
1600
		om.setHover(hover);
1601
		om.setTooltips(tooltips);
26055 tejbeer 1602
 
28435 tejbeer 1603
		cm.setType("bar");
1604
		cm.setData(dm);
1605
		cm.setOptions(om);
27884 tejbeer 1606
 
28435 tejbeer 1607
		LOGGER.info("cm" + cm);
26055 tejbeer 1608
 
28435 tejbeer 1609
		return cm;
26055 tejbeer 1610
 
28435 tejbeer 1611
	}
1612
 
26418 tejbeer 1613
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 1614
		List<Menu> menus = null;
26011 amit.gupta 1615
		try {
1616
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1617
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 1618
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 1619
			ReporticoCacheTable rctSaholic = null;
1620
			ReporticoCacheTable rctPartneStat = null;
1621
 
27509 tejbeer 1622
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 1623
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
1624
 
27509 tejbeer 1625
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 1626
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 1627
 
27670 tejbeer 1628
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 1629
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 1630
 
27819 tejbeer 1631
			Map<AuthUser, Long> authUserTicketCount = null;
1632
 
27539 tejbeer 1633
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
1634
				wm.put(entry.getKey(), entry.getValue());
1635
			}
1636
 
1637
			wm.put(0, "Total Values");
1638
			long stockValue = 0;
1639
			long stockQty = 0;
1640
			long pendingIndent = 0;
27542 tejbeer 1641
			long tertiary = 0;
26418 tejbeer 1642
 
27701 tejbeer 1643
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 1644
 
27701 tejbeer 1645
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 1646
			if (emails.contains(authUser.getEmailId())) {
1647
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
27930 amit.gupta 1648
				LOGGER.info("fofoIds" + fofoIds);
27727 tejbeer 1649
			}
27556 tejbeer 1650
 
27701 tejbeer 1651
			if (fofoIds != null) {
27539 tejbeer 1652
 
27701 tejbeer 1653
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1654
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
1655
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
1656
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
1657
				// warehouseStock
1658
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
1659
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1660
 
1661
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1662
 
1663
				if (!warehouseStockMap.isEmpty()) {
1664
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
1665
						stockValue += warehouseStock.getValue().getStockValue();
1666
						stockQty += warehouseStock.getValue().getStockQty();
1667
						pendingIndent += warehouseStock.getValue().getPendingIndent();
1668
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 1669
					}
27701 tejbeer 1670
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
1671
					ws.setStockQty(stockQty);
1672
					ws.setStockValue(stockValue);
1673
					ws.setPendingIndent(pendingIndent);
1674
					ws.setTertiary(tertiary);
1675
					ws.setWarehouseId(0);
1676
					warehouseStockMap.put(0, ws);
27591 tejbeer 1677
 
27701 tejbeer 1678
				}
27670 tejbeer 1679
 
27701 tejbeer 1680
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
1681
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 1682
 
27701 tejbeer 1683
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
1684
 
1685
				// warehouseStock
1686
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
1687
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
1688
 
1689
				partnersBrandSaleMap = fofoStoreRepository
1690
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
1691
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1692
 
1693
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
1694
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
1695
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
1696
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
1697
					if (bpt != null) {
1698
						bpt.setAmtd(un.getUnbilledMtd());
1699
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1700
					} else {
1701
						bpt = new BrandWisePartnerSaleModel();
1702
						bpt.setBrand(un.getBrand());
1703
						bpt.setAmtd(un.getUnbilledMtd());
1704
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1705
						bpt.setLms(0);
1706
						bpt.setLmtd(0);
1707
						bpt.setMtd(0);
1708
						bpt.setMtdQty(0);
1709
						bpt.setLmtd(0);
1710
						bpt.setLmtdQty(0);
1711
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 1712
					}
26418 tejbeer 1713
				}
27701 tejbeer 1714
				accessoriesBrandSales = fofoStoreRepository
1715
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
28272 tejbeer 1716
				Set<CustomRetailer> positionRetailers = fofoIds.stream()
1717
						.map(x -> retailerService.getAllFofoRetailers().get(x)).filter(x -> x != null)
1718
						.collect(Collectors.toSet());
27931 amit.gupta 1719
				model.addAttribute("retailers", gson.toJson(positionRetailers));
1720
				model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
1721
				model.addAttribute("warehouses", getWarehouses(positionRetailers));
28442 amit.gupta 1722
			} else {
1723
				List<Position> warehousePositions = positions.stream()
1724
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1725
						.collect(Collectors.toList());
1726
				if (warehousePositions.size() > 0) {
1727
					Set<CustomRetailer> positionRetailers = new HashSet<>();
1728
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
1729
						positionRetailers.addAll(customRetailers);
1730
					});
1731
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1732
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1733
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
1734
				}
26418 tejbeer 1735
			}
1736
 
27819 tejbeer 1737
			if (positions.size() > 0) {
1738
				if (positions.stream()
1739
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1740
								|| x.getEscalationType().equals(EscalationType.L4)
1741
								|| x.getEscalationType().equals(EscalationType.L5))
1742
						.count() > 0) {
1743
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1744
				}
1745
			}
1746
 
27415 tejbeer 1747
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
28442 amit.gupta 1748
					.contains(email)) {
26029 amit.gupta 1749
				menus = menuRepository.selectAll();
1750
			} else if (positions.size() > 0) {
27108 amit.gupta 1751
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1752
					menus = menuRepository.selectAll();
27893 tejbeer 1753
				} else {
1754
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1755
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1756
					if (menuIds.size() > 0) {
1757
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1758
					}
26022 amit.gupta 1759
				}
27930 amit.gupta 1760
			}
28272 tejbeer 1761
			model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1762
 
27628 tejbeer 1763
			model.addAttribute("rctPartneStat", rctPartneStat);
1764
 
1765
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1766
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1767
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1768
 
1769
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1770
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1771
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1772
 
27594 tejbeer 1773
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1774
 
26012 amit.gupta 1775
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1776
		}
26028 amit.gupta 1777
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1778
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1779
		model.addAttribute("menu", menuList);
26012 amit.gupta 1780
		return "admin";
1781
	}
1782
 
26468 amit.gupta 1783
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1784
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1785
			throws Exception {
1786
 
1787
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1788
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1789
 
26468 amit.gupta 1790
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1791
		if (authId != 0) {
1792
			List<Integer> fofoIds = pp.get(authId);
1793
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1794
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1795
		} else {
26418 tejbeer 1796
		}
1797
 
1798
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1799
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1800
 
1801
		return "auth_user_partner_detail";
26468 amit.gupta 1802
	}
26418 tejbeer 1803
 
27545 tejbeer 1804
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1805
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1806
			throws Exception {
27701 tejbeer 1807
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1808
		String email = loginDetails.getEmailId();
1809
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1810
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1811
 
27701 tejbeer 1812
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1813
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1814
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1815
 
27545 tejbeer 1816
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1817
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1818
		if (warehouseId != 0) {
27701 tejbeer 1819
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1820
			/*
1821
			 * List<Integer> fofoIds =
1822
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1823
			 * .map(x -> x.getId()).collect(Collectors.toList());
1824
			 */
27545 tejbeer 1825
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1826
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1827
		} else {
27701 tejbeer 1828
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1829
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1830
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1831
		}
1832
 
1833
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1834
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1835
 
1836
		return "auth_user_partner_detail";
1837
	}
1838
 
27509 tejbeer 1839
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1840
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1841
			@RequestParam List<Integer> warehouseId) throws Exception {
1842
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1843
		String email = loginDetails.getEmailId();
1844
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1845
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1846
 
27701 tejbeer 1847
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1848
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1849
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1850
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1851
		if (!warehouseId.contains(0)) {
1852
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1853
		} else {
1854
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1855
			warehouseWiseBrandStock = saholicInventoryCISRepository
1856
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1857
 
1858
		}
27542 tejbeer 1859
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1860
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1861
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1862
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1863
 
27509 tejbeer 1864
		return "warehouse_brand_stock";
1865
	}
1866
 
27529 tejbeer 1867
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1868
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1869
		inventoryService.getItemAvailabilityAndIndent();
1870
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1871
		return "response";
1872
	}
1873
 
27701 tejbeer 1874
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1875
			throws Exception {
27628 tejbeer 1876
 
1877
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1878
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1879
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1880
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1881
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1882
		if (partnerStats != null) {
27701 tejbeer 1883
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1884
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1885
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1886
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1887
						.collect(Collectors.toList());
27634 tejbeer 1888
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1889
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1890
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1891
				}
27628 tejbeer 1892
 
1893
			}
27701 tejbeer 1894
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1895
					.collect(Collectors.toList());
1896
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1897
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1898
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1899
			warehouseIdAndallValues.put(0, partnerDetailModel);
1900
		}
1901
		return warehouseIdAndallValues;
1902
	}
1903
 
1904
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1905
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1906
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1907
		ObjectOutputStream oos = null;
1908
		FileOutputStream fout = null;
1909
		try {
1910
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1911
			oos = new ObjectOutputStream(fout);
1912
			oos.writeObject(partnerStats);
1913
 
1914
		} catch (Exception ex) {
1915
			ex.printStackTrace();
1916
		} finally {
1917
			if (oos != null) {
1918
				oos.close();
1919
			}
1920
		}
1921
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1922
		if (rct == null) {
1923
			rct = new ReporticoCacheTable();
1924
			rct.setTableName("partnerStat");
1925
 
1926
		}
1927
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1928
		reporticoCacheTableRepository.persist(rct);
1929
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1930
		return "response";
1931
	}
1932
 
1933
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1934
		ObjectInputStream objectinputstream = null;
1935
		Map<Integer, PartnerDetailModel> partnerStat = null;
1936
		try {
1937
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1938
			objectinputstream = new ObjectInputStream(streamIn);
1939
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1940
 
1941
			LOGGER.info("partnerStat" + partnerStat);
1942
			objectinputstream.close();
1943
 
1944
		} catch (Exception e) {
1945
			LOGGER.info("exceptionddd" + e);
1946
 
1947
			e.printStackTrace();
1948
 
1949
		} finally {
1950
			if (objectinputstream != null) {
1951
				objectinputstream.close();
1952
				LOGGER.info("clofddd" + partnerStat);
1953
 
1954
			}
1955
		}
1956
		return partnerStat;
1957
 
1958
	}
1959
 
27539 tejbeer 1960
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1961
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1962
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1963
			throws Exception {
27509 tejbeer 1964
 
1965
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1966
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1967
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1968
 
27509 tejbeer 1969
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1970
		model.addAttribute("brands", listbrands);
27538 tejbeer 1971
		model.addAttribute("listCategory", listCategory);
1972
 
27529 tejbeer 1973
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1974
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1975
		model.addAttribute("selectedCategory", category);
1976
 
27509 tejbeer 1977
		return "warehouse_brand_item_stock";
1978
	}
1979
 
27538 tejbeer 1980
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1981
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1982
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1983
			throws Exception {
27539 tejbeer 1984
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1985
		if (warehouseId.contains(0)) {
1986
			warehouseId.addAll(warehouseMap.keySet());
1987
		}
27538 tejbeer 1988
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1989
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1990
 
27538 tejbeer 1991
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1992
		model.addAttribute("warehouseMap", warehouseMap);
1993
		return "warehouse_item_details";
1994
	}
1995
 
26114 amit.gupta 1996
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1997
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1998
		positionRetailers.stream().forEach(x -> {
1999
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 2000
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
2001
			}
2002
		});
26114 amit.gupta 2003
		return gson.toJson(warehouses);
2004
 
2005
	}
2006
 
27556 tejbeer 2007
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 2008
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
2009
			throws Exception {
27701 tejbeer 2010
 
2011
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2012
		String email = loginDetails.getEmailId();
2013
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2014
		Set<Integer> authfofoIds = storeGuyMap.get(email);
2015
 
27670 tejbeer 2016
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 2017
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 2018
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
2019
 
2020
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 2021
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 2022
 
2023
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
2024
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
2025
			if (bpt != null) {
2026
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 2027
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 2028
			} else {
2029
				bpt = new WarehouseWiseBrandSaleModel();
2030
				bpt.setWarehouseId(un.getWarehouseId());
2031
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 2032
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 2033
				bpt.setLms(0);
2034
				bpt.setLmtd(0);
2035
				bpt.setMtd(0);
2036
				bpt.setMtdQty(0);
2037
				bpt.setLmtd(0);
2038
				bpt.setLmtdQty(0);
2039
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
2040
			}
2041
		}
27556 tejbeer 2042
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 2043
 
2044
		Set<String> brands = inventoryService.getAllTagListingBrands();
2045
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 2046
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 2047
		model.addAttribute("brands", brands);
2048
		model.addAttribute("selectedbrand", brand);
2049
		return "warehousewise_brand_partners_sale";
27556 tejbeer 2050
	}
2051
 
27594 tejbeer 2052
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
2053
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
2054
			@RequestParam String brand) throws Exception {
27701 tejbeer 2055
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2056
		String email = loginDetails.getEmailId();
2057
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2058
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 2059
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 2060
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 2061
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2062
 
2063
		Set<String> brands = inventoryService.getAllTagListingBrands();
2064
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
2065
		model.addAttribute("warehouseMap", warehouseMap);
2066
		model.addAttribute("brands", brands);
2067
		model.addAttribute("selectedbrand", brand);
2068
		return "warehousewise_accessoriesbrand_sale";
2069
	}
2070
 
27556 tejbeer 2071
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
2072
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
2073
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
2074
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 2075
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2076
		String email = loginDetails.getEmailId();
2077
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2078
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 2079
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 2080
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 2081
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
2082
 
2083
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 2084
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 2085
 
2086
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
2087
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
2088
			if (bpt != null) {
2089
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 2090
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 2091
			} else {
2092
				bpt = new WarehouseBrandWiseItemSaleModel();
2093
				bpt.setWarehouseId(un.getWarehouseId());
2094
				bpt.setItemId(un.getItemId());
2095
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 2096
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 2097
				bpt.setBrand(un.getBrand());
2098
				bpt.setModelName(un.getModelName());
2099
				bpt.setModelNumber(un.getModelNumber());
2100
				bpt.setColor(un.getColor());
2101
				bpt.setLms(0);
2102
				bpt.setLmtd(0);
2103
				bpt.setMtd(0);
2104
				bpt.setMtdQty(0);
2105
				bpt.setLmtd(0);
2106
				bpt.setLmtdQty(0);
2107
				branditemSalesMap.put(un.getItemId(), bpt);
2108
			}
2109
		}
2110
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 2111
		model.addAttribute("warehouseMap", warehouseMap);
2112
		return "warehouse_partner_itemwise_sale";
2113
	}
2114
 
27594 tejbeer 2115
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
2116
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
2117
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
2118
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 2119
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2120
		String email = loginDetails.getEmailId();
2121
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2122
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 2123
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 2124
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 2125
		model.addAttribute("branditemSales", branditemSales);
2126
		model.addAttribute("warehouseMap", warehouseMap);
2127
		return "warehouse_accessories_itemwsie_sale";
2128
	}
2129
 
26012 amit.gupta 2130
	private List<Menu> prepareMenu(List<Menu> menus) {
2131
		List<Menu> returnMenu = new ArrayList<>();
2132
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
2133
		for (Menu menu : menus) {
2134
			if (menu.get_parent() == null) {
26014 amit.gupta 2135
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 2136
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 2137
				}
2138
			} else {
26012 amit.gupta 2139
				Menu parentMenu = menu.get_parent();
2140
				if (!subMenuMap.containsKey(parentMenu)) {
2141
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 2142
				}
26012 amit.gupta 2143
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 2144
			}
2145
		}
26012 amit.gupta 2146
		subMenuMap.entrySet().stream().forEach(entry -> {
2147
			entry.getKey().setSubMenus(entry.getValue());
2148
			returnMenu.add(entry.getKey());
2149
		});
2150
		return returnMenu;
26005 amit.gupta 2151
	}
2152
 
24288 amit.gupta 2153
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 2154
	private boolean hasGift(int fofoId) {
2155
		try {
24288 amit.gupta 2156
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
2157
					.getAvailability() > 0;
24203 amit.gupta 2158
		} catch (ProfitMandiBusinessException e) {
2159
			return false;
2160
		}
2161
	}
24288 amit.gupta 2162
 
22354 ashik.ali 2163
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 2164
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 2165
		model.addAttribute("appContextPath", request.getContextPath());
2166
		return "contact-us";
2167
	}
23923 amit.gupta 2168
 
25649 tejbeer 2169
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 2170
	public String getNotificationsWithType(HttpServletRequest request,
2171
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 2172
			@RequestParam(name = "offset", defaultValue = "0") int offset,
2173
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
2174
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 2175
		int userId = 0;
2176
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
2177
		if (isAdmin) {
2178
			userId = loginDetails.getFofoId();
2179
		} else {
2180
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
2181
		}
25683 tejbeer 2182
		List<Notification> notifications = null;
2183
 
26086 tejbeer 2184
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
2185
				userId, offset, limit);
2186
		LOGGER.info("messageType" + messageType);
2187
		notifications = getNotifications(notificationCampaigns, messageType);
2188
 
25683 tejbeer 2189
		model.addAttribute("notifications", notifications);
2190
 
2191
		LOGGER.info("notifications" + notifications);
2192
		return "notification-template";
2193
	}
2194
 
2195
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
2196
			throws ProfitMandiBusinessException {
2197
		List<Notification> notifications = new ArrayList<>();
2198
		Document document = null;
2199
		if (messageType != null) {
2200
			for (NotificationCampaign notificationCampaign : nc) {
2201
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 2202
					Notification ns = new Notification();
2203
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2204
							SimpleCampaignParams.class);
2205
					Campaign campaign = new SimpleCampaign(scp);
2206
					LocalDateTime expire = campaign.getExpireTimestamp();
2207
					ns.setCid(Integer.toString(notificationCampaign.getId()));
2208
					ns.setType(campaign.getType());
2209
					ns.setMessage(campaign.getMessage());
2210
					ns.setTitle(campaign.getTitle());
25651 tejbeer 2211
					if (notificationCampaign.getDocumentId() != null) {
2212
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
2213
						ns.setDocumentName(document.getDisplayName());
2214
					}
25683 tejbeer 2215
					ns.setUrl(campaign.getUrl());
25649 tejbeer 2216
					ns.setShowImage(campaign.getShowImage());
2217
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 2218
					ns.setDocumentId(notificationCampaign.getDocumentId());
2219
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 2220
					ns.setCreated(
2221
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
2222
									* 1000);
2223
					if (LocalDateTime.now().isAfter(expire)) {
2224
						ns.setExpired(true);
2225
					} else {
2226
						ns.setExpired(false);
2227
					}
2228
					notifications.add(ns);
2229
				}
2230
			}
25683 tejbeer 2231
		} else {
2232
			for (NotificationCampaign notificationCampaign : nc) {
2233
 
2234
				Notification ns = new Notification();
2235
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2236
						SimpleCampaignParams.class);
2237
				Campaign campaign = new SimpleCampaign(scp);
2238
				LocalDateTime expire = campaign.getExpireTimestamp();
2239
				ns.setCid(Integer.toString(notificationCampaign.getId()));
2240
				ns.setType(campaign.getType());
2241
				ns.setMessage(campaign.getMessage());
2242
				ns.setTitle(campaign.getTitle());
2243
				if (notificationCampaign.getDocumentId() != null) {
2244
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
2245
					ns.setDocumentName(document.getDisplayName());
2246
				}
2247
				ns.setUrl(campaign.getUrl());
2248
				ns.setShowImage(campaign.getShowImage());
2249
				ns.setImageUrl(campaign.getImageUrl());
2250
				ns.setDocumentId(notificationCampaign.getDocumentId());
2251
				ns.setMessageType(notificationCampaign.getMessageType());
2252
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
2253
						* 1000);
2254
				if (LocalDateTime.now().isAfter(expire)) {
2255
					ns.setExpired(true);
2256
				} else {
2257
					ns.setExpired(false);
2258
				}
2259
				notifications.add(ns);
2260
			}
2261
 
25649 tejbeer 2262
		}
25683 tejbeer 2263
		return notifications;
25651 tejbeer 2264
 
2265
	}
25649 tejbeer 2266
 
25651 tejbeer 2267
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
2268
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
2269
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
2270
			throws ProfitMandiBusinessException {
2271
		Document document = documentRepository.selectById(documentId);
2272
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
2273
		if (nc.getDocumentId() == null) {
2274
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
2275
		}
2276
		if (nc.getDocumentId() != documentId) {
2277
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
2278
		}
2279
		return responseSender.ok(document);
25649 tejbeer 2280
	}
2281
 
25651 tejbeer 2282
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
2283
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
2284
			throws ProfitMandiBusinessException {
2285
 
2286
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
2287
 
2288
		if (nc.getDocumentId() == null) {
2289
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
2290
		}
2291
 
2292
		Document document = documentRepository.selectById(nc.getDocumentId());
2293
 
2294
		FileInputStream file = null;
2295
		try {
2296
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
2297
		} catch (FileNotFoundException e) {
2298
			LOGGER.error("Retailer Document file not found : ", e);
2299
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
2300
		}
2301
		// ByteArrayOutputStream byteArrayOutputStream = new
2302
		// ByteArrayOutputStream();
2303
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
2304
 
2305
		final HttpHeaders headers = new HttpHeaders();
2306
		String contentType = "";
2307
		if (document.getContentType() == ContentType.JPEG) {
2308
			contentType = "image/jpeg";
2309
		} else if (document.getContentType() == ContentType.PNG) {
2310
			contentType = "image/png";
2311
		} else if (document.getContentType() == ContentType.PDF) {
2312
			contentType = "application/pdf";
2313
		}
2314
		headers.set("Content-Type", contentType);
2315
		headers.set("Content-disposition", "inline; filename=" + document.getName());
2316
		headers.setContentLength(document.getSize());
2317
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
2318
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
2319
	}
26460 amit.gupta 2320
 
2321
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 2322
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 2323
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 2324
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
2325
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
2326
			List<Integer> authIds = l2l1.getValue();
2327
			authIds.add(l2l1.getKey());
2328
 
2329
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 2330
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 2331
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 2332
			if (!leads.isEmpty()) {
2333
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
2334
			} else {
2335
				authIdAndleadsCountMap.put(auth.getId(), 0);
2336
			}
26422 tejbeer 2337
		}
26468 amit.gupta 2338
 
26460 amit.gupta 2339
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 2340
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
2341
				.collect(Collectors.toList());
26433 tejbeer 2342
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 2343
 
26460 amit.gupta 2344
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 2345
 
26460 amit.gupta 2346
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
2347
		for (int authUserId : pp.keySet()) {
2348
			if (L2L1Mapping.keySet().contains(authUserId)) {
2349
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 2350
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 2351
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
2352
						.collect(Collectors.toList());
27632 tejbeer 2353
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 2354
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
2355
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 2356
			}
2357
		}
26997 amit.gupta 2358
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
2359
				.collect(Collectors.toList());
26468 amit.gupta 2360
		PartnerDetailModel partnerDetailModel = partnerStatsService
2361
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 2362
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 2363
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 2364
		return authIdAndallValues;
2365
	}
2366
 
27579 tejbeer 2367
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
2368
	public String getItemWiseTertiary(HttpServletRequest request,
2369
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
2370
			throws ProfitMandiBusinessException {
2371
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
2372
 
2373
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 2374
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2375
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 2376
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
2377
		return "item-wise-tertiary";
2378
	}
2379
 
27586 tejbeer 2380
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
2381
	public String getItemWiseIndent(HttpServletRequest request,
2382
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
2383
			throws ProfitMandiBusinessException {
2384
 
2385
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
2386
		model.addAttribute("unbilledOrders", unbilledOrders);
2387
 
2388
		return "item-wise-indent";
2389
	}
2390
 
27636 tejbeer 2391
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
2392
	public String getPartnerInvestment(HttpServletRequest request,
2393
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2394
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
2395
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
2396
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2397
		model.addAttribute("partnerDetailModel", partnerDetailModel);
2398
		model.addAttribute("customRetailer", customRetailer);
2399
		return "partner-investment";
2400
	}
27727 tejbeer 2401
 
27704 amit.gupta 2402
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
2403
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
2404
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
2405
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
2406
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 2407
 
27704 amit.gupta 2408
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
2409
		return "partner-pending-indent-item";
2410
	}
2411
 
27636 tejbeer 2412
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
2413
	public String getPartnerActivateStockItem(HttpServletRequest request,
2414
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2415
		List<ActivateItemModel> activateStocks = new ArrayList<>();
2416
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2417
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2418
 
2419
		for (InventoryItem inventoryItem : inventoryItems) {
2420
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
2421
			Item item = itemRepository.selectById(inventoryItem.getItemId());
2422
			ActivateItemModel aim = new ActivateItemModel();
2423
			aim.setFofoId(inventoryItem.getFofoId());
2424
			aim.setQuantity(inventoryItem.getGoodQuantity());
2425
			aim.setAmount(tagListing.getSellingPrice());
2426
			aim.setItemDescription(item.getItemDescription());
2427
			aim.setItemId(inventoryItem.getItemId());
2428
			activateStocks.add(aim);
2429
		}
2430
 
2431
		model.addAttribute("activateStocks", activateStocks);
2432
		model.addAttribute("customRetailer", customRetailer);
2433
		return "partner-activate-stock";
2434
	}
2435
 
2436
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
2437
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
2438
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2439
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2440
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2441
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
2442
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 2443
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
2444
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 2445
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2446
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 2447
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2448
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
2449
 
27636 tejbeer 2450
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
2451
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 2452
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 2453
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 2454
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
2455
 
27636 tejbeer 2456
		model.addAttribute("customRetailer", customRetailer);
2457
		return "partner-brand-mtd-sale";
2458
	}
2459
 
27637 tejbeer 2460
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
2461
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
2462
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2463
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2464
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2465
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
2466
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 2467
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
2468
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 2469
 
2470
		Double accesorieslmtdsale = fofoOrderRepository
2471
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
2472
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
2473
				.get(fofoId);
27638 tejbeer 2474
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2475
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
2476
				Optional.of(false)).get(fofoId);
2477
 
27637 tejbeer 2478
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 2479
		model.addAttribute("brandLmtdQty", brandLmtdQty);
2480
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 2481
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
2482
		model.addAttribute("customRetailer", customRetailer);
2483
		return "partner-brand-lmtd-sale";
2484
	}
2485
 
27660 tejbeer 2486
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
2487
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
2488
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2489
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2490
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2491
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2492
 
2493
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 2494
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2495
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 2496
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2497
 
27893 tejbeer 2498
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2499
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 2500
		Long accesorieslmsqty = fofoOrderRepository
2501
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 2502
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 2503
				.get(fofoId);
2504
 
2505
		model.addAttribute("brandLMSAmount", brandLMSAmount);
2506
		model.addAttribute("brandLmsQty", brandLmsQty);
2507
		model.addAttribute("accesorieslmssale", accesorieslmssale);
2508
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
2509
		model.addAttribute("customRetailer", customRetailer);
2510
		return "partner-brand-lms-sale";
2511
	}
2512
 
27640 tejbeer 2513
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
2514
	public String getPatnerInStock(HttpServletRequest request,
2515
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2516
 
2517
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2518
 
27660 tejbeer 2519
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 2520
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 2521
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 2522
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
2523
 
27660 tejbeer 2524
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
2525
				.selectInStockItemsByBrand(fofoId);
2526
 
2527
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
2528
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2529
 
2530
		model.addAttribute("stockItemMap", stockItemMap);
2531
		model.addAttribute("mobileStock", mobileStocks);
2532
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 2533
		model.addAttribute("customRetailer", customRetailer);
2534
		return "partner-instock-item";
2535
	}
2536
 
27660 tejbeer 2537
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
2538
	public String getOpenTicketByFofoId(HttpServletRequest request,
2539
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2540
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
2541
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2542
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
2543
				.collect(Collectors.toList());
2544
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
2545
 
2546
		for (TicketAssigned ticketAssign : ticketAssigns) {
2547
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
2548
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
2549
		}
2550
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
2551
		model.addAttribute("ticketAssigns", ticketAssigns);
2552
		model.addAttribute("customRetailer", customRetailer);
2553
		return "open-ticket";
2554
	}
2555
 
27893 tejbeer 2556
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
2557
	public String getPartnerSecondarySale(HttpServletRequest request,
2558
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
2559
			throws Exception {
2560
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2561
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2562
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2563
		LocalDateTime startDate = null;
2564
		LocalDateTime endDate = null;
2565
		List<InStockBrandModel> secondarySale = null;
2566
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
2567
 
2568
		if (timeValue.equals("mtd")) {
2569
			startDate = curDate.withDayOfMonth(1);
2570
			endDate = curDate.with(LocalTime.MAX);
2571
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2572
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2573
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2574
			LOGGER.info("secondarySalemtd" + secondarySale);
2575
		} else if (timeValue.equals("lmtd")) {
2576
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2577
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
2578
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2579
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2580
 
2581
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2582
			LOGGER.info("secondarySalelmtd" + secondarySale);
2583
 
2584
		} else {
2585
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2586
			endDate = curDate.withDayOfMonth(1);
2587
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2588
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2589
 
2590
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2591
			LOGGER.info("secondarySalelms" + secondarySale);
2592
 
2593
		}
2594
 
2595
		LOGGER.info("secondarySale" + secondarySale);
2596
		model.addAttribute("secondarySale", secondarySale);
2597
		model.addAttribute("secondaryItemSale", secondaryItemSale);
2598
		model.addAttribute("customRetailer", customRetailer);
2599
 
2600
		return "partner-secondary-order";
2601
	}
2602
 
21615 kshitij.so 2603
}