Subversion Repositories SmartDukaan

Rev

Rev 28453 | Rev 28455 | 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
			}
28454 tejbeer 1646
			Map<Integer, CustomRetailer> customRetailerMap = null;
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
				}
28454 tejbeer 1675
				customRetailerMap = retailerService
1676
						.getFofoRetailers(fofoIds.stream().map(x -> x).collect(Collectors.toList()));
27670 tejbeer 1677
 
27701 tejbeer 1678
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
1679
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 1680
 
27701 tejbeer 1681
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
1682
 
1683
				// warehouseStock
1684
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
1685
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
1686
 
28272 tejbeer 1687
				Set<CustomRetailer> positionRetailers = fofoIds.stream()
1688
						.map(x -> retailerService.getAllFofoRetailers().get(x)).filter(x -> x != null)
1689
						.collect(Collectors.toSet());
27931 amit.gupta 1690
				model.addAttribute("retailers", gson.toJson(positionRetailers));
1691
				model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
1692
				model.addAttribute("warehouses", getWarehouses(positionRetailers));
28442 amit.gupta 1693
			} else {
1694
				List<Position> warehousePositions = positions.stream()
1695
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
1696
						.collect(Collectors.toList());
1697
				if (warehousePositions.size() > 0) {
1698
					Set<CustomRetailer> positionRetailers = new HashSet<>();
1699
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
1700
						positionRetailers.addAll(customRetailers);
1701
					});
1702
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1703
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1704
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
1705
				}
26418 tejbeer 1706
			}
1707
 
27819 tejbeer 1708
			if (positions.size() > 0) {
1709
				if (positions.stream()
1710
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1711
								|| x.getEscalationType().equals(EscalationType.L4)
1712
								|| x.getEscalationType().equals(EscalationType.L5))
1713
						.count() > 0) {
1714
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1715
				}
1716
			}
1717
 
27415 tejbeer 1718
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
28442 amit.gupta 1719
					.contains(email)) {
26029 amit.gupta 1720
				menus = menuRepository.selectAll();
1721
			} else if (positions.size() > 0) {
27108 amit.gupta 1722
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1723
					menus = menuRepository.selectAll();
27893 tejbeer 1724
				} else {
1725
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1726
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1727
					if (menuIds.size() > 0) {
1728
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1729
					}
26022 amit.gupta 1730
				}
27930 amit.gupta 1731
			}
28451 tejbeer 1732
 
28272 tejbeer 1733
			model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1734
 
27628 tejbeer 1735
			model.addAttribute("rctPartneStat", rctPartneStat);
1736
 
1737
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1738
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1739
			model.addAttribute("warehouseMap", wm);
28451 tejbeer 1740
			model.addAttribute("customRetailersMap", customRetailerMap);
1741
			model.addAttribute("fofoIds", fofoIds);
27819 tejbeer 1742
 
1743
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1744
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
28451 tejbeer 1745
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
27556 tejbeer 1746
 
28451 tejbeer 1747
			model.addAttribute("date", curDate.withDayOfMonth(1).minusMonths(6).toLocalDate());
27594 tejbeer 1748
 
26012 amit.gupta 1749
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1750
		}
26028 amit.gupta 1751
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1752
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1753
		model.addAttribute("menu", menuList);
26012 amit.gupta 1754
		return "admin";
1755
	}
1756
 
26468 amit.gupta 1757
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1758
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1759
			throws Exception {
1760
 
1761
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1762
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1763
 
26468 amit.gupta 1764
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1765
		if (authId != 0) {
1766
			List<Integer> fofoIds = pp.get(authId);
1767
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1768
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1769
		} else {
26418 tejbeer 1770
		}
1771
 
1772
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1773
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1774
 
1775
		return "auth_user_partner_detail";
26468 amit.gupta 1776
	}
26418 tejbeer 1777
 
27545 tejbeer 1778
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1779
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1780
			throws Exception {
27701 tejbeer 1781
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1782
		String email = loginDetails.getEmailId();
1783
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1784
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1785
 
27701 tejbeer 1786
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1787
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1788
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1789
 
27545 tejbeer 1790
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1791
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1792
		if (warehouseId != 0) {
27701 tejbeer 1793
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1794
			/*
1795
			 * List<Integer> fofoIds =
1796
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1797
			 * .map(x -> x.getId()).collect(Collectors.toList());
1798
			 */
27545 tejbeer 1799
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1800
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1801
		} else {
27701 tejbeer 1802
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1803
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1804
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1805
		}
1806
 
1807
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1808
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1809
 
1810
		return "auth_user_partner_detail";
1811
	}
1812
 
