Subversion Repositories SmartDukaan

Rev

Rev 28430 | Rev 28433 | 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");
28432 tejbeer 932
		colorList.add("burlywood");
933
		colorList.add("goldenrod");
934
		colorList.add("slategray");
935
		colorList.add("darkviolet");
936
		colorList.add("cornsilk");
937
 
28430 tejbeer 938
		List<String> borderList = new ArrayList<>();
939
 
940
		borderList.add("orange");
941
		borderList.add("#DB8C44");
942
		borderList.add("pink");
943
		borderList.add("green");
944
		borderList.add("red");
945
		borderList.add("lightskyblue");
28432 tejbeer 946
		borderList.add("slategray");
947
		borderList.add("darkviolet");
948
		colorList.add("cornsilk");
28430 tejbeer 949
 
950
		int i= 0;
951
 
952
		for (Entry<String, List<Double>> brandValue : brandlistValue.entrySet()) {
953
 
954
			DatasetModel lineLmsChart = new DatasetModel();
955
			lineLmsChart.setLabel(brandValue.getKey());
956
			lineLmsChart.setBackgroundColor(borderList.get(i));
957
			lineLmsChart.setData(brandValue.getValue());
958
			lineLmsChart.setType("line");
959
			lineLmsChart.setOrder(1);
960
			lineLmsChart.setFill("false");
961
			lineLmsChart.setBorderColor(colorList.get(i));
962
			datasets.add(lineLmsChart);
963
 
964
			i++;
965
		}
966
 
967
		DataModel dm = new DataModel();
968
		dm.setDatasets(datasets);
969
		dm.setLabels(labels);
970
 
971
		LegendModel lm = new LegendModel();
972
		lm.setPosition("top");
973
 
974
		TitleModel tm = new TitleModel();
975
		tm.setText("Brand Wise LMS");
976
		tm.setDisplay(true);
977
 
978
		OptionsModel om = new OptionsModel();
979
		om.setResponsive(true);
980
		om.setLegend(lm);
981
		om.setTitle(tm);
982
 
983
		ChartModel cm = new ChartModel();
984
		cm.setType("line");
985
		cm.setData(dm);
986
		cm.setOptions(om);
987
 
988
		LOGGER.info("cm" + cm);
989
 
990
		return cm;
991
 
992
	}
993
 
26055 tejbeer 994
	private ChartModel getBrandChart(int fofoId) {
995
 
996
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
997
 
998
		LOGGER.info("cur Date" + curDate.withDayOfMonth(1));
999
 
1000
		LOGGER.info("curDateYear" + curDate.with(LocalTime.MAX));
1001
 
27900 tejbeer 1002
		Map<String, Double> brandwisesale = fofoOrderItemRepository
28430 tejbeer 1003
		.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
26244 tejbeer 1004
 
27900 tejbeer 1005
		LOGGER.info("brandwisesale" + brandwisesale);
27884 tejbeer 1006
 
26244 tejbeer 1007
		Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
28430 tejbeer 1008
		fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27900 tejbeer 1009
		brandwisesale.put("Accessories", accesoriesmtdsale.get(fofoId));
28272 tejbeer 1010
 
27884 tejbeer 1011
		Map<String, Double> activatedImeisWithSellingPriceMTD = fofoOrderRepository
28430 tejbeer 1012
		.selectValueOfActivatedImeis(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId).stream()
1013
		.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
27900 tejbeer 1014
 
27978 tejbeer 1015
		activatedImeisWithSellingPriceMTD.put("Lava", brandwisesale.get("Lava"));
1016
 
27884 tejbeer 1017
		Map<String, Double> activatedImeisWithSellingPriceLMTD = fofoOrderRepository
28430 tejbeer 1018
		.selectValueOfActivatedImeis(curDate.withDayOfMonth(1).minusMonths(1),
1019
		curDate.with(LocalTime.MAX).minusMonths(1), fofoId)
1020
		.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getSellingPrice()));
