Subversion Repositories SmartDukaan

Rev

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