27509 tejbeer 1813
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1814
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1815
			@RequestParam List<Integer> warehouseId) throws Exception {
1816
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1817
		String email = loginDetails.getEmailId();
1818
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1819
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1820
 
27701 tejbeer 1821
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1822
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1823
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1824
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1825
		if (!warehouseId.contains(0)) {
1826
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1827
		} else {
1828
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1829
			warehouseWiseBrandStock = saholicInventoryCISRepository
1830
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1831
 
1832
		}
27542 tejbeer 1833
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1834
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1835
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1836
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1837
 
27509 tejbeer 1838
		return "warehouse_brand_stock";
1839
	}
1840
 
27529 tejbeer 1841
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1842
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1843
		inventoryService.getItemAvailabilityAndIndent();
1844
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1845
		return "response";
1846
	}
1847
 
27701 tejbeer 1848
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1849
			throws Exception {
27628 tejbeer 1850
 
1851
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1852
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1853
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1854
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1855
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1856
		if (partnerStats != null) {
27701 tejbeer 1857
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1858
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1859
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1860
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1861
						.collect(Collectors.toList());
27634 tejbeer 1862
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1863
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1864
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1865
				}
27628 tejbeer 1866
 
1867
			}
27701 tejbeer 1868
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1869
					.collect(Collectors.toList());
1870
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1871
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1872
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1873
			warehouseIdAndallValues.put(0, partnerDetailModel);
1874
		}
1875
		return warehouseIdAndallValues;
1876
	}
1877
 
1878
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1879
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1880
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1881
		ObjectOutputStream oos = null;
1882
		FileOutputStream fout = null;
1883
		try {
1884
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1885
			oos = new ObjectOutputStream(fout);
1886
			oos.writeObject(partnerStats);
1887
 
1888
		} catch (Exception ex) {
1889
			ex.printStackTrace();
1890
		} finally {
1891
			if (oos != null) {
1892
				oos.close();
1893
			}
1894
		}
1895
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1896
		if (rct == null) {
1897
			rct = new ReporticoCacheTable();
1898
			rct.setTableName("partnerStat");
1899
 
1900
		}
1901
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1902
		reporticoCacheTableRepository.persist(rct);
1903
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1904
		return "response";
1905
	}
1906
 
1907
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1908
		ObjectInputStream objectinputstream = null;
1909
		Map<Integer, PartnerDetailModel> partnerStat = null;
1910
		try {
1911
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1912
			objectinputstream = new ObjectInputStream(streamIn);
1913
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1914
 
1915
			LOGGER.info("partnerStat" + partnerStat);
1916
			objectinputstream.close();
1917
 
1918
		} catch (Exception e) {
1919
			LOGGER.info("exceptionddd" + e);
1920
 
1921
			e.printStackTrace();
1922
 
1923
		} finally {
1924
			if (objectinputstream != null) {
1925
				objectinputstream.close();
1926
				LOGGER.info("clofddd" + partnerStat);
1927
 
1928
			}
1929
		}
1930
		return partnerStat;
1931
 
1932
	}
1933
 
27539 tejbeer 1934
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1935
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1936
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1937
			throws Exception {
27509 tejbeer 1938
 
1939
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1940
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1941
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1942
 
27509 tejbeer 1943
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1944
		model.addAttribute("brands", listbrands);
27538 tejbeer 1945
		model.addAttribute("listCategory", listCategory);
1946
 
27529 tejbeer 1947
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1948
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1949
		model.addAttribute("selectedCategory", category);
1950
 
27509 tejbeer 1951
		return "warehouse_brand_item_stock";
1952
	}
1953
 
27538 tejbeer 1954
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1955
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1956
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1957
			throws Exception {
27539 tejbeer 1958
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1959
		if (warehouseId.contains(0)) {
1960
			warehouseId.addAll(warehouseMap.keySet());
1961
		}
27538 tejbeer 1962
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1963
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1964
 
27538 tejbeer 1965
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1966
		model.addAttribute("warehouseMap", warehouseMap);
1967
		return "warehouse_item_details";
1968
	}
1969
 
26114 amit.gupta 1970
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1971
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1972
		positionRetailers.stream().forEach(x -> {
1973
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1974
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1975
			}
1976
		});
26114 amit.gupta 1977
		return gson.toJson(warehouses);
1978
 
1979
	}
1980
 