26055 tejbeer 1021
		Map<String, Double> lmtdBrandWiseSale = fofoOrderItemRepository.selectSumAmountGroupByBrand(
28430 tejbeer 1022
		curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27978 tejbeer 1023
		activatedImeisWithSellingPriceLMTD.put("Lava", lmtdBrandWiseSale.get("Lava"));
26055 tejbeer 1024
 
26244 tejbeer 1025
		Map<Integer, Double> accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(
28430 tejbeer 1026
		fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1027
		Optional.of(false));
27884 tejbeer 1028
 
1029
		lmtdBrandWiseSale.put("Accessories", accesorieslmtdsale.get(fofoId));
1030
 
26055 tejbeer 1031
		ChartModel cm = new ChartModel();
1032
 
28430 tejbeer 1033
		 HashSet<String> labels = new HashSet<String>();
1034
		 labels.addAll(brandwisesale.keySet());
1035
		 labels.addAll(lmtdBrandWiseSale.keySet());
26055 tejbeer 1036
 
28430 tejbeer 1037
		 List<String> labelList = new ArrayList<>(labels);
27884 tejbeer 1038
 
28430 tejbeer 1039
		 List<Double> mtdActivatedImeisValues = new ArrayList<>();
27884 tejbeer 1040
 
28430 tejbeer 1041
		 List<Double> mtdValues = new ArrayList<>();
1042
		 List<Double> lmtdUnActivatedImeisValues = new ArrayList<>();
1043
		 List<Double> lmtdActivatedImeisValues = new ArrayList<>();
1044
		 List<Double> mtdUnActivatedImeisValues = new ArrayList<>();
1045
		 List<Double> lmtdValues = new ArrayList<>();
1046
		 for (String label : labelList) {
1047
		 mtdActivatedImeisValues.add(activatedImeisWithSellingPriceMTD.get(label) == null ? 0
1048
		 : activatedImeisWithSellingPriceMTD.get(label));
1049
		 lmtdActivatedImeisValues.add(activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
1050
		 : activatedImeisWithSellingPriceLMTD.get(label));
26055 tejbeer 1051
 
28430 tejbeer 1052
		 mtdValues.add(brandwisesale.get(label) == null ? 0 : brandwisesale.get(label));
1053
		 if (brandwisesale.get(label) != null) {
1054
		 mtdUnActivatedImeisValues
1055
		 .add(brandwisesale.get(label) - (activatedImeisWithSellingPriceMTD.get(label) == null ? 0
1056
		 : activatedImeisWithSellingPriceMTD.get(label)));
1057
		 } else {
1058
		 mtdUnActivatedImeisValues.add(0.0);
1059
		 }
1060
		 if (lmtdBrandWiseSale.get(label) != null) {
1061
		 lmtdUnActivatedImeisValues
1062
		 .add(lmtdBrandWiseSale.get(label) - (activatedImeisWithSellingPriceLMTD.get(label) == null ? 0
1063
		 : activatedImeisWithSellingPriceLMTD.get(label)));
1064
		 } else {
1065
		 lmtdUnActivatedImeisValues.add(0.0);
1066
		 }
26055 tejbeer 1067
 
28430 tejbeer 1068
		 lmtdValues.add(lmtdBrandWiseSale.get(label) == null ? 0 : lmtdBrandWiseSale.get(label));
1069
		 }
1070
		 DatasetModel dsmtotal = new DatasetModel();
1071
		 dsmtotal.setLabel("MTD");
1072
		 dsmtotal.setBackgroundColor("blue");
1073
		 dsmtotal.setBorderColor("blue");
1074
		 dsmtotal.setData(mtdValues);
1075
		 dsmtotal.setStack("stack0");
1076
		 dsmtotal.setOrder(1);
26055 tejbeer 1077
 
28430 tejbeer 1078
		 DatasetModel dsmUnactivated = new DatasetModel();
1079
		 dsmUnactivated.setLabel("MTD Unactivated");
1080
		 dsmUnactivated.setBackgroundColor("red");
1081
		 dsmUnactivated.setBorderColor("red");
1082
		 dsmUnactivated.setData(mtdUnActivatedImeisValues);
1083
		 dsmUnactivated.setStack("stack0");
1084
		 dsmUnactivated.setOrder(1);
27884 tejbeer 1085
 
28430 tejbeer 1086
		 LOGGER.info("mtdValuesMoney" + mtdValues);
27884 tejbeer 1087
 
28430 tejbeer 1088
		 DatasetModel mtdActivatedImeis = new DatasetModel();
1089
		 mtdActivatedImeis.setLabel("MTD Activation");
1090
		 mtdActivatedImeis.setBorderColor("#00008b");
1091
		 mtdActivatedImeis.setData(mtdActivatedImeisValues);
1092
		 mtdActivatedImeis.setBackgroundColor("#00008b");
1093
		 mtdActivatedImeis.setStack("stack0");
1094
		 mtdActivatedImeis.setOrder(1);
27884 tejbeer 1095
 
28430 tejbeer 1096
		 DatasetModel lmtddsmtotal = new DatasetModel();
1097
		 lmtddsmtotal.setLabel("LMTD");
1098
		 lmtddsmtotal.setBackgroundColor("blue");
1099
		 lmtddsmtotal.setData(lmtdValues);
1100
		 lmtddsmtotal.setBorderColor("blue");
1101
		 lmtddsmtotal.setStack("stack1");
1102
		 lmtddsmtotal.setOrder(1);
27884 tejbeer 1103
 
28430 tejbeer 1104
		 DatasetModel lmtdUnActivated = new DatasetModel();
1105
		 lmtdUnActivated.setLabel("LMTD Unactivation");
1106
		 lmtdUnActivated.setBackgroundColor("red");
1107
		 lmtdUnActivated.setBorderColor("red");
1108
		 lmtdUnActivated.setData(lmtdUnActivatedImeisValues);
1109
		 lmtdUnActivated.setStack("stack1");
1110
		 lmtdUnActivated.setOrder(1);
27884 tejbeer 1111
 
28430 tejbeer 1112
		 DatasetModel LmtdActivatedImeis = new DatasetModel();
1113
		 LmtdActivatedImeis.setLabel("LMTD Activation");
1114
		 LmtdActivatedImeis.setBackgroundColor("#87ceeb");
1115
		 LmtdActivatedImeis.setBorderColor("#87ceeb");
1116
		 LmtdActivatedImeis.setData(lmtdActivatedImeisValues);
1117
		 LmtdActivatedImeis.setStack("stack1");
1118
		 LmtdActivatedImeis.setOrder(1);
27930 amit.gupta 1119
 
28430 tejbeer 1120
		 DatasetModel linemtdChart = new DatasetModel();
1121
		 linemtdChart.setLabel("MTD");
1122
		 linemtdChart.setBackgroundColor("#006400");
1123
		 linemtdChart.setBorderColor("#006400");
1124
		 linemtdChart.setData(mtdValues);
1125
		 linemtdChart.setType("line");
1126
		 linemtdChart.setOrder(2);
1127
		 linemtdChart.setFill("false");
27930 amit.gupta 1128
 
28430 tejbeer 1129
		 DatasetModel lineLmtdChart = new DatasetModel();
1130
		 lineLmtdChart.setLabel("LMTD");
1131
		 lineLmtdChart.setBackgroundColor("hotpink");
1132
		 lineLmtdChart.setBorderColor("hotpink");
1133
		 lineLmtdChart.setData(lmtdValues);
1134
		 lineLmtdChart.setType("line");
1135
		 lineLmtdChart.setOrder(3);
1136
		 lineLmtdChart.setFill("false");
27930 amit.gupta 1137
 
28430 tejbeer 1138
		 List<DatasetModel> datasets = new ArrayList<>();
1139
		 datasets.add(mtdActivatedImeis);
1140
		 datasets.add(dsmUnactivated);
1141
		 datasets.add(LmtdActivatedImeis);
1142
		 datasets.add(lmtdUnActivated);
1143
		 datasets.add(linemtdChart);
1144
		 datasets.add(lineLmtdChart);
27884 tejbeer 1145
 
28430 tejbeer 1146
		 DataModel dm = new DataModel();
1147
		 dm.setDatasets(datasets);
1148
		 dm.setLabels(labels);
27884 tejbeer 1149
 
28430 tejbeer 1150
		 LegendModel lm = new LegendModel();
1151
		 lm.setPosition("top");
26055 tejbeer 1152
 
28430 tejbeer 1153
		 TitleModel tm = new TitleModel();
1154
		 tm.setText("Brand Wise Sales");
1155
		 tm.setDisplay(true);
26055 tejbeer 1156
 
28430 tejbeer 1157
		 List<Axis> xAxes = new ArrayList<>();
1158
		 Axis xAxis = new Axis();
1159
		 xAxis.setStacked(true);
1160
		 xAxes.add(xAxis);
26055 tejbeer 1161
 
28430 tejbeer 1162
		 List<Axis> yAxes = new ArrayList<>();
1163
		 Axis yAxis = new Axis();
1164
		 yAxis.setStacked(false);
1165
		 yAxes.add(yAxis);
27884 tejbeer 1166
 
28430 tejbeer 1167
		 ScalesModel sm = new ScalesModel();
1168
		 sm.setxAxes(xAxes);
27884 tejbeer 1169
 
28430 tejbeer 1170
		 OptionsModel om = new OptionsModel();
1171
		 om.setLegend(lm);
1172
		 om.setTitle(tm);
1173
		 om.setScales(sm);
27884 tejbeer 1174
 
28430 tejbeer 1175
		 cm.setType("bar");
1176
		 cm.setData(dm);
1177
		 cm.setOptions(om);
26055 tejbeer 1178
 
28430 tejbeer 1179
		 LOGGER.info("cm" + cm);
26055 tejbeer 1180
 
28430 tejbeer 1181
		 return cm;
27884 tejbeer 1182
 
28430 tejbeer 1183
		 }
