Subversion Repositories SmartDukaan

Rev

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