27556 tejbeer 1981
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1982
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1983
			throws Exception {
27701 tejbeer 1984
 
1985
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1986
		String email = loginDetails.getEmailId();
1987
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1988
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1989
 
27670 tejbeer 1990
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1991
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1992
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1993
 
1994
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1995
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1996
 
1997
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1998
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1999
			if (bpt != null) {
2000
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 2001
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 2002
			} else {
2003
				bpt = new WarehouseWiseBrandSaleModel();
2004
				bpt.setWarehouseId(un.getWarehouseId());
2005
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 2006
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 2007
				bpt.setLms(0);
2008
				bpt.setLmtd(0);
2009
				bpt.setMtd(0);
2010
				bpt.setMtdQty(0);
2011
				bpt.setLmtd(0);
2012
				bpt.setLmtdQty(0);
2013
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
2014
			}
2015
		}
27556 tejbeer 2016
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 2017
 
2018
		Set<String> brands = inventoryService.getAllTagListingBrands();
2019
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 2020
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 2021
		model.addAttribute("brands", brands);
2022
		model.addAttribute("selectedbrand", brand);
2023
		return "warehousewise_brand_partners_sale";
27556 tejbeer 2024
	}
2025
 
27594 tejbeer 2026
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
2027
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
2028
			@RequestParam String brand) throws Exception {
27701 tejbeer 2029
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2030
		String email = loginDetails.getEmailId();
2031
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2032
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 2033
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 2034
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 2035
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2036
 
2037
		Set<String> brands = inventoryService.getAllTagListingBrands();
2038
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
2039
		model.addAttribute("warehouseMap", warehouseMap);
2040
		model.addAttribute("brands", brands);
2041
		model.addAttribute("selectedbrand", brand);
2042
		return "warehousewise_accessoriesbrand_sale";
2043
	}
2044
 
27556 tejbeer 2045
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
2046
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
2047
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
2048
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 2049
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2050
		String email = loginDetails.getEmailId();
2051
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2052
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 2053
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 2054
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 2055
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
2056
 
2057
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 2058
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 2059
 
2060
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
2061
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
2062
			if (bpt != null) {
2063
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 2064
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 2065
			} else {
2066
				bpt = new WarehouseBrandWiseItemSaleModel();
2067
				bpt.setWarehouseId(un.getWarehouseId());
2068
				bpt.setItemId(un.getItemId());
2069
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 2070
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 2071
				bpt.setBrand(un.getBrand());
2072
				bpt.setModelName(un.getModelName());
2073
				bpt.setModelNumber(un.getModelNumber());
2074
				bpt.setColor(un.getColor());
2075
				bpt.setLms(0);
2076
				bpt.setLmtd(0);
2077
				bpt.setMtd(0);
2078
				bpt.setMtdQty(0);
2079
				bpt.setLmtd(0);
2080
				bpt.setLmtdQty(0);
2081
				branditemSalesMap.put(un.getItemId(), bpt);
2082
			}
2083
		}
2084
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 2085
		model.addAttribute("warehouseMap", warehouseMap);
2086
		return "warehouse_partner_itemwise_sale";
2087
	}
2088
 
27594 tejbeer 2089
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
2090
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
2091
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
2092
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 2093
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2094
		String email = loginDetails.getEmailId();
2095
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2096
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 2097
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 2098
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 2099
		model.addAttribute("branditemSales", branditemSales);
2100
		model.addAttribute("warehouseMap", warehouseMap);
2101
		return "warehouse_accessories_itemwsie_sale";
2102
	}
2103
 
26012 amit.gupta 2104
	private List<Menu> prepareMenu(List<Menu> menus) {
2105
		List<Menu> returnMenu = new ArrayList<>();
2106
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
2107
		for (Menu menu : menus) {
2108
			if (menu.get_parent() == null) {
26014 amit.gupta 2109
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 2110
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 2111
				}
2112
			} else {
26012 amit.gupta 2113
				Menu parentMenu = menu.get_parent();
2114
				if (!subMenuMap.containsKey(parentMenu)) {
2115
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 2116
				}
26012 amit.gupta 2117
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 2118
			}
2119
		}
26012 amit.gupta 2120
		subMenuMap.entrySet().stream().forEach(entry -> {
2121
			entry.getKey().setSubMenus(entry.getValue());
2122
			returnMenu.add(entry.getKey());
2123
		});
2124
		return returnMenu;
26005 amit.gupta 2125
	}
2126
 
24288 amit.gupta 2127
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 2128
	private boolean hasGift(int fofoId) {
2129
		try {
24288 amit.gupta 2130
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
2131
					.getAvailability() > 0;
24203 amit.gupta 2132
		} catch (ProfitMandiBusinessException e) {
2133
			return false;
2134
		}
2135
	}
24288 amit.gupta 2136
 
22354 ashik.ali 2137
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 2138
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 2139
		model.addAttribute("appContextPath", request.getContextPath());
2140
		return "contact-us";
2141
	}
23923 amit.gupta 2142
 