26055 tejbeer 1184
 
1185
 
26418 tejbeer 1186
	private String adminPanel(int fofoId, String email, Model model) throws Exception {
26022 amit.gupta 1187
		List<Menu> menus = null;
26011 amit.gupta 1188
		try {
1189
			AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1190
			List<Position> positions = positionRepository.selectAll(authUser.getId());
27545 tejbeer 1191
			Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
27628 tejbeer 1192
			ReporticoCacheTable rctSaholic = null;
1193
			ReporticoCacheTable rctPartneStat = null;
1194
 
27509 tejbeer 1195
			Map<Integer, WarehouseWiseStockModel> warehouseStockMap = new HashMap<>();
27701 tejbeer 1196
			LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
1197
 
27509 tejbeer 1198
			Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27539 tejbeer 1199
			LinkedHashMap<Integer, String> wm = new LinkedHashMap<Integer, String>();
27701 tejbeer 1200
 
27670 tejbeer 1201
			Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
27594 tejbeer 1202
			List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
27701 tejbeer 1203
 
27819 tejbeer 1204
			Map<AuthUser, Long> authUserTicketCount = null;
1205
 
27539 tejbeer 1206
			for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
1207
				wm.put(entry.getKey(), entry.getValue());
1208
			}
1209
 
1210
			wm.put(0, "Total Values");
1211
			long stockValue = 0;
1212
			long stockQty = 0;
1213
			long pendingIndent = 0;
27542 tejbeer 1214
			long tertiary = 0;
26418 tejbeer 1215
 
27701 tejbeer 1216
			Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
27727 tejbeer 1217
 
27701 tejbeer 1218
			Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
27727 tejbeer 1219
			if (emails.contains(authUser.getEmailId())) {
1220
				fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
27930 amit.gupta 1221
				LOGGER.info("fofoIds" + fofoIds);
27727 tejbeer 1222
			}
27556 tejbeer 1223
 
27701 tejbeer 1224
			if (fofoIds != null) {
27539 tejbeer 1225
 
27701 tejbeer 1226
				Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1227
						.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
1228
						.collect(Collectors.groupingBy(FofoStore::getWarehouseId,
1229
								Collectors.mapping(FofoStore::getId, Collectors.toList())));
1230
				// warehouseStock
1231
				List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
1232
						.selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1233
 
1234
				warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1235
 
1236
				if (!warehouseStockMap.isEmpty()) {
1237
					for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
1238
						stockValue += warehouseStock.getValue().getStockValue();
1239
						stockQty += warehouseStock.getValue().getStockQty();
1240
						pendingIndent += warehouseStock.getValue().getPendingIndent();
1241
						tertiary += warehouseStock.getValue().getTertiary();
27539 tejbeer 1242
					}
27701 tejbeer 1243
					WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
1244
					ws.setStockQty(stockQty);
1245
					ws.setStockValue(stockValue);
1246
					ws.setPendingIndent(pendingIndent);
1247
					ws.setTertiary(tertiary);
1248
					ws.setWarehouseId(0);
1249
					warehouseStockMap.put(0, ws);
27591 tejbeer 1250
 
27701 tejbeer 1251
				}
27670 tejbeer 1252
 
27701 tejbeer 1253
				warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
1254
						.forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
27670 tejbeer 1255
 
27701 tejbeer 1256
				rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
1257
 
1258
				// warehouseStock
1259
				warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
1260
				rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
1261
 
1262
				partnersBrandSaleMap = fofoStoreRepository
1263
						.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream()
1264
						.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1265
 
1266
				List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
1267
						.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
1268
				for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
1269
					BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
1270
					if (bpt != null) {
1271
						bpt.setAmtd(un.getUnbilledMtd());
1272
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1273
					} else {
1274
						bpt = new BrandWisePartnerSaleModel();
1275
						bpt.setBrand(un.getBrand());
1276
						bpt.setAmtd(un.getUnbilledMtd());
1277
						bpt.setUamtdQty(un.getUnbilledMTDQty());
1278
						bpt.setLms(0);
1279
						bpt.setLmtd(0);
1280
						bpt.setMtd(0);
1281
						bpt.setMtdQty(0);
1282
						bpt.setLmtd(0);
1283
						bpt.setLmtdQty(0);
1284
						partnersBrandSaleMap.put(un.getBrand(), bpt);
27670 tejbeer 1285
					}
26418 tejbeer 1286
				}
27701 tejbeer 1287
				accessoriesBrandSales = fofoStoreRepository
1288
						.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
28272 tejbeer 1289
				Set<CustomRetailer> positionRetailers = fofoIds.stream()
1290
						.map(x -> retailerService.getAllFofoRetailers().get(x)).filter(x -> x != null)
1291
						.collect(Collectors.toSet());
27931 amit.gupta 1292
				model.addAttribute("retailers", gson.toJson(positionRetailers));
1293
				model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
1294
				model.addAttribute("warehouses", getWarehouses(positionRetailers));
26418 tejbeer 1295
			}
1296
 
27819 tejbeer 1297
			if (positions.size() > 0) {
1298
				if (positions.stream()
1299
						.filter(x -> x.getEscalationType().equals(EscalationType.L3)
1300
								|| x.getEscalationType().equals(EscalationType.L4)
1301
								|| x.getEscalationType().equals(EscalationType.L5))
1302
						.count() > 0) {
1303
					authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
1304
				}
1305
			}
1306
 
