Subversion Repositories SmartDukaan

Rev

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