25649 tejbeer 2143
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 2144
	public String getNotificationsWithType(HttpServletRequest request,
2145
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 2146
			@RequestParam(name = "offset", defaultValue = "0") int offset,
2147
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
2148
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 2149
		int userId = 0;
2150
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
2151
		if (isAdmin) {
2152
			userId = loginDetails.getFofoId();
2153
		} else {
2154
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
2155
		}
25683 tejbeer 2156
		List<Notification> notifications = null;
2157
 
26086 tejbeer 2158
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
2159
				userId, offset, limit);
2160
		LOGGER.info("messageType" + messageType);
2161
		notifications = getNotifications(notificationCampaigns, messageType);
2162
 
25683 tejbeer 2163
		model.addAttribute("notifications", notifications);
2164
 
2165
		LOGGER.info("notifications" + notifications);
2166
		return "notification-template";
2167
	}
2168
 
2169
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
2170
			throws ProfitMandiBusinessException {
2171
		List<Notification> notifications = new ArrayList<>();
2172
		Document document = null;
2173
		if (messageType != null) {
2174
			for (NotificationCampaign notificationCampaign : nc) {
2175
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 2176
					Notification ns = new Notification();
2177
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2178
							SimpleCampaignParams.class);
2179
					Campaign campaign = new SimpleCampaign(scp);
2180
					LocalDateTime expire = campaign.getExpireTimestamp();
2181
					ns.setCid(Integer.toString(notificationCampaign.getId()));
2182
					ns.setType(campaign.getType());
2183
					ns.setMessage(campaign.getMessage());
2184
					ns.setTitle(campaign.getTitle());
25651 tejbeer 2185
					if (notificationCampaign.getDocumentId() != null) {
2186
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
2187
						ns.setDocumentName(document.getDisplayName());
2188
					}
25683 tejbeer 2189
					ns.setUrl(campaign.getUrl());
25649 tejbeer 2190
					ns.setShowImage(campaign.getShowImage());
2191
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 2192
					ns.setDocumentId(notificationCampaign.getDocumentId());
2193
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 2194
					ns.setCreated(
2195
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
2196
									* 1000);
2197
					if (LocalDateTime.now().isAfter(expire)) {
2198
						ns.setExpired(true);
2199
					} else {
2200
						ns.setExpired(false);
2201
					}
2202
					notifications.add(ns);
2203
				}
2204
			}
25683 tejbeer 2205
		} else {
2206
			for (NotificationCampaign notificationCampaign : nc) {
2207
 
2208
				Notification ns = new Notification();
2209
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
2210
						SimpleCampaignParams.class);
2211
				Campaign campaign = new SimpleCampaign(scp);
2212
				LocalDateTime expire = campaign.getExpireTimestamp();
2213
				ns.setCid(Integer.toString(notificationCampaign.getId()));
2214
				ns.setType(campaign.getType());
2215
				ns.setMessage(campaign.getMessage());
2216
				ns.setTitle(campaign.getTitle());
2217
				if (notificationCampaign.getDocumentId() != null) {
2218
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
2219
					ns.setDocumentName(document.getDisplayName());
2220
				}
2221
				ns.setUrl(campaign.getUrl());
2222
				ns.setShowImage(campaign.getShowImage());
2223
				ns.setImageUrl(campaign.getImageUrl());
2224
				ns.setDocumentId(notificationCampaign.getDocumentId());
2225
				ns.setMessageType(notificationCampaign.getMessageType());
2226
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
2227
						* 1000);
2228
				if (LocalDateTime.now().isAfter(expire)) {
2229
					ns.setExpired(true);
2230
				} else {
2231
					ns.setExpired(false);
2232
				}
2233
				notifications.add(ns);
2234
			}
2235
 
25649 tejbeer 2236
		}
25683 tejbeer 2237
		return notifications;
25651 tejbeer 2238
 
2239
	}
25649 tejbeer 2240
 
25651 tejbeer 2241
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
2242
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
2243
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
2244
			throws ProfitMandiBusinessException {
2245
		Document document = documentRepository.selectById(documentId);
2246
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
2247
		if (nc.getDocumentId() == null) {
2248
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
2249
		}
2250
		if (nc.getDocumentId() != documentId) {
2251
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
2252
		}
2253
		return responseSender.ok(document);
25649 tejbeer 2254
	}
2255
 