27415 tejbeer 1307
			if (Arrays.asList("amit.gupta@shop2020.in", "tejbeer.kaur@shop2020.in", "manish.tiwari@smartdukaan.com")
27701 tejbeer 1308
					.contains(email))
1309
 
1310
			{
26029 amit.gupta 1311
				menus = menuRepository.selectAll();
1312
			} else if (positions.size() > 0) {
27108 amit.gupta 1313
				if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
26028 amit.gupta 1314
					menus = menuRepository.selectAll();
27893 tejbeer 1315
				} else {
1316
					List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
1317
							.map(x -> x.getMenuId()).collect(Collectors.toList());
1318
					if (menuIds.size() > 0) {
1319
						menus = menuRepository.selectAllByIds(menuIds);
26028 amit.gupta 1320
					}
26022 amit.gupta 1321
				}
27930 amit.gupta 1322
			}
28272 tejbeer 1323
			/*
1324
			 * List<Position> salesPositions = positions.stream() .filter(x ->
1325
			 * x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1326
			 * .collect(Collectors.toList()); if (salesPositions.size() > 0) {
1327
			 * Set<CustomRetailer> positionRetailers = new HashSet<>();
1328
			 * csService.getPositionCustomRetailerMap(salesPositions).values().forEach(
1329
			 * customRetailers -> { positionRetailers.addAll(customRetailers); }); }
1330
			 */
1331
			if (fofoIds == null) {
1332
				List<Position> warehousePositions = positions.stream()
1333
						.filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
26090 amit.gupta 1334
						.collect(Collectors.toList());
28272 tejbeer 1335
				if (warehousePositions.size() > 0) {
26090 amit.gupta 1336
					Set<CustomRetailer> positionRetailers = new HashSet<>();
28272 tejbeer 1337
					csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
26090 amit.gupta 1338
						positionRetailers.addAll(customRetailers);
1339
					});
28272 tejbeer 1340
					model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
1341
					model.addAttribute("retailers", gson.toJson(positionRetailers));
1342
					model.addAttribute("warehouses", getWarehouses(positionRetailers));
26090 amit.gupta 1343
				}
28272 tejbeer 1344
			}
1345
			model.addAttribute("authId", authUser.getId());
26028 amit.gupta 1346
 
27628 tejbeer 1347
			model.addAttribute("rctPartneStat", rctPartneStat);
1348
 
1349
			model.addAttribute("reporticoDate", rctSaholic);
27545 tejbeer 1350
			model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
27539 tejbeer 1351
			model.addAttribute("warehouseMap", wm);
27819 tejbeer 1352
 
1353
			model.addAttribute("authUserTicketCount", authUserTicketCount);
27701 tejbeer 1354
			model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
27670 tejbeer 1355
			model.addAttribute("brandSalesMap", partnersBrandSaleMap);
27556 tejbeer 1356
 
27594 tejbeer 1357
			model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1358
 
26012 amit.gupta 1359
		} catch (ProfitMandiBusinessException e) {
26011 amit.gupta 1360
		}
26028 amit.gupta 1361
		List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
26422 tejbeer 1362
		LOGGER.info("menu" + menuList);
26022 amit.gupta 1363
		model.addAttribute("menu", menuList);
26012 amit.gupta 1364
		return "admin";
1365
	}
1366
 
26468 amit.gupta 1367
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1368
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1369
			throws Exception {
1370
 
1371
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1372
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1373
 
26468 amit.gupta 1374
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1375
		if (authId != 0) {
1376
			List<Integer> fofoIds = pp.get(authId);
1377
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1378
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1379
		} else {
26418 tejbeer 1380
		}
1381
 
1382
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1383
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1384
 
1385
		return "auth_user_partner_detail";
26468 amit.gupta 1386
	}
26418 tejbeer 1387
 
27545 tejbeer 1388
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1389
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1390
			throws Exception {
27701 tejbeer 1391
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1392
		String email = loginDetails.getEmailId();
1393
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1394
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27545 tejbeer 1395
 
27701 tejbeer 1396
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1397
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1398
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1399
 
27545 tejbeer 1400
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
27628 tejbeer 1401
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = this.getPartnersStatDataFromFile();
27545 tejbeer 1402
		if (warehouseId != 0) {
27701 tejbeer 1403
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1404
			/*
1405
			 * List<Integer> fofoIds =
1406
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1407
			 * .map(x -> x.getId()).collect(Collectors.toList());
1408
			 */
27545 tejbeer 1409
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1410
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1411
		} else {
27701 tejbeer 1412
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream()
1413
					.filter(x -> new ArrayList<>(authfofoIds).contains(x.getKey()))
1414
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1415
		}
1416
 
1417
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1418
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1419
 
1420
		return "auth_user_partner_detail";
1421
	}
1422
 
27509 tejbeer 1423
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1424
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1425
			@RequestParam List<Integer> warehouseId) throws Exception {
1426
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1427
		String email = loginDetails.getEmailId();
1428
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1429
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27509 tejbeer 1430
 
27701 tejbeer 1431
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1432
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1433
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1434
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1435
		if (!warehouseId.contains(0)) {
1436
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1437
		} else {
1438
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1439
			warehouseWiseBrandStock = saholicInventoryCISRepository
1440
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1441
 
1442
		}
27542 tejbeer 1443
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1444
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1445
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1446
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1447
 
27509 tejbeer 1448
		return "warehouse_brand_stock";
1449
	}
1450
 
27529 tejbeer 1451
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1452
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1453
		inventoryService.getItemAvailabilityAndIndent();
1454
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1455
		return "response";
1456
	}
1457
 
27701 tejbeer 1458
	public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
1459
			throws Exception {
27628 tejbeer 1460
 
1461
		Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
27701 tejbeer 1462
		// Map<Integer, List<FofoStore>> warehousePartnerMap =
1463
		// fofoStoreRepository.getWarehousePartnerMap();
27628 tejbeer 1464
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
27701 tejbeer 1465
		List<Integer> allfofoIds = new ArrayList<>();
27628 tejbeer 1466
		if (partnerStats != null) {
27701 tejbeer 1467
			for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
1468
				List<Integer> fofoIds = warehouse.getValue().stream().map(x -> x).collect(Collectors.toList());
1469
				allfofoIds.addAll(fofoIds);
27628 tejbeer 1470
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1471
						.collect(Collectors.toList());
27634 tejbeer 1472
				if (partnerDetails != null && !partnerDetails.isEmpty()) {
1473
					PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1474
					warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
1475
				}
27628 tejbeer 1476
 
1477
			}
27701 tejbeer 1478
			List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
1479
					.collect(Collectors.toList());
1480
			LOGGER.info("allPartnerDetails" + allPartnerDetails);
27628 tejbeer 1481
			PartnerDetailModel partnerDetailModel = partnerStatsService
27701 tejbeer 1482
					.getAggregateStats(new ArrayList<>(allPartnerDetails));
27628 tejbeer 1483
			warehouseIdAndallValues.put(0, partnerDetailModel);
1484
		}
