Subversion Repositories SmartDukaan

Rev

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