25651 tejbeer 2256
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
2257
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
2258
			throws ProfitMandiBusinessException {
2259
 
2260
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
2261
 
2262
		if (nc.getDocumentId() == null) {
2263
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
2264
		}
2265
 
2266
		Document document = documentRepository.selectById(nc.getDocumentId());
2267
 
2268
		FileInputStream file = null;
2269
		try {
2270
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
2271
		} catch (FileNotFoundException e) {
2272
			LOGGER.error("Retailer Document file not found : ", e);
2273
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
2274
		}
2275
		// ByteArrayOutputStream byteArrayOutputStream = new
2276
		// ByteArrayOutputStream();
2277
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
2278
 
2279
		final HttpHeaders headers = new HttpHeaders();
2280
		String contentType = "";
2281
		if (document.getContentType() == ContentType.JPEG) {
2282
			contentType = "image/jpeg";
2283
		} else if (document.getContentType() == ContentType.PNG) {
2284
			contentType = "image/png";
2285
		} else if (document.getContentType() == ContentType.PDF) {
2286
			contentType = "application/pdf";
2287
		}
2288
		headers.set("Content-Type", contentType);
2289
		headers.set("Content-disposition", "inline; filename=" + document.getName());
2290
		headers.setContentLength(document.getSize());
2291
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
2292
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
2293
	}
26460 amit.gupta 2294
 
2295
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 2296
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 2297
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 2298
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
2299
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
2300
			List<Integer> authIds = l2l1.getValue();
2301
			authIds.add(l2l1.getKey());
2302
 
2303
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 2304
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 2305
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 2306
			if (!leads.isEmpty()) {
2307
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
2308
			} else {
2309
				authIdAndleadsCountMap.put(auth.getId(), 0);
2310
			}
26422 tejbeer 2311
		}
26468 amit.gupta 2312
 
26460 amit.gupta 2313
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 2314
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
2315
				.collect(Collectors.toList());
26433 tejbeer 2316
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 2317
 
26460 amit.gupta 2318
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 2319
 
26460 amit.gupta 2320
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
2321
		for (int authUserId : pp.keySet()) {
2322
			if (L2L1Mapping.keySet().contains(authUserId)) {
2323
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 2324
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 2325
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
2326
						.collect(Collectors.toList());
27632 tejbeer 2327
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 2328
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
2329
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 2330
			}
2331
		}
26997 amit.gupta 2332
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
2333
				.collect(Collectors.toList());
26468 amit.gupta 2334
		PartnerDetailModel partnerDetailModel = partnerStatsService
2335
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 2336
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 2337
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 2338
		return authIdAndallValues;
2339
	}
2340
 
27579 tejbeer 2341
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
2342
	public String getItemWiseTertiary(HttpServletRequest request,
2343
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
2344
			throws ProfitMandiBusinessException {
2345
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
2346
 
2347
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 2348
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2349
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 2350
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
2351
		return "item-wise-tertiary";
2352
	}
2353
 
27586 tejbeer 2354
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
2355
	public String getItemWiseIndent(HttpServletRequest request,
2356
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
2357
			throws ProfitMandiBusinessException {
2358
 
2359
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
2360
		model.addAttribute("unbilledOrders", unbilledOrders);
2361
 
2362
		return "item-wise-indent";
2363
	}
2364
 
27636 tejbeer 2365
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
2366
	public String getPartnerInvestment(HttpServletRequest request,
2367
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2368
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
2369
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
2370
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2371
		model.addAttribute("partnerDetailModel", partnerDetailModel);
2372
		model.addAttribute("customRetailer", customRetailer);
2373
		return "partner-investment";
2374
	}
27727 tejbeer 2375
 
27704 amit.gupta 2376
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
2377
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
2378
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
2379
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
2380
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 2381
 
27704 amit.gupta 2382
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
2383
		return "partner-pending-indent-item";
2384
	}
2385
 
27636 tejbeer 2386
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
2387
	public String getPartnerActivateStockItem(HttpServletRequest request,
2388
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2389
		List<ActivateItemModel> activateStocks = new ArrayList<>();
2390
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2391
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2392
 
2393
		for (InventoryItem inventoryItem : inventoryItems) {
2394
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
2395
			Item item = itemRepository.selectById(inventoryItem.getItemId());
2396
			ActivateItemModel aim = new ActivateItemModel();
2397
			aim.setFofoId(inventoryItem.getFofoId());
2398
			aim.setQuantity(inventoryItem.getGoodQuantity());
2399
			aim.setAmount(tagListing.getSellingPrice());
2400
			aim.setItemDescription(item.getItemDescription());
2401
			aim.setItemId(inventoryItem.getItemId());
2402
			activateStocks.add(aim);
2403
		}
2404
 
2405
		model.addAttribute("activateStocks", activateStocks);
2406
		model.addAttribute("customRetailer", customRetailer);
2407
		return "partner-activate-stock";
2408
	}
2409
 
2410
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
2411
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
2412
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2413
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2414
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2415
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
2416
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 2417
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
2418
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 2419
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2420
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 2421
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2422
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
2423
 
27636 tejbeer 2424
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
2425
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 2426
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 2427
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 2428
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
2429
 
27636 tejbeer 2430
		model.addAttribute("customRetailer", customRetailer);
2431
		return "partner-brand-mtd-sale";
2432
	}