1485
		return warehouseIdAndallValues;
1486
	}
1487
 
1488
	@RequestMapping(value = "/getPartnersStatData", method = RequestMethod.GET)
1489
	public String getPartnersStatData(HttpServletRequest request, Model model) throws Exception {
1490
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
1491
		ObjectOutputStream oos = null;
1492
		FileOutputStream fout = null;
1493
		try {
1494
			fout = new FileOutputStream("/tmp/partnerStat.tmp", false);
1495
			oos = new ObjectOutputStream(fout);
1496
			oos.writeObject(partnerStats);
1497
 
1498
		} catch (Exception ex) {
1499
			ex.printStackTrace();
1500
		} finally {
1501
			if (oos != null) {
1502
				oos.close();
1503
			}
1504
		}
1505
		ReporticoCacheTable rct = reporticoCacheTableRepository.selectByTableName("partnerStat");
1506
		if (rct == null) {
1507
			rct = new ReporticoCacheTable();
1508
			rct.setTableName("partnerStat");
1509
 
1510
		}
1511
		rct.setLastCreatedTimestamp(LocalDateTime.now());
1512
		reporticoCacheTableRepository.persist(rct);
1513
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1514
		return "response";
1515
	}
1516
 
1517
	public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
1518
		ObjectInputStream objectinputstream = null;
1519
		Map<Integer, PartnerDetailModel> partnerStat = null;
1520
		try {
1521
			FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
1522
			objectinputstream = new ObjectInputStream(streamIn);
1523
			partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
1524
 
1525
			LOGGER.info("partnerStat" + partnerStat);
1526
			objectinputstream.close();
1527
 
1528
		} catch (Exception e) {
1529
			LOGGER.info("exceptionddd" + e);
1530
 
1531
			e.printStackTrace();
1532
 
1533
		} finally {
1534
			if (objectinputstream != null) {
1535
				objectinputstream.close();
1536
				LOGGER.info("clofddd" + partnerStat);
1537
 
1538
			}
1539
		}
1540
		return partnerStat;
1541
 
1542
	}
1543
 
27539 tejbeer 1544
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1545
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
27538 tejbeer 1546
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1547
			throws Exception {
27509 tejbeer 1548
 
1549
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1550
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1551
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1552
 
27509 tejbeer 1553
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1554
		model.addAttribute("brands", listbrands);
27538 tejbeer 1555
		model.addAttribute("listCategory", listCategory);
1556
 
27529 tejbeer 1557
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1558
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1559
		model.addAttribute("selectedCategory", category);
1560
 
27509 tejbeer 1561
		return "warehouse_brand_item_stock";
1562
	}
1563
 
27538 tejbeer 1564
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1565
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1566
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1567
			throws Exception {
27539 tejbeer 1568
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1569
		if (warehouseId.contains(0)) {
1570
			warehouseId.addAll(warehouseMap.keySet());
1571
		}
27538 tejbeer 1572
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1573
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1574
 
27538 tejbeer 1575
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1576
		model.addAttribute("warehouseMap", warehouseMap);
1577
		return "warehouse_item_details";
1578
	}
1579
 
26114 amit.gupta 1580
	private String getWarehouses(Set<CustomRetailer> positionRetailers) {
1581
		Map<Integer, String> warehouses = new HashMap<>();
26222 tejbeer 1582
		positionRetailers.stream().forEach(x -> {
1583
			if (x.getWarehouseId() != 0) {
26171 amit.gupta 1584
				warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
1585
			}
1586
		});
26114 amit.gupta 1587
		return gson.toJson(warehouses);
1588
 
1589
	}
1590
 
27556 tejbeer 1591
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1592
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1593
			throws Exception {
27701 tejbeer 1594
 
1595
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1596
		String email = loginDetails.getEmailId();
1597
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1598
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1599
 
27670 tejbeer 1600
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1601
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1602
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1603
 
1604
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1605
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1606
 
1607
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1608
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1609
			if (bpt != null) {
1610
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 1611
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1612
			} else {
1613
				bpt = new WarehouseWiseBrandSaleModel();
1614
				bpt.setWarehouseId(un.getWarehouseId());
1615
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 1616
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1617
				bpt.setLms(0);
1618
				bpt.setLmtd(0);
1619
				bpt.setMtd(0);
1620
				bpt.setMtdQty(0);
1621
				bpt.setLmtd(0);
1622
				bpt.setLmtdQty(0);
1623
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1624
			}
1625
		}
27556 tejbeer 1626
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1627
 
1628
		Set<String> brands = inventoryService.getAllTagListingBrands();
1629
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1630
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1631
		model.addAttribute("brands", brands);
1632
		model.addAttribute("selectedbrand", brand);
1633
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1634
	}
1635
 
27594 tejbeer 1636
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1637
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1638
			@RequestParam String brand) throws Exception {
27701 tejbeer 1639
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1640
		String email = loginDetails.getEmailId();
1641
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1642
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1643
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1644
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1645
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1646
 
1647
		Set<String> brands = inventoryService.getAllTagListingBrands();
1648
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1649
		model.addAttribute("warehouseMap", warehouseMap);
1650
		model.addAttribute("brands", brands);
1651
		model.addAttribute("selectedbrand", brand);
1652
		return "warehousewise_accessoriesbrand_sale";
1653
	}
1654
 
27556 tejbeer 1655
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1656
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1657
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1658
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1659
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1660
		String email = loginDetails.getEmailId();
1661
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1662
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27670 tejbeer 1663
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 1664
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1665
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1666
 
1667
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 1668
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1669
 
