Subversion Repositories SmartDukaan

Rev

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

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