2433
 
27637 tejbeer 2434
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
2435
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
2436
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2437
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2438
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2439
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
2440
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 2441
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
2442
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 2443
 
2444
		Double accesorieslmtdsale = fofoOrderRepository
2445
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
2446
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
2447
				.get(fofoId);
27638 tejbeer 2448
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2449
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
2450
				Optional.of(false)).get(fofoId);
2451
 
27637 tejbeer 2452
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 2453
		model.addAttribute("brandLmtdQty", brandLmtdQty);
2454
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 2455
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
2456
		model.addAttribute("customRetailer", customRetailer);
2457
		return "partner-brand-lmtd-sale";
2458
	}
2459
 
27660 tejbeer 2460
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
2461
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
2462
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2463
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2464
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2465
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2466
 
2467
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 2468
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2469
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 2470
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2471
 
27893 tejbeer 2472
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2473
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 2474
		Long accesorieslmsqty = fofoOrderRepository
2475
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 2476
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 2477
				.get(fofoId);
2478
 
2479
		model.addAttribute("brandLMSAmount", brandLMSAmount);
2480
		model.addAttribute("brandLmsQty", brandLmsQty);
2481
		model.addAttribute("accesorieslmssale", accesorieslmssale);
2482
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
2483
		model.addAttribute("customRetailer", customRetailer);
2484
		return "partner-brand-lms-sale";
2485
	}
2486
 
27640 tejbeer 2487
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
2488
	public String getPatnerInStock(HttpServletRequest request,
2489
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2490
 
2491
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2492
 
27660 tejbeer 2493
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 2494
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 2495
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 2496
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
2497
 
27660 tejbeer 2498
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
2499
				.selectInStockItemsByBrand(fofoId);
2500
 
2501
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
2502
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2503
 
2504
		model.addAttribute("stockItemMap", stockItemMap);
2505
		model.addAttribute("mobileStock", mobileStocks);
2506
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 2507
		model.addAttribute("customRetailer", customRetailer);
2508
		return "partner-instock-item";
2509
	}
2510
 
27660 tejbeer 2511
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
2512
	public String getOpenTicketByFofoId(HttpServletRequest request,
2513
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2514
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
2515
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2516
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
2517
				.collect(Collectors.toList());
2518
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
2519
 
2520
		for (TicketAssigned ticketAssign : ticketAssigns) {
2521
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
2522
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
2523
		}
2524
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
2525
		model.addAttribute("ticketAssigns", ticketAssigns);
2526
		model.addAttribute("customRetailer", customRetailer);
2527
		return "open-ticket";
2528
	}
2529
 
27893 tejbeer 2530
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
2531
	public String getPartnerSecondarySale(HttpServletRequest request,
2532
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
2533
			throws Exception {
2534
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2535
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2536
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2537
		LocalDateTime startDate = null;
2538
		LocalDateTime endDate = null;
2539
		List<InStockBrandModel> secondarySale = null;
2540
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
2541
 
2542
		if (timeValue.equals("mtd")) {
2543
			startDate = curDate.withDayOfMonth(1);
2544
			endDate = curDate.with(LocalTime.MAX);
2545
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2546
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2547
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2548
			LOGGER.info("secondarySalemtd" + secondarySale);
2549
		} else if (timeValue.equals("lmtd")) {
2550
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2551
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
2552
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2553
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2554
 
2555
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2556
			LOGGER.info("secondarySalelmtd" + secondarySale);
2557
 
2558
		} else {
2559
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2560
			endDate = curDate.withDayOfMonth(1);
2561
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2562
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2563
 
2564
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2565
			LOGGER.info("secondarySalelms" + secondarySale);
2566
 
2567
		}
2568
 
2569
		LOGGER.info("secondarySale" + secondarySale);
2570
		model.addAttribute("secondarySale", secondarySale);
2571
		model.addAttribute("secondaryItemSale", secondaryItemSale);
2572
		model.addAttribute("customRetailer", customRetailer);
2573
 
2574
		return "partner-secondary-order";
2575
	}
2576
 
28451 tejbeer 2577
	@RequestMapping(value = "/getMobileBrandWise", method = RequestMethod.GET)
2578
	public String getMobileBrandWise(HttpServletRequest request, Model model) throws Exception {
2579
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2580
		String email = loginDetails.getEmailId();
2581
 
2582
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
2583
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2584
 
2585
		Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
2586
		if (emails.contains(authUser.getEmailId())) {
2587
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
2588
			LOGGER.info("fofoIds" + fofoIds);
2589
		}
2590
 
2591
		Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
2592
		partnersBrandSaleMap = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds))