1670
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1671
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1672
			if (bpt != null) {
1673
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 1674
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1675
			} else {
1676
				bpt = new WarehouseBrandWiseItemSaleModel();
1677
				bpt.setWarehouseId(un.getWarehouseId());
1678
				bpt.setItemId(un.getItemId());
1679
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 1680
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1681
				bpt.setBrand(un.getBrand());
1682
				bpt.setModelName(un.getModelName());
1683
				bpt.setModelNumber(un.getModelNumber());
1684
				bpt.setColor(un.getColor());
1685
				bpt.setLms(0);
1686
				bpt.setLmtd(0);
1687
				bpt.setMtd(0);
1688
				bpt.setMtdQty(0);
1689
				bpt.setLmtd(0);
1690
				bpt.setLmtdQty(0);
1691
				branditemSalesMap.put(un.getItemId(), bpt);
1692
			}
1693
		}
1694
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 1695
		model.addAttribute("warehouseMap", warehouseMap);
1696
		return "warehouse_partner_itemwise_sale";
1697
	}
1698
 
27594 tejbeer 1699
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1700
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1701
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1702
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1703
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1704
		String email = loginDetails.getEmailId();
1705
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1706
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1707
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 1708
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1709
		model.addAttribute("branditemSales", branditemSales);
1710
		model.addAttribute("warehouseMap", warehouseMap);
1711
		return "warehouse_accessories_itemwsie_sale";
1712
	}
1713
 
26012 amit.gupta 1714
	private List<Menu> prepareMenu(List<Menu> menus) {
1715
		List<Menu> returnMenu = new ArrayList<>();
1716
		Map<Menu, List<Menu>> subMenuMap = new HashMap<Menu, List<Menu>>();
1717
		for (Menu menu : menus) {
1718
			if (menu.get_parent() == null) {
26014 amit.gupta 1719
				if (!subMenuMap.containsKey(menu)) {
26012 amit.gupta 1720
					subMenuMap.put(menu, new ArrayList<>());
26011 amit.gupta 1721
				}
1722
			} else {
26012 amit.gupta 1723
				Menu parentMenu = menu.get_parent();
1724
				if (!subMenuMap.containsKey(parentMenu)) {
1725
					subMenuMap.put(parentMenu, new ArrayList<>());
26011 amit.gupta 1726
				}
26012 amit.gupta 1727
				subMenuMap.get(parentMenu).add(menu);
26011 amit.gupta 1728
			}
1729
		}
26012 amit.gupta 1730
		subMenuMap.entrySet().stream().forEach(entry -> {
1731
			entry.getKey().setSubMenus(entry.getValue());
1732
			returnMenu.add(entry.getKey());
1733
		});
1734
		return returnMenu;
26005 amit.gupta 1735
	}
1736
 
24288 amit.gupta 1737
	// This method is currently hardcoded to faciliate watches sold as gift.
24203 amit.gupta 1738
	private boolean hasGift(int fofoId) {
1739
		try {
24288 amit.gupta 1740
			return currentInventorySnapshotRepository.selectByItemIdAndFofoId(ProfitMandiConstants.GIFT_ID, fofoId)
1741
					.getAvailability() > 0;
24203 amit.gupta 1742
		} catch (ProfitMandiBusinessException e) {
1743
			return false;
1744
		}
1745
	}
24288 amit.gupta 1746
 
22354 ashik.ali 1747
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1748
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1749
		model.addAttribute("appContextPath", request.getContextPath());
1750
		return "contact-us";
1751
	}
23923 amit.gupta 1752
 
25649 tejbeer 1753
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1754
	public String getNotificationsWithType(HttpServletRequest request,
1755
			@RequestParam(required = false) MessageType messageType,
25649 tejbeer 1756
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1757
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1758
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1759
		int userId = 0;
1760
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1761
		if (isAdmin) {
1762
			userId = loginDetails.getFofoId();
1763
		} else {
1764
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1765
		}
25683 tejbeer 1766
		List<Notification> notifications = null;
1767
 
26086 tejbeer 1768
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1769
				userId, offset, limit);
1770
		LOGGER.info("messageType" + messageType);
1771
		notifications = getNotifications(notificationCampaigns, messageType);
1772
 
25683 tejbeer 1773
		model.addAttribute("notifications", notifications);
1774
 
1775
		LOGGER.info("notifications" + notifications);
1776
		return "notification-template";
1777
	}
1778
 
1779
	public List<Notification> getNotifications(List<NotificationCampaign> nc, MessageType messageType)
1780
			throws ProfitMandiBusinessException {
1781
		List<Notification> notifications = new ArrayList<>();
1782
		Document document = null;
1783
		if (messageType != null) {
1784
			for (NotificationCampaign notificationCampaign : nc) {
1785
				if (notificationCampaign.getMessageType() == messageType) {
25649 tejbeer 1786
					Notification ns = new Notification();
1787
					SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1788
							SimpleCampaignParams.class);
1789
					Campaign campaign = new SimpleCampaign(scp);
1790
					LocalDateTime expire = campaign.getExpireTimestamp();
1791
					ns.setCid(Integer.toString(notificationCampaign.getId()));
1792
					ns.setType(campaign.getType());
1793
					ns.setMessage(campaign.getMessage());
1794
					ns.setTitle(campaign.getTitle());
25651 tejbeer 1795
					if (notificationCampaign.getDocumentId() != null) {
1796
						document = documentRepository.selectById(notificationCampaign.getDocumentId());
1797
						ns.setDocumentName(document.getDisplayName());
1798
					}
25683 tejbeer 1799
					ns.setUrl(campaign.getUrl());
25649 tejbeer 1800
					ns.setShowImage(campaign.getShowImage());
1801
					ns.setImageUrl(campaign.getImageUrl());
25683 tejbeer 1802
					ns.setDocumentId(notificationCampaign.getDocumentId());
1803
					ns.setMessageType(notificationCampaign.getMessageType());
25649 tejbeer 1804
					ns.setCreated(
1805
							notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1806
									* 1000);
1807
					if (LocalDateTime.now().isAfter(expire)) {
1808
						ns.setExpired(true);
1809
					} else {
1810
						ns.setExpired(false);
1811
					}
1812
					notifications.add(ns);
1813
				}
1814
			}
25683 tejbeer 1815
		} else {
1816
			for (NotificationCampaign notificationCampaign : nc) {
1817
 
1818
				Notification ns = new Notification();
1819
				SimpleCampaignParams scp = gson.fromJson(notificationCampaign.getImplementationParams(),
1820
						SimpleCampaignParams.class);
1821
				Campaign campaign = new SimpleCampaign(scp);
1822
				LocalDateTime expire = campaign.getExpireTimestamp();
1823
				ns.setCid(Integer.toString(notificationCampaign.getId()));
1824
				ns.setType(campaign.getType());
1825
				ns.setMessage(campaign.getMessage());
1826
				ns.setTitle(campaign.getTitle());
1827
				if (notificationCampaign.getDocumentId() != null) {
1828
					document = documentRepository.selectById(notificationCampaign.getDocumentId());
1829
					ns.setDocumentName(document.getDisplayName());
1830
				}
1831
				ns.setUrl(campaign.getUrl());
1832
				ns.setShowImage(campaign.getShowImage());
1833
				ns.setImageUrl(campaign.getImageUrl());
1834
				ns.setDocumentId(notificationCampaign.getDocumentId());
1835
				ns.setMessageType(notificationCampaign.getMessageType());
1836
				ns.setCreated(notificationCampaign.getCreatedTimestamp().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30))
1837
						* 1000);
