Subversion Repositories SmartDukaan

Rev

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

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