2593
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
2594
 
2595
		List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
2596
				.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
2597
		for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
2598
			BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
2599
			if (bpt != null) {
2600
				bpt.setAmtd(un.getUnbilledMtd());
2601
				bpt.setUamtdQty(un.getUnbilledMTDQty());
2602
			} else {
2603
				bpt = new BrandWisePartnerSaleModel();
2604
				bpt.setBrand(un.getBrand());
2605
				bpt.setAmtd(un.getUnbilledMtd());
2606
				bpt.setUamtdQty(un.getUnbilledMTDQty());
2607
				bpt.setLms(0);
2608
				bpt.setLmtd(0);
2609
				bpt.setMtd(0);
2610
				bpt.setMtdQty(0);
2611
				bpt.setLmtd(0);
2612
				bpt.setLmtdQty(0);
2613
				partnersBrandSaleMap.put(un.getBrand(), bpt);
2614
			}
2615
		}
2616
 
2617
		model.addAttribute("brandSalesMap", partnersBrandSaleMap);
2618
 
2619
		return "mobile-brand-wise-report";
2620
	}
2621
 
2622
	@RequestMapping(value = "/getAccessoriesBrandWise", method = RequestMethod.GET)
2623
	public String getAccessoriesBrandWise(HttpServletRequest request, Model model) throws Exception {
2624
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2625
		String email = loginDetails.getEmailId();
2626
 
2627
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
2628
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2629
 
2630
		Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
2631
		if (emails.contains(authUser.getEmailId())) {
2632
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
2633
			LOGGER.info("fofoIds" + fofoIds);
2634
		}
2635
 
2636
		List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
2637
 
2638
		accessoriesBrandSales = fofoStoreRepository
2639
				.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
2640
 
2641
		model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
2642
		return "accessories-brand-wise-report";
2643
	}
2644
 
2645
	@RequestMapping(value = "/getMobileLMSGraph", method = RequestMethod.GET)
2646
	public String getMobileLMSGraph(HttpServletRequest request, @RequestParam int warehouseId,
2647
			@RequestParam(required = false) LocalDate date, @RequestParam List<Integer> fofoIds, Model model)
2648
			throws Exception {
2649
 
2650
		if (date == null) {
2651
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
2652
 
2653
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
2654
			date = startOfMonth.toLocalDate();
2655
		}
2656
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
2657
				.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
2658
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
2659
 
2660
		ChartModel cm;
2661
		if (warehouseId != 0) {
2662
			cm = this.getBrandWiseLms(Arrays.asList(warehouseId),
2663
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date);
2664
		} else {
2665
			cm = this.getBrandWiseLms(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
2666
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date);
2667
 
2668
		}
2669
 
2670
		LOGGER.info("chartMap" + gson.toJson(cm));
2671
		model.addAttribute("chartMap", gson.toJson(cm));
2672
		return "brand-wise-mobile-lms-chart";
2673
	}
2674
 
2675
	private ChartModel getBrandWiseLms(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDateTime) {
2676
		LOGGER.info("params" + warehouseIds + fofoIds + startDateTime);
2677
 
2678
		List<BrandWiseModel> brandWiseLms = fofoStoreRepository.selectGroupByBrandLms(fofoIds, warehouseIds,
2679
				startDateTime);
2680
		LOGGER.info("brandWiseLms" + brandWiseLms);
2681
 
2682
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
2683
 
2684
		Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
2685
		for (BrandWiseModel bwl : brandWiseLms) {
2686
			Map<YearMonth, Double> brandValue = new HashMap<>();
2687
			if (brandMonthValue.containsKey(bwl.getBrand())) {
2688
				brandValue = brandMonthValue.get(bwl.getBrand());
2689
				brandValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
2690
			} else {
2691
 
2692
				brandValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
2693
 
2694
			}
2695
			brandMonthValue.put(bwl.getBrand(), brandValue);
2696
 
2697
		}
2698
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2699
 
2700
		Period age = Period.between(startDateTime, LocalDate.now());
2701
		int months = age.getMonths();
2702
		LOGGER.info("months" + months);
2703
		LOGGER.info("brandWiseLms" + brandWiseLms);
2704
		LOGGER.info("brandMonthValue" + brandMonthValue);
2705
		List<String> brands = new ArrayList<>();
2706
		brands.add("Oppo");
2707
		brands.add("Vivo");
2708
		brands.add("Samsung");
2709
		brands.add("Realme");
2710
		brands.add("Mi");
2711
		brands.add("Tecno");
2712
		brands.add("Itel");
2713
		brands.add("Lava");
2714
		brands.add("Nokia");
2715
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
2716
 
2717
		for (String brand : brands) {
2718
			Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
2719
			for (int i = months; i >= 1; i--) {
2720
 
2721
				LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
2722
 
2723
				if (yearMonthValue != null) {
2724
					if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
2725
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
2726
					}
2727
 
2728
				} else {
2729
					yearMonthValue = new HashMap<>();
2730
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
2731
				}
2732
			}
2733
 
2734
			Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
2735
 
2736
			brandMonthValue.put(brand, sortedMonthBrandValue);
2737
 
2738
			sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
2739
 
2740
		}