1838
				if (LocalDateTime.now().isAfter(expire)) {
1839
					ns.setExpired(true);
1840
				} else {
1841
					ns.setExpired(false);
1842
				}
1843
				notifications.add(ns);
1844
			}
1845
 
25649 tejbeer 1846
		}
25683 tejbeer 1847
		return notifications;
25651 tejbeer 1848
 
1849
	}
25649 tejbeer 1850
 
25651 tejbeer 1851
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1852
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1853
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1854
			throws ProfitMandiBusinessException {
1855
		Document document = documentRepository.selectById(documentId);
1856
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1857
		if (nc.getDocumentId() == null) {
1858
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1859
		}
1860
		if (nc.getDocumentId() != documentId) {
1861
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1862
		}
1863
		return responseSender.ok(document);
25649 tejbeer 1864
	}
1865
 
25651 tejbeer 1866
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1867
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1868
			throws ProfitMandiBusinessException {
1869
 
1870
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1871
 
1872
		if (nc.getDocumentId() == null) {
1873
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1874
		}
1875
 
1876
		Document document = documentRepository.selectById(nc.getDocumentId());
1877
 
1878
		FileInputStream file = null;
1879
		try {
1880
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1881
		} catch (FileNotFoundException e) {
1882
			LOGGER.error("Retailer Document file not found : ", e);
1883
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1884
		}
1885
		// ByteArrayOutputStream byteArrayOutputStream = new
1886
		// ByteArrayOutputStream();
1887
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1888
 
1889
		final HttpHeaders headers = new HttpHeaders();
1890
		String contentType = "";
1891
		if (document.getContentType() == ContentType.JPEG) {
1892
			contentType = "image/jpeg";
1893
		} else if (document.getContentType() == ContentType.PNG) {
1894
			contentType = "image/png";
1895
		} else if (document.getContentType() == ContentType.PDF) {
1896
			contentType = "application/pdf";
1897
		}
1898
		headers.set("Content-Type", contentType);
1899
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1900
		headers.setContentLength(document.getSize());
1901
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1902
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1903
	}
26460 amit.gupta 1904
 
1905
	public Map<Integer, PartnerDetailModel> getL2AuthUserPartnerDetail() throws Exception {
26445 amit.gupta 1906
		LOGGER.info("getL2AuthUserPartnerDetail Started");
26460 amit.gupta 1907
		Map<Integer, List<Integer>> L2L1Mapping = csService.getL2L1Mapping();
26422 tejbeer 1908
		Map<Integer, Integer> authIdAndleadsCountMap = new HashMap<>();
1909
		for (Entry<Integer, List<Integer>> l2l1 : L2L1Mapping.entrySet()) {
1910
			List<Integer> authIds = l2l1.getValue();
1911
			authIds.add(l2l1.getKey());
1912
 
1913
			List<Lead> leads = leadRepository.selectByAssignAuthIdsAndStatus(authIds, LeadStatus.followUp);
26433 tejbeer 1914
			LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1915
			AuthUser auth = authRepository.selectById(l2l1.getKey());
26431 tejbeer 1916
			if (!leads.isEmpty()) {
1917
				authIdAndleadsCountMap.put(auth.getId(), leads.size());
1918
			} else {
1919
				authIdAndleadsCountMap.put(auth.getId(), 0);
1920
			}
26422 tejbeer 1921
		}
26468 amit.gupta 1922
 
26460 amit.gupta 1923
		Map<Integer, PartnerDetailModel> partnerStats = partnerStatsService.getAllPartnerStats();
27352 tejbeer 1924
		List<Integer> unmappedPartners = partnerStats.entrySet().stream().map(x -> x.getKey())
1925
				.collect(Collectors.toList());
26433 tejbeer 1926
		LOGGER.info("authIdAndleadsCountMap" + authIdAndleadsCountMap);
26422 tejbeer 1927
 
26460 amit.gupta 1928
		Map<Integer, PartnerDetailModel> authIdAndallValues = new LinkedHashMap<>();
26422 tejbeer 1929
 
26460 amit.gupta 1930
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1931
		for (int authUserId : pp.keySet()) {
1932
			if (L2L1Mapping.keySet().contains(authUserId)) {
1933
				List<Integer> fofoIds = pp.get(authUserId);
26997 amit.gupta 1934
				unmappedPartners.removeAll(fofoIds);
26468 amit.gupta 1935
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
1936
						.collect(Collectors.toList());
27632 tejbeer 1937
				LOGGER.info("authUserId {}, partnerDetails2 {}" + authUserId, partnerDetails);
26460 amit.gupta 1938
				PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
1939
				authIdAndallValues.put(authUserId, partnerDetailModel);
26422 tejbeer 1940
			}
1941
		}
26997 amit.gupta 1942
		List<PartnerDetailModel> unmappedPartnerDetails = unmappedPartners.stream().map(x -> partnerStats.get(x))
1943
				.collect(Collectors.toList());
26468 amit.gupta 1944
		PartnerDetailModel partnerDetailModel = partnerStatsService
1945
				.getAggregateStats(new ArrayList<>(partnerStats.values()));
27000 amit.gupta 1946
		authIdAndallValues.put(-1, partnerStatsService.getAggregateStats(unmappedPartnerDetails));
26460 amit.gupta 1947
		authIdAndallValues.put(0, partnerDetailModel);
26422 tejbeer 1948
		return authIdAndallValues;
1949
	}
1950
 