2741
 
2742
		LOGGER.info("brandMonthValue" + brandMonthValue);
2743
 
2744
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
2745
 
2746
		LinkedHashSet<String> labels = new LinkedHashSet<String>();
2747
 
2748
		for (int i = months; i >= 1; i--) {
2749
 
2750
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
2751
			labels.add(startMonth.format(DateTimeFormatter.ofPattern("MMM''uu")).toString());
2752
		}
2753
 
2754
		List<DatasetModel> datasets = new ArrayList<>();
2755
		List<String> colorList = new ArrayList<>();
2756
		colorList.add("darkgreen");
2757
		colorList.add("dodgerblue");
2758
		colorList.add("darkblue");
2759
		colorList.add("gold");
2760
		colorList.add("coral");
2761
		colorList.add("steelblue");
2762
		colorList.add("red");
2763
		colorList.add("midnightblue");
2764
		colorList.add("cornsilk");
2765
 
2766
		List<String> borderList = new ArrayList<>();
2767
		borderList.add("mediumseagreen");
2768
		borderList.add("lightblue");
2769
		borderList.add("#0000cd");
2770
		borderList.add("#f7e98e");
2771
 
2772
		borderList.add("#ff8c69");
2773
 
2774
		borderList.add("#0000cd");
2775
		borderList.add("lightsalmon");
2776
 
2777
		borderList.add("#0000cd");
2778
		borderList.add("cornsilk");
2779
 
2780
		int i = 0;
2781
 
2782
		for (Entry<String, List<Double>> brandValue : sortedBrandValue.entrySet()) {
2783
 
2784
			DatasetModel lmsModel = new DatasetModel();
2785
			lmsModel.setLabel(brandValue.getKey());
2786
			lmsModel.setBackgroundColor(colorList.get(i));
2787
			if (brandValue.getValue().isEmpty()) {
2788
 
2789
				lmsModel.setData(Arrays.asList(0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
2790
			} else {
2791
				lmsModel.setData(brandValue.getValue());
2792
			}
2793
			lmsModel.setType("line");
2794
			lmsModel.setOrder(1);
2795
			lmsModel.setFill("false");
2796
			lmsModel.setBorderColor(borderList.get(i));
2797
			datasets.add(lmsModel);
2798
 
2799
			i++;
2800
		}
2801
 
2802
		DataModel dm = new DataModel();
2803
		dm.setDatasets(datasets);
2804
		dm.setLabels(labels);
2805
 
2806
		LegendModel lm = new LegendModel();
2807
		lm.setPosition("top");
2808
 
2809
		Tooltips tooltips = new Tooltips();
2810
		tooltips.setBodyFontSize(15);
2811
		tooltips.setTitleFontSize(15);
2812
		tooltips.setMode("index");
2813
		tooltips.setIntersect(false);
2814
		tooltips.setBackgroundColor("rgba(0, 0, 0, .5)");
2815
 
2816
		HoverModel hover = new HoverModel();
2817
		hover.setIntersect(false);
2818
		hover.setMode("index");
2819
 
2820
		TitleModel tm = new TitleModel();
2821
		tm.setText("Brand Wise Monthly Sale");
2822
		tm.setDisplay(true);
2823
		tm.setFontSize(20);
2824
		tm.setFontColor("#111");
2825
 
2826
		OptionsModel om = new OptionsModel();
2827
		om.setResponsive(true);
2828
		om.setLegend(lm);
2829
		om.setTitle(tm);
2830
		om.setTooltips(tooltips);
2831
		om.setHover(hover);
2832
 
2833
		ChartModel cm = new ChartModel();
2834
 
2835
		cm.setType("line");
2836
		cm.setData(dm);
2837
		cm.setOptions(om);
2838
 
2839
		LOGGER.info("cm" + cm);
2840
 
2841
		return cm;
2842
	}
2843
 
21615 kshitij.so 2844
}