27579 tejbeer 1951
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1952
	public String getItemWiseTertiary(HttpServletRequest request,
1953
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1954
			throws ProfitMandiBusinessException {
1955
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1956
 
1957
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1958
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1959
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1960
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1961
		return "item-wise-tertiary";
1962
	}
1963
 
27586 tejbeer 1964
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1965
	public String getItemWiseIndent(HttpServletRequest request,
1966
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1967
			throws ProfitMandiBusinessException {
1968
 
1969
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1970
		model.addAttribute("unbilledOrders", unbilledOrders);
1971
 
1972
		return "item-wise-indent";
1973
	}
1974
 
27636 tejbeer 1975
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1976
	public String getPartnerInvestment(HttpServletRequest request,
1977
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1978
		Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
1979
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1980
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1981
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1982
		model.addAttribute("customRetailer", customRetailer);
1983
		return "partner-investment";
1984
	}
27727 tejbeer 1985
 
27704 amit.gupta 1986
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1987
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1988
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1989
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1990
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 1991
 
27704 amit.gupta 1992
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1993
		return "partner-pending-indent-item";
1994
	}
1995
 
27636 tejbeer 1996
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1997
	public String getPartnerActivateStockItem(HttpServletRequest request,
1998
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1999
		List<ActivateItemModel> activateStocks = new ArrayList<>();
2000
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2001
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2002
 
2003
		for (InventoryItem inventoryItem : inventoryItems) {
2004
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
2005
			Item item = itemRepository.selectById(inventoryItem.getItemId());
2006
			ActivateItemModel aim = new ActivateItemModel();
2007
			aim.setFofoId(inventoryItem.getFofoId());
2008
			aim.setQuantity(inventoryItem.getGoodQuantity());
2009
			aim.setAmount(tagListing.getSellingPrice());
2010
			aim.setItemDescription(item.getItemDescription());
2011
			aim.setItemId(inventoryItem.getItemId());
2012
			activateStocks.add(aim);
2013
		}
2014
 
2015
		model.addAttribute("activateStocks", activateStocks);
2016
		model.addAttribute("customRetailer", customRetailer);
2017
		return "partner-activate-stock";
2018
	}
2019
 
2020
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
2021
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
2022
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2023
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2024
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2025
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
2026
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 2027
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
2028
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 2029
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2030
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 2031
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2032
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
2033
 
27636 tejbeer 2034
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
2035
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 2036
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 2037
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 2038
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
2039
 
27636 tejbeer 2040
		model.addAttribute("customRetailer", customRetailer);
2041
		return "partner-brand-mtd-sale";
2042
	}
2043
 
27637 tejbeer 2044
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
2045
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
2046
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2047
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2048
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2049
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
2050
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 2051
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
2052
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 2053
 
2054
		Double accesorieslmtdsale = fofoOrderRepository
2055
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
2056
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
2057
				.get(fofoId);
27638 tejbeer 2058
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
2059
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
2060
				Optional.of(false)).get(fofoId);
2061
 
27637 tejbeer 2062
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 2063
		model.addAttribute("brandLmtdQty", brandLmtdQty);
2064
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 2065
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
2066
		model.addAttribute("customRetailer", customRetailer);
2067
		return "partner-brand-lmtd-sale";
2068
	}
2069
 
27660 tejbeer 2070
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
2071
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
2072
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2073
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2074
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2075
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2076
 
2077
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 2078
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2079
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 2080
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2081
 
27893 tejbeer 2082
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
2083
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 2084
		Long accesorieslmsqty = fofoOrderRepository
2085
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 2086
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 2087
				.get(fofoId);
2088
 
2089
		model.addAttribute("brandLMSAmount", brandLMSAmount);
2090
		model.addAttribute("brandLmsQty", brandLmsQty);
2091
		model.addAttribute("accesorieslmssale", accesorieslmssale);
2092
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
2093
		model.addAttribute("customRetailer", customRetailer);
2094
		return "partner-brand-lms-sale";
2095
	}
2096
 
27640 tejbeer 2097
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
2098
	public String getPatnerInStock(HttpServletRequest request,
2099
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2100
 
2101
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2102
 
27660 tejbeer 2103
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 2104
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 2105
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 2106
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
2107
 
27660 tejbeer 2108
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
2109
				.selectInStockItemsByBrand(fofoId);
2110
 
2111
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
2112
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2113
 
2114
		model.addAttribute("stockItemMap", stockItemMap);
2115
		model.addAttribute("mobileStock", mobileStocks);
2116
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 2117
		model.addAttribute("customRetailer", customRetailer);
2118
		return "partner-instock-item";
2119
	}
2120
 
27660 tejbeer 2121
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
2122
	public String getOpenTicketByFofoId(HttpServletRequest request,
2123
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
2124
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
2125
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2126
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
2127
				.collect(Collectors.toList());
2128
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
2129
 
2130
		for (TicketAssigned ticketAssign : ticketAssigns) {
2131
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
2132
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
2133
		}
2134
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
2135
		model.addAttribute("ticketAssigns", ticketAssigns);
2136
		model.addAttribute("customRetailer", customRetailer);
2137
		return "open-ticket";
2138
	}
2139
 
27893 tejbeer 2140
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
2141
	public String getPartnerSecondarySale(HttpServletRequest request,
2142
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
2143
			throws Exception {
2144
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
2145
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2146
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2147
		LocalDateTime startDate = null;
2148
		LocalDateTime endDate = null;
2149
		List<InStockBrandModel> secondarySale = null;
2150
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
2151
 
2152
		if (timeValue.equals("mtd")) {
2153
			startDate = curDate.withDayOfMonth(1);
2154
			endDate = curDate.with(LocalTime.MAX);
2155
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2156
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2157
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2158
			LOGGER.info("secondarySalemtd" + secondarySale);
2159
		} else if (timeValue.equals("lmtd")) {
2160
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2161
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
2162
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2163
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2164
 
2165
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2166
			LOGGER.info("secondarySalelmtd" + secondarySale);
2167
 
2168
		} else {
2169
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
2170
			endDate = curDate.withDayOfMonth(1);
2171
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
2172
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2173
 
2174
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2175
			LOGGER.info("secondarySalelms" + secondarySale);
2176
 
2177
		}
2178
 
2179
		LOGGER.info("secondarySale" + secondarySale);
2180
		model.addAttribute("secondarySale", secondarySale);
2181
		model.addAttribute("secondaryItemSale", secondaryItemSale);
2182
		model.addAttribute("customRetailer", customRetailer);
2183
 
2184
		return "partner-secondary-order";
2185
	}
2186
 
21615 kshitij.so 2187
}