Subversion Repositories SmartDukaan

Rev

Rev 31521 | Rev 31751 | 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
 
25649 tejbeer 3
import com.google.gson.Gson;
28825 tejbeer 4
import com.mongodb.DBObject;
25651 tejbeer 5
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 6
import com.spice.profitmandi.common.enumuration.MessageType;
22481 ashik.ali 7
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
31337 amit.gupta 8
import com.spice.profitmandi.common.model.*;
25651 tejbeer 9
import com.spice.profitmandi.common.web.util.ResponseSender;
26011 amit.gupta 10
import com.spice.profitmandi.dao.entity.auth.AuthUser;
27355 tejbeer 11
import com.spice.profitmandi.dao.entity.catalog.Item;
27636 tejbeer 12
import com.spice.profitmandi.dao.entity.catalog.TagListing;
28471 tejbeer 13
import com.spice.profitmandi.dao.entity.cs.Position;
27660 tejbeer 14
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
25651 tejbeer 15
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 16
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
31337 amit.gupta 17
import com.spice.profitmandi.dao.entity.fofo.*;
29720 manish 18
import com.spice.profitmandi.dao.entity.transaction.LineItem;
27586 tejbeer 19
import com.spice.profitmandi.dao.entity.transaction.Order;
29707 tejbeer 20
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
31259 tejbeer 21
import com.spice.profitmandi.dao.enumuration.fofo.Milestone;
28409 tejbeer 22
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
29707 tejbeer 23
import com.spice.profitmandi.dao.model.SamsungUpgradeOfferModel;
31337 amit.gupta 24
import com.spice.profitmandi.dao.model.*;
25976 amit.gupta 25
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
27355 tejbeer 26
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
31337 amit.gupta 27
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
29707 tejbeer 28
import com.spice.profitmandi.dao.repository.catalog.SamsungUpgradeOfferRepository;
27632 tejbeer 29
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
31662 amit.gupta 30
import com.spice.profitmandi.dao.repository.cs.*;
31337 amit.gupta 31
import com.spice.profitmandi.dao.repository.dtr.*;
32
import com.spice.profitmandi.dao.repository.fofo.*;
27529 tejbeer 33
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
34
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
29720 manish 35
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
27893 tejbeer 36
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
28443 tejbeer 37
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
28468 tejbeer 38
import com.spice.profitmandi.service.AdminUser;
39
import com.spice.profitmandi.service.FofoUser;
24336 amit.gupta 40
import com.spice.profitmandi.service.PartnerInvestmentService;
26460 amit.gupta 41
import com.spice.profitmandi.service.PartnerStatsService;
23844 amit.gupta 42
import com.spice.profitmandi.service.authentication.RoleManager;
25677 amit.gupta 43
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 44
import com.spice.profitmandi.service.offers.OfferService;
27586 tejbeer 45
import com.spice.profitmandi.service.transaction.TransactionService;
26005 amit.gupta 46
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 47
import com.spice.profitmandi.web.model.LoginDetails;
48
import com.spice.profitmandi.web.util.CookiesProcessor;
27529 tejbeer 49
import com.spice.profitmandi.web.util.MVCResponseSender;
31337 amit.gupta 50
import org.apache.logging.log4j.LogManager;
51
import org.apache.logging.log4j.Logger;
52
import org.json.JSONObject;
53
import org.springframework.beans.factory.annotation.Autowired;
54
import org.springframework.beans.factory.annotation.Value;
55
import org.springframework.core.io.InputStreamResource;
56
import org.springframework.http.HttpHeaders;
57
import org.springframework.http.HttpStatus;
58
import org.springframework.http.ResponseEntity;
59
import org.springframework.stereotype.Controller;
60
import org.springframework.ui.Model;
61
import org.springframework.web.bind.annotation.PathVariable;
62
import org.springframework.web.bind.annotation.RequestMapping;
63
import org.springframework.web.bind.annotation.RequestMethod;
64
import org.springframework.web.bind.annotation.RequestParam;
22481 ashik.ali 65
 
31337 amit.gupta 66
import javax.servlet.http.HttpServletRequest;
67
import javax.transaction.Transactional;
68
import java.io.File;
69
import java.io.FileInputStream;
70
import java.io.FileNotFoundException;
71
import java.time.LocalDate;
72
import java.time.LocalDateTime;
73
import java.time.LocalTime;
74
import java.time.YearMonth;
75
import java.time.format.DateTimeFormatter;
76
import java.util.*;
77
import java.util.Map.Entry;
78
import java.util.stream.Collectors;
79
 
80
import static in.shop2020.model.v1.order.OrderStatus.*;
81
 
21615 kshitij.so 82
@Controller
25222 amit.gupta 83
@Transactional(rollbackOn = Throwable.class)
21615 kshitij.so 84
public class DashboardController {
23923 amit.gupta 85
 
27727 tejbeer 86
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
31129 tejbeer 87
			"amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com", "kanan.choudhary@smartdukaan.com");
27727 tejbeer 88
 
23379 ashik.ali 89
	@Value("${web.api.host}")
90
	private String webApiHost;
23923 amit.gupta 91
 
24072 amit.gupta 92
	@Value("${web.api.scheme}")
93
	private String webApiScheme;
24288 amit.gupta 94
 
31662 amit.gupta 95
	@Autowired
96
	private CsService1 csService1;
97
 
24078 amit.gupta 98
	@Value("${web.api.root}")
99
	private String webApiRoot;
100
 
23379 ashik.ali 101
	@Value("${web.api.port}")
102
	private int webApiPort;
28430 tejbeer 103
 
22481 ashik.ali 104
	@Autowired
28443 tejbeer 105
	private PriceDropRepository priceDropRepository;
106
 
107
	@Autowired
22927 ashik.ali 108
	private CookiesProcessor cookiesProcessor;
26468 amit.gupta 109
 
26460 amit.gupta 110
	@Autowired
28409 tejbeer 111
	private PendingOrderRepository pendingOrderRepository;
112
 
113
	@Autowired
26460 amit.gupta 114
	private PartnerStatsService partnerStatsService;
23923 amit.gupta 115
 
23568 govind 116
	@Autowired
26090 amit.gupta 117
	private CsService csService;
118
 
119
	@Autowired
25653 amit.gupta 120
	private ResponseSender<?> responseSender;
26012 amit.gupta 121
 
26005 amit.gupta 122
	@Autowired
123
	RetailerService retailerService;
25214 amit.gupta 124
 
125
	@Autowired
28468 tejbeer 126
	private AdminUser adminUser;
127
 
128
	@Autowired
23786 amit.gupta 129
	private RoleManager roleManager;
23923 amit.gupta 130
 
23838 ashik.ali 131
	@Autowired
132
	private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 133
 
134
	@Autowired
24880 govind 135
	private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 136
 
23884 amit.gupta 137
	@Autowired
25653 amit.gupta 138
	DocumentRepository documentRepository;
26236 amit.gupta 139
 
26234 amit.gupta 140
	@Autowired
141
	InventoryItemRepository inventoryItemRepository;
25683 tejbeer 142
 
25677 amit.gupta 143
	@Autowired
144
	InventoryService inventoryService;
23923 amit.gupta 145
 
23884 amit.gupta 146
	@Autowired
28409 tejbeer 147
	private PendingOrderItemRepository pendingOrderItemRepository;
148
 
149
	@Autowired
24203 amit.gupta 150
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
151
 
24880 govind 152
	@Autowired
153
	private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 154
 
26011 amit.gupta 155
	@Autowired
25566 tejbeer 156
	private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 157
 
24996 amit.gupta 158
	@Autowired
25649 tejbeer 159
	private HygieneDataRepository hygieneDataRepository;
160
 
161
	@Autowired
162
	private UserAccountRepository userAccountRepository;
163
 
164
	@Autowired
165
	private NotificationCampaignRepository notificationCampaignRepository;
166
 
167
	@Autowired
25976 amit.gupta 168
	private AuthRepository authRepository;
24880 govind 169
 
25649 tejbeer 170
	@Autowired
26071 tejbeer 171
	private FofoOrderRepository fofoOrderRepository;
172
 
173
	@Autowired
25649 tejbeer 174
	private Gson gson;
175
 
26418 tejbeer 176
	@Autowired
177
	TicketRepository ticketRepository;
178
 
179
	@Autowired
27876 amit.gupta 180
	private OfferService offerService;
181
 
182
	@Autowired
27355 tejbeer 183
	private ItemRepository itemRepository;
26588 tejbeer 184
 
27509 tejbeer 185
	@Autowired
27529 tejbeer 186
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
187
 
188
	@Autowired
189
	private MVCResponseSender mvcResponseSender;
190
 
191
	@Autowired
192
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
193
 
27586 tejbeer 194
	@Autowired
195
	private TransactionService transactionService;
196
 
27632 tejbeer 197
	@Autowired
198
	private TagListingRepository tagListingRepository;
199
 
27660 tejbeer 200
	@Autowired
201
	private TicketAssignedRepository ticketAssignedRepository;
202
 
27893 tejbeer 203
	@Autowired
204
	private OrderRepository orderRepository;
28468 tejbeer 205
 
206
	@Autowired
207
	private FofoUser fofoUser;
29875 tejbeer 208
 
28471 tejbeer 209
	@Autowired
28825 tejbeer 210
	private ActivatedImeiRepository activatedImeiRepository;
211
 
212
	@Autowired
213
	private Mongo mongoClient;
214
 
215
	@Autowired
29578 tejbeer 216
	private SchemeInOutRepository schemeInOutRepository;
29875 tejbeer 217
 
29578 tejbeer 218
	@Autowired
29720 manish 219
	private LineItemRepository lineItemRepository;
29875 tejbeer 220
 
29720 manish 221
	@Autowired
29578 tejbeer 222
	private FofoLineItemRepository fofoLineItemRepository;
223
 
224
	@Autowired
28471 tejbeer 225
	private PositionRepository positionRepository;
29707 tejbeer 226
 
227
	@Autowired
31211 tejbeer 228
	private MonthlyTargetRepository monthlyTargetRepository;
31285 tejbeer 229
 
31211 tejbeer 230
	@Autowired
29707 tejbeer 231
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
23568 govind 232
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
23923 amit.gupta 233
 
25136 amit.gupta 234
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
25726 amit.gupta 235
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
25740 amit.gupta 236
		boolean isAdmin = false;
237
		model.addAttribute("isAdmin", isAdmin);
238
 
239
		model.addAttribute("webApiHost", webApiHost);
240
		model.addAttribute("webApiPort", webApiPort);
241
		model.addAttribute("webApiScheme", webApiScheme);
242
		model.addAttribute("webApiRoot", webApiRoot);
243
		if (isAdmin) {
244
			return "dashboard1";
26236 amit.gupta 245
		}
246
 
247
		FofoStore fofoStore = null;
26234 amit.gupta 248
		try {
249
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
250
			fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
251
			if (!fofoStore.isActive()) {
252
				return "redirect:/login";
253
			}
25740 amit.gupta 254
 
26234 amit.gupta 255
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
256
			model.addAttribute("partnerType", partnerType);
257
			model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
258
			model.addAttribute("fofoStore", customRetailer);
259
			model.addAttribute("partnerType", partnerType);
28468 tejbeer 260
			model.addAttribute("hasGift", fofoUser.hasGift(fofoId));
26234 amit.gupta 261
			model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
25740 amit.gupta 262
 
28468 tejbeer 263
			model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(fofoId));
264
			model.addAttribute("salesMap", fofoUser.getSales(fofoId));
26234 amit.gupta 265
			model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
266
			// this.setInvestments
267
			//
28272 tejbeer 268
			Map<Integer, String> monthValueMap = new HashMap<>();
269
			for (int i = 0; i <= 5; i++) {
270
				LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
271
				monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
272
			}
273
			LOGGER.info("monthValueMap" + monthValueMap);
274
			model.addAttribute("monthValueMap", monthValueMap);
28468 tejbeer 275
			model.addAttribute("investments", fofoUser.getInvestments(fofoId));
26234 amit.gupta 276
			model.addAttribute("isInvestmentOk",
31521 amit.gupta 277
					partnerInvestmentService.isInvestmentOk(fofoId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
26234 amit.gupta 278
		} catch (ProfitMandiBusinessException e) {
279
			LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
25740 amit.gupta 280
 
281
		}
282
 
28430 tejbeer 283
		return "12dashboard34";
28272 tejbeer 284
	}
25740 amit.gupta 285
 
27474 tejbeer 286
	@RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
287
	public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
288
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
289
		int fofoId = loginDetails.getFofoId();
290
		Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
291
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
292
		int dayOfMonth = curDate.getDayOfMonth();
293
		for (int i = 1; i <= 6; i++) {
294
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
27555 tejbeer 295
			int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
29875 tejbeer 296
			LOGGER.info("Start of previous Month {}, start of next month Month {}", startOfMonth,
297
					startOfMonth.plusMonths(1));
27474 tejbeer 298
			double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
299
					startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
300
 
27574 tejbeer 301
			double mtdSales = fofoOrderItemRepository
302
					.selectSumMopGroupByRetailer(startOfMonth,
303
							startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false)
304
					.get(fofoId);
27474 tejbeer 305
 
306
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
307
 
308
			MonthSaleModel ms = new MonthSaleModel();
28468 tejbeer 309
			ms.setMtdSales(fofoUser.format((long) mtdSales));
310
			ms.setMonthlySales(fofoUser.format(((long) monthSales)));
27474 tejbeer 311
			ms.setPartnerType(partnerType);
27476 tejbeer 312
			ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
27474 tejbeer 313
			monthSaleMap.put(i, ms);
29875 tejbeer 314
		}
27474 tejbeer 315
 
316
		model.addAttribute("monthSales", monthSaleMap);
317
		return "monthSales";
318
	}
319
 
21615 kshitij.so 320
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
25653 amit.gupta 321
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
22927 ashik.ali 322
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26011 amit.gupta 323
		String email = loginDetails.getEmailId();
28430 tejbeer 324
		int fofoId = loginDetails.getFofoId();
25180 amit.gupta 325
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
326
		model.addAttribute("isAdmin", isAdmin);
23923 amit.gupta 327
 
25274 amit.gupta 328
		model.addAttribute("webApiHost", webApiHost);
329
		model.addAttribute("webApiPort", webApiPort);
330
		model.addAttribute("webApiScheme", webApiScheme);
25544 amit.gupta 331
		model.addAttribute("webApiRoot", webApiRoot);
25183 amit.gupta 332
		if (isAdmin) {
28468 tejbeer 333
			return adminUser.adminPanel(loginDetails.getFofoId(), email, model);
25180 amit.gupta 334
		} else {
25740 amit.gupta 335
			FofoStore fofoStore = null;
25180 amit.gupta 336
			try {
337
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
25544 amit.gupta 338
				if (!fofoStore.isActive()) {
339
					return "redirect:/login";
340
				}
30346 tejbeer 341
 
30455 amit.gupta 342
				LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
343
				LocalDateTime endtDate = LocalDateTime.now();
344
				OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository
345
						.selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);
346
				LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());
347
 
348
				long countOrder = pendingOrderRepository.pendingOrderCount(fofoId, OrderStatus.PROCESSING);
349
				LOGGER.info("countOrder" + countOrder);
350
 
351
				ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
352
 
353
				orderStatus.add(SUBMITTED_FOR_PROCESSING);
354
				orderStatus.add(BILLED);
355
				orderStatus.add(SHIPPED_FROM_WH);
356
				orderStatus.add(DELIVERY_SUCCESS);
357
 
358
				List<Order> openOrders = orderRepository.selectGrnTimestampNull(fofoId, orderStatus);
359
				List<LineItem> submittedLineItemIds = openOrders.stream()
30564 tejbeer 360
						.filter(x -> x.getStatus().equals(SUBMITTED_FOR_PROCESSING)).map(x -> x.getLineItem())
361
						.collect(Collectors.toList());
362
				List<LineItem> billedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(BILLED))
30455 amit.gupta 363
						.map(x -> x.getLineItem()).collect(Collectors.toList());
30564 tejbeer 364
				List<LineItem> shippedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(SHIPPED_FROM_WH))
30455 amit.gupta 365
						.map(x -> x.getLineItem()).collect(Collectors.toList());
366
				List<LineItem> grnPendingLineItemIds = openOrders.stream()
30564 tejbeer 367
						.filter(x -> x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getLineItem())
368
						.collect(Collectors.toList());
30455 amit.gupta 369
 
370
				long imeiActivationPendingCount = 0;
371
				long imeiActivationPendingValue = 0;
30564 tejbeer 372
				List<Integer> grnPendingOrderIds = openOrders.stream()
373
						.filter(x -> x.getStatus().equals(SHIPPED_FROM_WH) || x.getStatus().equals(DELIVERY_SUCCESS))
374
						.map(x -> x.getId()).collect(Collectors.toList());
30455 amit.gupta 375
				if (grnPendingOrderIds.size() > 0) {
30564 tejbeer 376
					List<ImeiActivationTimestampModel> imeiActivationTimestampModels = activatedImeiRepository
377
							.selectActivatedImeisByOrders(grnPendingOrderIds);
30455 amit.gupta 378
					imeiActivationPendingCount = imeiActivationTimestampModels.size();
30564 tejbeer 379
					imeiActivationPendingValue = imeiActivationTimestampModels.stream()
380
							.collect(Collectors.summingDouble(x -> x.getSellingPrice())).longValue();
30455 amit.gupta 381
				}
382
 
30564 tejbeer 383
				long grnPendingCount = grnPendingLineItemIds.stream()
384
						.collect(Collectors.summingLong(LineItem::getQuantity));
30455 amit.gupta 385
				long grnPendingValue = grnPendingLineItemIds.stream()
386
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
387
				model.addAttribute("grnPendingCount", grnPendingCount);
388
				model.addAttribute("grnPendingValue", grnPendingValue);
389
 
30564 tejbeer 390
				long submittedCount = submittedLineItemIds.stream()
391
						.collect(Collectors.summingLong(LineItem::getQuantity));
30455 amit.gupta 392
				long submittedValue = submittedLineItemIds.stream()
393
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
394
				model.addAttribute("submittedCount", submittedCount);
395
				model.addAttribute("submittedValue", submittedValue);
396
 
397
				long billedCount = billedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
30564 tejbeer 398
				long billedValue = billedOrderIds.stream()
399
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
30455 amit.gupta 400
				model.addAttribute("billedValue", billedValue);
401
				model.addAttribute("billedCount", billedCount);
402
				LOGGER.info("billedCount {}", billedCount);
403
 
404
				long shippedCount = shippedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
405
				model.addAttribute("shippedCount", shippedCount);
406
				LOGGER.info("shippedCount {}", shippedCount);
407
				long shippedValue = shippedOrderIds.stream()
408
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
409
				model.addAttribute("shippedValue", shippedValue);
410
 
411
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
412
 
413
				LocalDateTime currentMonthStart = curDate.withDayOfMonth(1);
414
				LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
415
				LocalDateTime currentMonthEnd = currentMonthStart.withDayOfMonth(1);
416
 
417
				LOGGER.info("lastMonthStart" + lastMonthStart);
418
				LOGGER.info("currentMonthEnd" + currentMonthEnd);
419
 
420
				model.addAttribute("countOrder", countOrder);
421
				model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());
422
 
25740 amit.gupta 423
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
25566 tejbeer 424
				model.addAttribute("partnerType", partnerType);
25653 amit.gupta 425
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
25180 amit.gupta 426
				model.addAttribute("fofoStore", fofoStore);
25566 tejbeer 427
				model.addAttribute("partnerType", partnerType);
28468 tejbeer 428
				model.addAttribute("hasGift", fofoUser.hasGift(loginDetails.getFofoId()));
25180 amit.gupta 429
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
26222 tejbeer 430
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
26162 amit.gupta 431
						.append("partnerId", fofoStore.getId()).toString());
26460 amit.gupta 432
				model.addAttribute("activatedImeis",
433
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
30564 tejbeer 434
				model.addAttribute("imeiActivationPendingCount", imeiActivationPendingCount);
435
				model.addAttribute("imeiActivationPendingValue", imeiActivationPendingValue);
30053 manish 436
 
26071 tejbeer 437
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
438
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
439
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
27701 tejbeer 440
 
26071 tejbeer 441
				Double accesoriesStock = currentInventorySnapshotRepository
442
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
443
								Optional.of(false))
444
						.get(loginDetails.getFofoId());
25180 amit.gupta 445
 
26071 tejbeer 446
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
28468 tejbeer 447
				model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(loginDetails.getFofoId()));
448
				model.addAttribute("salesMap", fofoUser.getSales(loginDetails.getFofoId()));
449
				ChartModel cm = fofoUser.getBrandChart(loginDetails.getFofoId());
26055 tejbeer 450
 
451
				LOGGER.info("chartMap" + gson.toJson(cm));
452
				model.addAttribute("chartMap", gson.toJson(cm));
27701 tejbeer 453
 
27876 amit.gupta 454
				List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(),
455
						YearMonth.from(LocalDateTime.now()));
456
				model.addAttribute("publishedOffers", publishedOffers);
28468 tejbeer 457
				model.addAttribute("investments", fofoUser.getInvestments(loginDetails.getFofoId()));
25544 amit.gupta 458
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
31521 amit.gupta 459
						ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
26460 amit.gupta 460
 
30564 tejbeer 461
				double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(),
462
						currentMonthStart, currentMonthEnd) / 2;
30455 amit.gupta 463
				double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
464
						currentMonthStart) / 2;
30564 tejbeer 465
				double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(),
466
						LocalDateTime.MIN, currentMonthEnd) / 2;
30455 amit.gupta 467
				model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
468
				model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
469
				model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
470
 
30564 tejbeer 471
				long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true,
472
						currentMonthStart, currentMonthEnd);
30455 amit.gupta 473
 
474
				long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
475
						currentMonthStart, currentMonthEnd);
476
				if (hygieneCount == 0 && invalidHygieneCount == 0) {
477
					invalidHygieneCount = 1;
478
				}
479
				Map<Integer, String> monthValueMap = new HashMap<>();
480
				for (int i = 0; i <= 5; i++) {
481
					LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
482
					monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
483
				}
484
 
31211 tejbeer 485
				MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
486
				model.addAttribute("monthlyTarget", monthlyTarget);
487
 
30455 amit.gupta 488
				model.addAttribute("monthValueMap", monthValueMap);
489
				model.addAttribute("month", 0);
490
				model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
491
				model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
492
				model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
493
 
25180 amit.gupta 494
			} catch (ProfitMandiBusinessException e) {
495
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
496
 
497
			}
30455 amit.gupta 498
			return "dashboard1";
22481 ashik.ali 499
		}
25649 tejbeer 500
 
21615 kshitij.so 501
	}
29875 tejbeer 502
 
29720 manish 503
	@RequestMapping(value = "/getGrnPendingOrderStatus", method = RequestMethod.GET)
504
	public String getGrnPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 505
 
29720 manish 506
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
507
		int fofoId = loginDetails.getFofoId();
30224 tejbeer 508
		List<Order> grnPendingOrders = orderRepository.selectGrnTimestampNull(fofoId,
509
				Arrays.asList(in.shop2020.model.v1.order.OrderStatus.DELIVERY_SUCCESS));
29746 manish 510
 
29934 amit.gupta 511
		model.addAttribute("grnPendingOrders", grnPendingOrders);
29720 manish 512
		return "purchase-grn-order-status";
513
	}
29875 tejbeer 514
 
29720 manish 515
	@RequestMapping(value = "/getPendingOrderStatus", method = RequestMethod.GET)
516
	public String getPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 517
 
29720 manish 518
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
519
		int fofoId = loginDetails.getFofoId();
29875 tejbeer 520
		ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
521
 
29720 manish 522
		orderStatus.add(in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING);
29875 tejbeer 523
 
524
		List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
525
		List<Integer> submittedOrderIds = order.stream()
526
				.filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING)
527
				.map(x -> x.getId()).collect(Collectors.toList());
528
		model.addAttribute("submittedOrderIds", submittedOrderIds);
529
		if (!submittedOrderIds.isEmpty()) {
530
 
531
			List<LineItem> submittedLineItem = lineItemRepository.selectLineItem(submittedOrderIds);
532
			Map<Integer, LineItem> submittedLineItemMap = submittedLineItem.stream()
533
					.collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
534
			LOGGER.info("submittedLineItemMap {}", submittedLineItemMap);
535
			model.addAttribute("submittedLineItemMap", submittedLineItemMap);
536
		}
537
 
29720 manish 538
		return "purchase-pending-order-status";
539
	}
29875 tejbeer 540
 
29720 manish 541
	@RequestMapping(value = "/getBilledOrderStatus", method = RequestMethod.GET)
542
	public String getBilledOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 543
 
29720 manish 544
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
545
		int fofoId = loginDetails.getFofoId();
29875 tejbeer 546
		ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
29720 manish 547
		orderStatus.add(in.shop2020.model.v1.order.OrderStatus.BILLED);
29875 tejbeer 548
 
549
		List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
550
		List<Integer> billedOrderIds = order.stream()
551
				.filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.BILLED).map(x -> x.getId())
552
				.collect(Collectors.toList());
553
		LOGGER.info("billedOrderIds {}", billedOrderIds);
554
		model.addAttribute("billedOrderIds", billedOrderIds);
555
 
556
		if (!billedOrderIds.isEmpty()) {
557
			List<LineItem> billedLineItem = lineItemRepository.selectLineItem(billedOrderIds);
558
			Map<Integer, LineItem> billedLineItemMap = billedLineItem.stream()
559
					.collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
560
			LOGGER.info("billedLineItemMap {}", billedLineItemMap);
561
			model.addAttribute("billedLineItemMap", billedLineItemMap);
562
		}
563
 
29720 manish 564
		return "purchase-billed-order-status";
565
	}
29875 tejbeer 566
 
29720 manish 567
	@RequestMapping(value = "/getShippedOrderStatus", method = RequestMethod.GET)
568
	public String getShippedOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 569
 
29720 manish 570
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
571
		int fofoId = loginDetails.getFofoId();
29875 tejbeer 572
		ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
573
 
30455 amit.gupta 574
		orderStatus.add(SHIPPED_FROM_WH);
29875 tejbeer 575
 
576
		List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
30347 tejbeer 577
		List<Integer> shippedOrderIds = order.stream().filter(x -> x.getPartnerGrnTimestamp() == null)
29875 tejbeer 578
				.map(x -> x.getId()).collect(Collectors.toList());
579
		model.addAttribute("shippedOrderIds", shippedOrderIds);
580
		LOGGER.info("shippedOrderIds {}", shippedOrderIds);
581
 
582
		if (!shippedOrderIds.isEmpty()) {
583
			List<LineItem> shippedLineItem = lineItemRepository.selectLineItem(shippedOrderIds);
584
			Map<Integer, LineItem> shippedLineItemMap = shippedLineItem.stream()
585
					.collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
586
			LOGGER.info("shippedLineItemMap {}", shippedLineItemMap);
587
 
588
			model.addAttribute("shippedLineItemMap", shippedLineItemMap);
589
		}
29720 manish 590
		return "purchase-shipped-order-status";
591
	}
23923 amit.gupta 592
 
31337 amit.gupta 593
	@Autowired
594
	OfferRepository offerRepository;
595
 
31353 amit.gupta 596
	@Autowired
597
	OfferPayoutRepository offerPayoutRepository;
598
 
30224 tejbeer 599
	@RequestMapping(value = "/partnerTotalIncomeByMonth/{yearMonth}", method = RequestMethod.GET)
600
	public String getPartnerTotalIncomeByMonth(HttpServletRequest request, @PathVariable int yearMonth, Model model)
601
			throws Exception {
602
 
603
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
604
		long pendingIncome = 0;
605
		long partnerPurchaseIn = 0;
606
		long partnerCreditedSale = 0;
607
		long partnerFrontIncome = 0;
608
 
31337 amit.gupta 609
		LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
610
		LocalDateTime endOfMonth = startOfMonth.plusMonths(1).toLocalDate().atStartOfDay();
30224 tejbeer 611
 
612
		AllPurchaseInventoryModel partnerlPendingSaleAmount = schemeInOutRepository
31337 amit.gupta 613
				.selectAllPendingSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
30224 tejbeer 614
		AllPurchaseInventoryModel partnerCreditedSaleAmount = schemeInOutRepository
31337 amit.gupta 615
				.selectAllCreditedSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
30224 tejbeer 616
		AllPurchaseInventoryModel partnerPurchaseInAmount = schemeInOutRepository
31337 amit.gupta 617
				.selectAllPurchaseInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
30224 tejbeer 618
 
619
		AllPurchaseInventoryModel partnerFrontIncomes = schemeInOutRepository
31337 amit.gupta 620
				.selectFrontIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
30224 tejbeer 621
 
31466 tejbeer 622
		List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository
623
				.getTotalPayoutsByPartnerPeriod(YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()),
624
						loginDetails.getFofoId(), null, null);
31353 amit.gupta 625
 
31466 tejbeer 626
		long additionalIncome = offerPayoutImeiIncomeModels.stream()
627
				.collect(Collectors.summingDouble(x -> x.getSalePayout() + x.getPurchasePayout())).longValue();
628
		// AllPurchaseInventoryModel partnerAdditionalIncome =
629
		// offerRepository.selectPurchaseIncome(loginDetails.getFofoId(), startOfMonth,
630
		// endOfMonth);
31337 amit.gupta 631
 
30224 tejbeer 632
		LOGGER.info("partnerfrontIncomes" + partnerFrontIncomes);
633
 
634
		LOGGER.info("partnerCreditedSaleAmount" + partnerCreditedSaleAmount);
635
		LOGGER.info("partnerPurchaseInAmount" + partnerPurchaseInAmount);
636
		LOGGER.info("partnerlPendingSaleAmount" + partnerlPendingSaleAmount);
637
 
638
		if (partnerlPendingSaleAmount != null) {
639
 
640
			pendingIncome = partnerlPendingSaleAmount.getAmount();
641
 
642
			LOGGER.info("pendingIncome" + pendingIncome);
643
 
644
		}
645
 
646
		if (partnerCreditedSaleAmount != null) {
647
 
648
			partnerCreditedSale = partnerCreditedSaleAmount.getAmount();
649
 
650
			LOGGER.info("partnerCreditedSale" + partnerCreditedSale);
651
 
652
		}
653
		if (partnerFrontIncomes != null) {
654
 
655
			partnerFrontIncome = partnerFrontIncomes.getAmount();
656
			LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
657
 
658
		}
659
		if (partnerPurchaseInAmount != null) {
660
 
661
			partnerPurchaseIn = partnerPurchaseInAmount.getAmount();
662
			LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
663
 
664
		}
665
 
666
		LOGGER.info("partnerPurchaseInTT" + partnerPurchaseIn);
667
		LOGGER.info("partnerCreditedSaleTT" + partnerCreditedSale);
668
		LOGGER.info("pendingIncomeTT" + pendingIncome);
669
 
31466 tejbeer 670
		long totalIncome = partnerCreditedSale + partnerPurchaseIn + pendingIncome + partnerFrontIncome
671
				+ additionalIncome;
30224 tejbeer 672
 
31353 amit.gupta 673
		long creditedIncome = partnerCreditedSale + partnerPurchaseIn + partnerFrontIncome + additionalIncome;
30224 tejbeer 674
 
675
		long pendingTotalIncome = pendingIncome;
676
		LOGGER.info("totalIncome" + totalIncome);
677
		LOGGER.info("creditedIncome" + creditedIncome);
678
		LOGGER.info("pendingTotalIncome" + pendingTotalIncome);
679
 
680
		model.addAttribute("totalIncome", totalIncome);
681
		model.addAttribute("creditedIncome", creditedIncome);
682
		model.addAttribute("pendingTotalIncome", pendingTotalIncome);
683
 
684
		Map<Integer, String> monthValueMap = new HashMap<>();
685
		for (int i = 0; i <= 5; i++) {
31338 amit.gupta 686
			LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
687
			monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
30224 tejbeer 688
		}
689
 
690
		model.addAttribute("month", yearMonth);
691
		model.addAttribute("monthValueMap", monthValueMap);
692
 
693
		return "partner-total-income";
694
	}
695
 
28272 tejbeer 696
	@RequestMapping(value = "/getMonthsInvestment", method = RequestMethod.GET)
697
	public String getMonthsInvestment(HttpServletRequest request,
30564 tejbeer 698
			@RequestParam(name = "month", required = true, defaultValue = "0") int month, Model model)
28272 tejbeer 699
			throws Exception {
700
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
701
		int fofoId = loginDetails.getFofoId();
28468 tejbeer 702
		Map<String, Object> investment = fofoUser.getInvestmentsMonths(fofoId, month);
28430 tejbeer 703
 
28272 tejbeer 704
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
705
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
706
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
707
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
708
				currentMonthEnd) / 2;
709
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
710
				currentMonthStart) / 2;
711
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
712
				currentMonthEnd) / 2;
713
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
714
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
715
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
716
 
28430 tejbeer 717
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true,
718
				currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
28272 tejbeer 719
 
720
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
28430 tejbeer 721
				currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
28272 tejbeer 722
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
723
			invalidHygieneCount = 1;
724
		}
725
		Map<Integer, String> monthValueMap = new HashMap<>();
726
		for (int i = 0; i <= 5; i++) {
727
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
728
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
729
		}
730
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
28430 tejbeer 731
		model.addAttribute("monthValueMap", monthValueMap);
28272 tejbeer 732
		model.addAttribute("investments", investment);
733
		model.addAttribute("monthDays", LocalDate.now().minusMonths(month).lengthOfMonth());
734
		model.addAttribute("dayOfMonth", LocalDate.now().minusMonths(month).lengthOfMonth());
28430 tejbeer 735
		model.addAttribute("month", month);
28272 tejbeer 736
		return "performance";
737
	}
738
 
27884 tejbeer 739
	@RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
740
	public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
741
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
742
		int fofoId = loginDetails.getFofoId();
28468 tejbeer 743
		ChartInvestmentModel cm = fofoUser.getInvestmentChart(fofoId);
27884 tejbeer 744
		model.addAttribute("chartPieMap", gson.toJson(cm));
745
 
746
		LOGGER.info("InvestmentChart" + gson.toJson(cm));
747
		LOGGER.info("InvestmentChart" + cm);
748
		return "investmentdetails";
749
	}
750
 
28430 tejbeer 751
	@RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
752
	public String getlmsLineChart(HttpServletRequest request, Model model) throws Exception {
753
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
754
		int fofoId = loginDetails.getFofoId();
28468 tejbeer 755
		ChartModel cm = fofoUser.getLmsLineChart(loginDetails.getFofoId());
28430 tejbeer 756
 
757
		LOGGER.info("linechartMap" + gson.toJson(cm));
758
		model.addAttribute("linechartMap", gson.toJson(cm));
759
		return "lmsLineChart";
760
	}
761
 
28439 tejbeer 762
	@RequestMapping(value = "/getMonthlyPurchaseLineChart", method = RequestMethod.GET)
763
	public String getMonthlyPurchaseLineChart(HttpServletRequest request, Model model) throws Exception {
764
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
765
		int fofoId = loginDetails.getFofoId();
28468 tejbeer 766
		ChartModel cm = fofoUser.getPurchaseOrderChart(fofoId);
28439 tejbeer 767
 
768
		LOGGER.info("chartMap" + gson.toJson(cm));
769
		model.addAttribute("chartMap", gson.toJson(cm));
770
 
771
		return "purchase_chart";
772
	}
773
 
28430 tejbeer 774
	@RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
775
	public String getBarChart(HttpServletRequest request, Model model) throws Exception {
776
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
777
		int fofoId = loginDetails.getFofoId();
28468 tejbeer 778
		ChartModel cm = fofoUser.getBrandChart(fofoId);
28430 tejbeer 779
 
780
		LOGGER.info("chartMap" + gson.toJson(cm));
781
		model.addAttribute("chartMap", gson.toJson(cm));
782
 
783
		return "bar_chart";
784
	}
785
 
28455 tejbeer 786
	@RequestMapping(value = "/getPriceDropDetails", method = RequestMethod.GET)
787
	public String getPriceDropDetails(HttpServletRequest request,
30564 tejbeer 788
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
789
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
790
			@RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
28455 tejbeer 791
			throws Exception {
792
 
793
		LOGGER.info("params" + fofoId + brand + yearMonth);
794
 
795
		List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository
796
				.selectBrandPendingPriceDropWithDetailsByYearMonth(fofoId, brand, yearMonth);
797
 
798
		LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
799
 
800
		model.addAttribute("priceDropdetailsList", priceDropdetailsList);
801
 
802
		return "price-drop-details";
803
	}
28825 tejbeer 804
 
28641 amit.gupta 805
	@RequestMapping(value = "/getPriceDropDetailSixMonths", method = RequestMethod.GET)
806
	public String getPriceDropDetailSixMonths(HttpServletRequest request,
30564 tejbeer 807
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
808
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
28641 amit.gupta 809
			throws Exception {
28455 tejbeer 810
 
28641 amit.gupta 811
		LOGGER.info("params" + fofoId + brand);
812
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
813
		LocalDateTime startfMonthSixMonth = curDate.withDayOfMonth(1).minusMonths(12);
814
		LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(6);
815
 
816
		List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository
28825 tejbeer 817
				.selectBrandPendingPriceDropWithDetailsAndSixMonth(fofoId, brand, startfMonthSixMonth, endMonthTotal);
28641 amit.gupta 818
 
819
		LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
820
 
821
		model.addAttribute("priceDropdetailsList", priceDropdetailsList);
822
 
823
		return "price-drop-details";
824
	}
825
 
28455 tejbeer 826
	@RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
827
	public String getMonthlyPriceDropTabular(HttpServletRequest request, Model model) throws Exception {
828
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
829
		int fofoId = loginDetails.getFofoId();
830
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
831
 
832
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
28641 amit.gupta 833
		LocalDateTime startfMonthTotal = curDate.withDayOfMonth(1).minusMonths(12);
29875 tejbeer 834
		LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(5);
28455 tejbeer 835
 
29875 tejbeer 836
		LOGGER.info("startfMonthTotal" + startfMonthTotal);
837
 
838
		LOGGER.info("endMonthTotal" + endMonthTotal);
28641 amit.gupta 839
		List<YearMonth> yms = new ArrayList<YearMonth>();
28455 tejbeer 840
 
29875 tejbeer 841
		for (int i = 0; i <= 5; i++) {
28641 amit.gupta 842
			yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
28455 tejbeer 843
		}
28641 amit.gupta 844
		Collections.reverse(yms);
845
		model.addAttribute("yms", yms);
846
		LOGGER.info("ym" + yms);
28455 tejbeer 847
 
848
		List<PriceDropYearMonthModel> priceDropYearMonthModels = priceDropRepository
849
				.selectBrandPendingPriceDropByYearMonth(fofoId, startOfMonth);
850
 
28641 amit.gupta 851
		List<PriceDropBrandModel> priceDropBrandSixMonthTotals = priceDropRepository
852
				.selectSixMonthBrandPriceDropByYearMonth(fofoId, startfMonthTotal, endMonthTotal);
853
 
28455 tejbeer 854
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
855
 
856
		Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
28641 amit.gupta 857
 
858
		LOGGER.info("priceDropBrandSixMonthTotals" + priceDropBrandSixMonthTotals);
28825 tejbeer 859
 
860
		Map<String, Double> priceDropBrandSixMonthMap = priceDropBrandSixMonthTotals.stream()
861
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
862
 
28641 amit.gupta 863
		model.addAttribute("priceDropBrandSixMonthMap", priceDropBrandSixMonthMap);
28455 tejbeer 864
		LOGGER.info("priceDropYearMonthModels" + priceDropYearMonthModels);
28641 amit.gupta 865
 
28455 tejbeer 866
		for (PriceDropYearMonthModel pdm : priceDropYearMonthModels) {
28641 amit.gupta 867
			Map<YearMonth, Double> brandValue = new HashMap<>();
28455 tejbeer 868
 
869
			if (brandMonthValue.containsKey(pdm.getBrand())) {
870
				brandValue = brandMonthValue.get(pdm.getBrand());
871
				brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
872
			} else {
873
 
874
				brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
875
 
876
			}
877
			brandMonthValue.put(pdm.getBrand(), brandValue);
878
		}
879
		List<String> brands = new ArrayList<>();
880
		brands.add("Accessories");
881
		brands.add("Oppo");
882
		brands.add("Vivo");
883
		brands.add("Samsung");
884
		brands.add("Realme");
28462 tejbeer 885
		brands.add("MI");
28455 tejbeer 886
		brands.add("Tecno");
887
		brands.add("Itel");
888
		brands.add("Nokia");
29578 tejbeer 889
 
28455 tejbeer 890
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
891
 
28825 tejbeer 892
		model.addAttribute("brands", brands);
893
 
28455 tejbeer 894
		for (String brand : brands) {
895
			Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
29875 tejbeer 896
			for (int i = 5; i >= 0; i--) {
28455 tejbeer 897
 
898
				LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
899
 
900
				if (yearMonthValue != null) {
901
					if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
902
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
903
					}
904
 
905
				} else {
906
					yearMonthValue = new HashMap<>();
907
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
908
				}
909
			}
910
 
911
			Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
912
 
913
			brandMonthValue.put(brand, sortedMonthBrandValue);
914
 
915
			sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
916
 
917
		}
918
 
29578 tejbeer 919
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
920
		model.addAttribute("fofoId", fofoId);
28455 tejbeer 921
 
29578 tejbeer 922
		model.addAttribute("sortedBrandValue", sortedBrandValue);
28455 tejbeer 923
 
29578 tejbeer 924
		return "price-drop-tabular";
925
	}
28455 tejbeer 926
 
29578 tejbeer 927
	@RequestMapping(value = "/getMonthlyActivation", method = RequestMethod.GET)
928
	public String getMonthlyActivation(HttpServletRequest request, Model model) throws Exception {
929
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
930
		int fofoId = loginDetails.getFofoId();
28455 tejbeer 931
 
29578 tejbeer 932
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
933
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
934
 
935
		List<YearMonth> yms = new ArrayList<YearMonth>();
936
 
29580 tejbeer 937
		for (int i = 0; i <= 5; i++) {
29578 tejbeer 938
			yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
939
		}
940
		Collections.reverse(yms);
941
		model.addAttribute("yms", yms);
942
		LOGGER.info("ym" + yms);
943
 
944
		List<ActivationYearMonthModel> pendingActivationModels = schemeInOutRepository
945
				.selectPendingActivationGroupByBrandYearMonth(fofoId, startOfMonth);
946
 
947
		List<ActivationBrandModel> pendingActivationBeforeSixMonth = schemeInOutRepository
948
				.selectByYearMonthActivationGroupByBrand(fofoId, startOfMonth);
949
 
950
		Map<String, Double> pendingActivationBeforeSixMonthMap = pendingActivationBeforeSixMonth.stream()
951
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
952
 
953
		model.addAttribute("pendingActivationBeforeSixMonthMap", pendingActivationBeforeSixMonthMap);
954
 
955
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
956
 
957
		Map<String, Map<YearMonth, Double>> activationBrandMonthMap = new HashMap<>();
958
 
959
		for (ActivationYearMonthModel pam : pendingActivationModels) {
960
			Map<YearMonth, Double> brandValue = new HashMap<>();
961
 
962
			if (activationBrandMonthMap.containsKey(pam.getBrand())) {
963
				brandValue = activationBrandMonthMap.get(pam.getBrand());
964
				brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
965
			} else {
966
 
967
				brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
968
 
28455 tejbeer 969
			}
29578 tejbeer 970
			activationBrandMonthMap.put(pam.getBrand(), brandValue);
971
		}
28455 tejbeer 972
 
29578 tejbeer 973
		List<String> brands = new ArrayList<>();
974
		brands.add("Oppo");
975
		brands.add("Vivo");
976
		brands.add("Samsung");
977
		brands.add("Realme");
978
		brands.add("MI");
979
		brands.add("Tecno");
980
		brands.add("Itel");
981
		brands.add("Nokia");
982
		brands.add("Lava");
983
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
984
 
985
		model.addAttribute("brands", brands);
986
 
987
		for (String brand : brands) {
988
			Map<YearMonth, Double> yearMonthValue = activationBrandMonthMap.get(brand);
29580 tejbeer 989
			for (int i = 5; i >= 0; i--) {
29578 tejbeer 990
				LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
991
				if (yearMonthValue != null) {
992
					if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
993
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
994
					}
995
 
996
				} else {
997
					yearMonthValue = new HashMap<>();
998
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
999
				}
1000
			}
1001
			Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1002
			activationBrandMonthMap.put(brand, sortedMonthBrandValue);
1003
			sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
28455 tejbeer 1004
		}
1005
 
29580 tejbeer 1006
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
29578 tejbeer 1007
		model.addAttribute("sortedBrandValue", sortedBrandValue);
28455 tejbeer 1008
		model.addAttribute("fofoId", fofoId);
29578 tejbeer 1009
		return "activation-tabular";
1010
	}
28455 tejbeer 1011
 
29578 tejbeer 1012
	@RequestMapping(value = "/getMonthlyActivationItemDetail", method = RequestMethod.GET)
1013
	public String getMonthlyActivationItemDetail(HttpServletRequest request,
30564 tejbeer 1014
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1015
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
1016
			@RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
29578 tejbeer 1017
			throws Exception {
28455 tejbeer 1018
 
29578 tejbeer 1019
		LOGGER.info("params" + fofoId + brand + yearMonth);
1020
 
1021
		List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository
1022
				.selectBrandPendingActivationItemDetails(fofoId, brand, yearMonth);
1023
 
1024
		for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
1025
 
1026
			List<FofoLineItem> flis = fofoLineItemRepository
1027
					.selectByInventoryItemId(activationItemDetail.getInventoryItemId());
1028
 
1029
			LOGGER.info("flis" + flis);
1030
 
1031
			int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max()
1032
					.orElseThrow(NoSuchElementException::new);
1033
			LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);
1034
 
1035
			FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);
1036
 
1037
			FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());
1038
 
1039
			activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
1040
 
1041
		}
1042
		LOGGER.info("activationItemDetails" + activationItemDetails);
1043
 
1044
		model.addAttribute("activationItemDetails", activationItemDetails);
1045
 
1046
		return "activation-pending-item-details";
28455 tejbeer 1047
	}
1048
 
29578 tejbeer 1049
	@RequestMapping(value = "/getMonthlyActivationBeforeSixMonthsItemDetail", method = RequestMethod.GET)
1050
	public String getMonthlyActivationItemDetail(HttpServletRequest request,
30564 tejbeer 1051
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1052
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
29578 tejbeer 1053
			throws Exception {
1054
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1055
 
1056
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1057
 
1058
		List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository
1059
				.selectBrandPendingActivationItemDetailByYearMonth(fofoId, brand, startOfMonth);
1060
 
1061
		for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
1062
 
1063
			List<FofoLineItem> flis = fofoLineItemRepository
1064
					.selectByInventoryItemId(activationItemDetail.getInventoryItemId());
1065
			LOGGER.info("flis" + flis);
1066
 
1067
			int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max()
1068
					.orElseThrow(NoSuchElementException::new);
1069
			LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);
1070
 
1071
			FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);
1072
 
1073
			FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());
1074
 
1075
			activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
1076
 
1077
		}
1078
		LOGGER.info("activationItemDetails" + activationItemDetails);
1079
 
1080
		model.addAttribute("activationItemDetails", activationItemDetails);
1081
 
1082
		return "activation-pending-item-details";
1083
	}
1084
 
29707 tejbeer 1085
	@RequestMapping(value = "/getMonthlySamsungUpgradeOffer", method = RequestMethod.GET)
1086
	public String getMonthlySamsungUpgradeOffer(HttpServletRequest request, Model model) throws Exception {
1087
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1088
		int fofoId = loginDetails.getFofoId();
1089
 
1090
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1091
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1092
 
1093
		List<YearMonth> yms = new ArrayList<YearMonth>();
1094
 
1095
		for (int i = 0; i <= 5; i++) {
1096
			yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
1097
		}
1098
		Collections.reverse(yms);
1099
		model.addAttribute("yms", yms);
1100
		LOGGER.info("ym" + yms);
1101
 
1102
		List<SamsungUpgradeOfferModel> suos = samsungUpgradeOfferRepository.selectUpgradeOfferGroupByYearMonth(fofoId,
1103
				UpgradeOfferStatus.approved, startOfMonth);
1104
 
1105
		LOGGER.info("suos" + suos);
1106
 
1107
		List<BrandAmountModel> beforeSixMonthOffers = samsungUpgradeOfferRepository
1108
				.selectUpgradeOfferByYearMonthGroupByBrand(fofoId, UpgradeOfferStatus.approved, startOfMonth);
1109
 
1110
		Map<String, Double> pendingUpgradeOfferBeforeSixMonthMap = beforeSixMonthOffers.stream()
1111
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
1112
 
1113
		model.addAttribute("pendingUpgradeOfferBeforeSixMonthMap", pendingUpgradeOfferBeforeSixMonthMap);
1114
 
1115
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
1116
 
1117
		Map<String, Map<YearMonth, Double>> upgradeOfferBrandMonthMap = new HashMap<>();
1118
 
1119
		for (SamsungUpgradeOfferModel suo : suos) {
1120
			Map<YearMonth, Double> brandValue = new HashMap<>();
1121
 
1122
			if (upgradeOfferBrandMonthMap.containsKey(suo.getBrand())) {
1123
				brandValue = upgradeOfferBrandMonthMap.get(suo.getBrand());
1124
				brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1125
			} else {
1126
 
1127
				brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1128
 
1129
			}
1130
			upgradeOfferBrandMonthMap.put(suo.getBrand(), brandValue);
1131
		}
1132
 
1133
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
1134
		String brand = "Samsung";
1135
 
1136
		Map<YearMonth, Double> yearMonthValue = upgradeOfferBrandMonthMap.get(brand);
1137
		for (int i = 5; i >= 0; i--) {
1138
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
1139
			if (yearMonthValue != null) {
1140
				if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
1141
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1142
				}
1143
 
1144
			} else {
1145
				yearMonthValue = new HashMap<>();
1146
				yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1147
			}
1148
		}
1149
		Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1150
		upgradeOfferBrandMonthMap.put(brand, sortedMonthBrandValue);
1151
		sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
1152
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
1153
 
1154
		model.addAttribute("brand", brand);
1155
		model.addAttribute("sortedBrandValue", sortedBrandValue);
1156
		model.addAttribute("fofoId", fofoId);
1157
		return "upgrade-offer-tabular";
1158
 
1159
	}
1160
 
1161
	@RequestMapping(value = "/getMonthlyUpgradeOfferItemDetail", method = RequestMethod.GET)
1162
	public String getMonthlyUpgradeOfferItemDetail(HttpServletRequest request,
30564 tejbeer 1163
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1164
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
1165
			@RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
29707 tejbeer 1166
			throws Exception {
1167
 
1168
		LOGGER.info("params" + fofoId + brand + yearMonth);
1169
		List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository
1170
				.selectUpgradeOfferItemDetails(fofoId, UpgradeOfferStatus.approved, brand, yearMonth);
1171
 
1172
		model.addAttribute("offerItems", offerItems);
1173
 
1174
		return "upgrade-offer-item-detail";
1175
	}
1176
 
1177
	@RequestMapping(value = "/getUpgradeOfferBeforeSixMonthItemDetail", method = RequestMethod.GET)
1178
	public String getUpgradeOfferBeforeSixMonthItemDetail(HttpServletRequest request,
30564 tejbeer 1179
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1180
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
29707 tejbeer 1181
			throws Exception {
1182
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1183
 
1184
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1185
 
1186
		List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository
1187
				.selectUpgradeOfferItemDetailByYearMonth(fofoId, UpgradeOfferStatus.approved, brand, startOfMonth);
1188
 
1189
		model.addAttribute("offerItems", offerItems);
1190
 
1191
		return "upgrade-offer-item-detail";
1192
	}
1193
 
26468 amit.gupta 1194
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
26418 tejbeer 1195
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1196
			throws Exception {
1197
 
1198
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
26963 amit.gupta 1199
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1200
 
26468 amit.gupta 1201
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1202
		if (authId != 0) {
1203
			List<Integer> fofoIds = pp.get(authId);
1204
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1205
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
26474 amit.gupta 1206
		} else {
26418 tejbeer 1207
		}
1208
 
1209
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1210
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1211
 
1212
		return "auth_user_partner_detail";
26468 amit.gupta 1213
	}
26418 tejbeer 1214
 
27545 tejbeer 1215
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1216
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1217
			throws Exception {
27701 tejbeer 1218
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1219
		String email = loginDetails.getEmailId();
28472 tejbeer 1220
 
1221
		Set<Integer> authfofoIds = new HashSet<>();
31662 amit.gupta 1222
		authfofoIds = csService1.getAuthFofoIds(email, true);
27701 tejbeer 1223
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1224
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1225
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1226
 
27545 tejbeer 1227
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
28468 tejbeer 1228
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = adminUser.getPartnersStatDataFromFile();
27545 tejbeer 1229
		if (warehouseId != 0) {
27701 tejbeer 1230
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1231
			/*
1232
			 * List<Integer> fofoIds =
1233
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1234
			 * .map(x -> x.getId()).collect(Collectors.toList());
1235
			 */
27545 tejbeer 1236
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1237
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1238
		} else {
28472 tejbeer 1239
 
1240
			List<Integer> fofoIds = new ArrayList<>(authfofoIds);
1241
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
27701 tejbeer 1242
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
27545 tejbeer 1243
		}
29164 manish 1244
		ChartInvestmentModel cm = adminUser.getAllStatePartnerType(fofoIdAndallValues);
1245
		model.addAttribute("chartPieMap", gson.toJson(cm));
27545 tejbeer 1246
 
29164 manish 1247
		LOGGER.info("adminUserChart" + gson.toJson(cm));
1248
 
31211 tejbeer 1249
		Map<Integer, MonthlyTarget> monthlyTargetMap = monthlyTargetRepository.selectByDate(YearMonth.now()).stream()
1250
				.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1251
 
27545 tejbeer 1252
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1253
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
31211 tejbeer 1254
		model.addAttribute("monthlyTargetMap", monthlyTargetMap);
27545 tejbeer 1255
 
31154 tejbeer 1256
		List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values()).stream()
1257
				.filter(x -> !x.equals(PartnerType.ALL)).collect(Collectors.toList());
31211 tejbeer 1258
 
31154 tejbeer 1259
		model.addAttribute("partnerTypes", partnerTypes);
1260
 
27545 tejbeer 1261
		return "auth_user_partner_detail";
1262
	}
1263
 
31662 amit.gupta 1264
 
27509 tejbeer 1265
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
27701 tejbeer 1266
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
30564 tejbeer 1267
			@RequestParam List<Integer> warehouseId) throws Exception {
27701 tejbeer 1268
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1269
		String email = loginDetails.getEmailId();
31662 amit.gupta 1270
		Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
27701 tejbeer 1271
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1272
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1273
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1274
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1275
		if (!warehouseId.contains(0)) {
1276
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1277
		} else {
1278
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1279
			warehouseWiseBrandStock = saholicInventoryCISRepository
1280
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1281
 
1282
		}
27542 tejbeer 1283
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27509 tejbeer 1284
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
27542 tejbeer 1285
		model.addAttribute("warehouseId", warehouseId);
27509 tejbeer 1286
		model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1287
 
27509 tejbeer 1288
		return "warehouse_brand_stock";
1289
	}
1290
 
27529 tejbeer 1291
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1292
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1293
		inventoryService.getItemAvailabilityAndIndent();
31238 amit.gupta 1294
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
27529 tejbeer 1295
		return "response";
1296
	}
1297
 
27539 tejbeer 1298
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1299
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
30564 tejbeer 1300
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
27538 tejbeer 1301
			throws Exception {
27509 tejbeer 1302
 
1303
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27529 tejbeer 1304
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
27538 tejbeer 1305
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1306
 
27509 tejbeer 1307
		model.addAttribute("warehouseMap", warehouseMap);
27529 tejbeer 1308
		model.addAttribute("brands", listbrands);
27538 tejbeer 1309
		model.addAttribute("listCategory", listCategory);
1310
 
27529 tejbeer 1311
		model.addAttribute("selectedBrand", brands);
27538 tejbeer 1312
		model.addAttribute("selectedWarehouse", warehouseId);
27539 tejbeer 1313
		model.addAttribute("selectedCategory", category);
1314
 
27509 tejbeer 1315
		return "warehouse_brand_item_stock";
1316
	}
1317
 
27538 tejbeer 1318
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1319
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
30564 tejbeer 1320
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
27538 tejbeer 1321
			throws Exception {
27539 tejbeer 1322
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1323
		if (warehouseId.contains(0)) {
1324
			warehouseId.addAll(warehouseMap.keySet());
1325
		}
27538 tejbeer 1326
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1327
				.selectWarehouseItemStock(warehouseId, brands, category);
27539 tejbeer 1328
 
27538 tejbeer 1329
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1330
		model.addAttribute("warehouseMap", warehouseMap);
1331
		return "warehouse_item_details";
1332
	}
1333
 
27556 tejbeer 1334
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
27591 tejbeer 1335
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1336
			throws Exception {
27701 tejbeer 1337
 
1338
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1339
		String email = loginDetails.getEmailId();
1340
 
31662 amit.gupta 1341
		Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
28472 tejbeer 1342
 
27670 tejbeer 1343
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1344
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1345
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1346
 
1347
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
27701 tejbeer 1348
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1349
 
1350
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1351
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1352
			if (bpt != null) {
1353
				bpt.setAmtd(un.getUnbilledMtd());
27676 tejbeer 1354
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1355
			} else {
1356
				bpt = new WarehouseWiseBrandSaleModel();
1357
				bpt.setWarehouseId(un.getWarehouseId());
1358
				bpt.setAmtd(un.getUnbilledMtd());
27677 tejbeer 1359
				bpt.setUamtdQty(un.getUnbilledQty());
27670 tejbeer 1360
				bpt.setLms(0);
1361
				bpt.setLmtd(0);
1362
				bpt.setMtd(0);
1363
				bpt.setMtdQty(0);
1364
				bpt.setLmtd(0);
1365
				bpt.setLmtdQty(0);
1366
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1367
			}
1368
		}
27556 tejbeer 1369
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1370
 
1371
		Set<String> brands = inventoryService.getAllTagListingBrands();
1372
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
27556 tejbeer 1373
		model.addAttribute("warehouseMap", warehouseMap);
27591 tejbeer 1374
		model.addAttribute("brands", brands);
1375
		model.addAttribute("selectedbrand", brand);
1376
		return "warehousewise_brand_partners_sale";
27556 tejbeer 1377
	}
1378
 
27594 tejbeer 1379
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1380
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
30564 tejbeer 1381
			@RequestParam String brand) throws Exception {
27701 tejbeer 1382
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1383
		String email = loginDetails.getEmailId();
1384
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1385
		Set<Integer> authfofoIds = storeGuyMap.get(email);
28472 tejbeer 1386
 
1387
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1388
		if (authfofoIds == null) {
1389
			List<Position> positions1 = positionRepository.selectAll(authUser.getId());
1390
			if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
1391
					.count() > 0) {
1392
				authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
1393
						.flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
1394
			}
1395
		}
27594 tejbeer 1396
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
27701 tejbeer 1397
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1398
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1399
 
1400
		Set<String> brands = inventoryService.getAllTagListingBrands();
1401
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1402
		model.addAttribute("warehouseMap", warehouseMap);
1403
		model.addAttribute("brands", brands);
1404
		model.addAttribute("selectedbrand", brand);
1405
		return "warehousewise_accessoriesbrand_sale";
1406
	}
1407
 
27556 tejbeer 1408
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1409
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
30564 tejbeer 1410
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
27556 tejbeer 1411
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1412
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1413
		String email = loginDetails.getEmailId();
31662 amit.gupta 1414
		Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
27670 tejbeer 1415
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
27701 tejbeer 1416
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
27670 tejbeer 1417
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1418
 
1419
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
27701 tejbeer 1420
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1421
 
1422
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1423
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1424
			if (bpt != null) {
1425
				bpt.setAmtd(un.getAmtd());
27676 tejbeer 1426
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1427
			} else {
1428
				bpt = new WarehouseBrandWiseItemSaleModel();
1429
				bpt.setWarehouseId(un.getWarehouseId());
1430
				bpt.setItemId(un.getItemId());
1431
				bpt.setAmtd(un.getAmtd());
27677 tejbeer 1432
				bpt.setUamtdQty(un.getUnmtdQty());
27670 tejbeer 1433
				bpt.setBrand(un.getBrand());
1434
				bpt.setModelName(un.getModelName());
1435
				bpt.setModelNumber(un.getModelNumber());
1436
				bpt.setColor(un.getColor());
1437
				bpt.setLms(0);
1438
				bpt.setLmtd(0);
1439
				bpt.setMtd(0);
1440
				bpt.setMtdQty(0);
1441
				bpt.setLmtd(0);
1442
				bpt.setLmtdQty(0);
1443
				branditemSalesMap.put(un.getItemId(), bpt);
1444
			}
1445
		}
1446
		model.addAttribute("branditemSales", branditemSalesMap);
27556 tejbeer 1447
		model.addAttribute("warehouseMap", warehouseMap);
1448
		return "warehouse_partner_itemwise_sale";
1449
	}
1450
 
27594 tejbeer 1451
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1452
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
30564 tejbeer 1453
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
27594 tejbeer 1454
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27701 tejbeer 1455
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1456
		String email = loginDetails.getEmailId();
1457
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1458
		Set<Integer> authfofoIds = storeGuyMap.get(email);
27594 tejbeer 1459
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
27701 tejbeer 1460
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
27594 tejbeer 1461
		model.addAttribute("branditemSales", branditemSales);
1462
		model.addAttribute("warehouseMap", warehouseMap);
1463
		return "warehouse_accessories_itemwsie_sale";
1464
	}
1465
 
22354 ashik.ali 1466
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
23923 amit.gupta 1467
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
22354 ashik.ali 1468
		model.addAttribute("appContextPath", request.getContextPath());
1469
		return "contact-us";
1470
	}
23923 amit.gupta 1471
 
25649 tejbeer 1472
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
25683 tejbeer 1473
	public String getNotificationsWithType(HttpServletRequest request,
30564 tejbeer 1474
			@RequestParam(required = false) MessageType messageType,
1475
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1476
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
25649 tejbeer 1477
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26060 tejbeer 1478
		int userId = 0;
1479
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1480
		if (isAdmin) {
1481
			userId = loginDetails.getFofoId();
1482
		} else {
1483
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1484
		}
25683 tejbeer 1485
		List<Notification> notifications = null;
1486
 
26086 tejbeer 1487
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1488
				userId, offset, limit);
1489
		LOGGER.info("messageType" + messageType);
28468 tejbeer 1490
		notifications = fofoUser.getNotifications(notificationCampaigns, messageType);
26086 tejbeer 1491
 
25683 tejbeer 1492
		model.addAttribute("notifications", notifications);
1493
 
1494
		LOGGER.info("notifications" + notifications);
1495
		return "notification-template";
1496
	}
1497
 
25651 tejbeer 1498
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1499
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
30564 tejbeer 1500
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
25651 tejbeer 1501
			throws ProfitMandiBusinessException {
1502
		Document document = documentRepository.selectById(documentId);
1503
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1504
		if (nc.getDocumentId() == null) {
1505
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1506
		}
1507
		if (nc.getDocumentId() != documentId) {
1508
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1509
		}
1510
		return responseSender.ok(document);
25649 tejbeer 1511
	}
1512
 
25651 tejbeer 1513
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1514
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1515
			throws ProfitMandiBusinessException {
1516
 
1517
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1518
 
1519
		if (nc.getDocumentId() == null) {
1520
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1521
		}
1522
 
1523
		Document document = documentRepository.selectById(nc.getDocumentId());
1524
 
1525
		FileInputStream file = null;
1526
		try {
1527
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1528
		} catch (FileNotFoundException e) {
1529
			LOGGER.error("Retailer Document file not found : ", e);
1530
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1531
		}
1532
		// ByteArrayOutputStream byteArrayOutputStream = new
1533
		// ByteArrayOutputStream();
1534
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1535
 
1536
		final HttpHeaders headers = new HttpHeaders();
1537
		String contentType = "";
1538
		if (document.getContentType() == ContentType.JPEG) {
1539
			contentType = "image/jpeg";
1540
		} else if (document.getContentType() == ContentType.PNG) {
1541
			contentType = "image/png";
1542
		} else if (document.getContentType() == ContentType.PDF) {
1543
			contentType = "application/pdf";
1544
		}
1545
		headers.set("Content-Type", contentType);
1546
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1547
		headers.setContentLength(document.getSize());
1548
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1549
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1550
	}
26460 amit.gupta 1551
 
27579 tejbeer 1552
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1553
	public String getItemWiseTertiary(HttpServletRequest request,
30564 tejbeer 1554
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
27579 tejbeer 1555
			throws ProfitMandiBusinessException {
1556
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1557
 
1558
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
27586 tejbeer 1559
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1560
		model.addAttribute("customRetailer", customRetailer);
27579 tejbeer 1561
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1562
		return "item-wise-tertiary";
1563
	}
1564
 
27586 tejbeer 1565
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1566
	public String getItemWiseIndent(HttpServletRequest request,
30564 tejbeer 1567
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
27586 tejbeer 1568
			throws ProfitMandiBusinessException {
1569
 
1570
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1571
		model.addAttribute("unbilledOrders", unbilledOrders);
1572
 
1573
		return "item-wise-indent";
1574
	}
1575
 
27636 tejbeer 1576
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1577
	public String getPartnerInvestment(HttpServletRequest request,
30564 tejbeer 1578
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
28468 tejbeer 1579
		Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
27636 tejbeer 1580
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1581
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1582
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1583
		model.addAttribute("customRetailer", customRetailer);
1584
		return "partner-investment";
1585
	}
27727 tejbeer 1586
 
27704 amit.gupta 1587
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1588
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
30564 tejbeer 1589
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
27704 amit.gupta 1590
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1591
				.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 1592
 
27704 amit.gupta 1593
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1594
		return "partner-pending-indent-item";
1595
	}
1596
 
27636 tejbeer 1597
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1598
	public String getPartnerActivateStockItem(HttpServletRequest request,
30564 tejbeer 1599
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27636 tejbeer 1600
		List<ActivateItemModel> activateStocks = new ArrayList<>();
1601
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1602
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1603
 
1604
		for (InventoryItem inventoryItem : inventoryItems) {
1605
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1606
			Item item = itemRepository.selectById(inventoryItem.getItemId());
1607
			ActivateItemModel aim = new ActivateItemModel();
1608
			aim.setFofoId(inventoryItem.getFofoId());
1609
			aim.setQuantity(inventoryItem.getGoodQuantity());
1610
			aim.setAmount(tagListing.getSellingPrice());
1611
			aim.setItemDescription(item.getItemDescription());
1612
			aim.setItemId(inventoryItem.getItemId());
1613
			activateStocks.add(aim);
1614
		}
1615
 
1616
		model.addAttribute("activateStocks", activateStocks);
1617
		model.addAttribute("customRetailer", customRetailer);
1618
		return "partner-activate-stock";
1619
	}
1620
 
1621
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1622
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
30564 tejbeer 1623
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27636 tejbeer 1624
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1625
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1626
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
1627
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
27638 tejbeer 1628
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
1629
				curDate.with(LocalTime.MAX), fofoId);
27636 tejbeer 1630
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1631
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 1632
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1633
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1634
 
27636 tejbeer 1635
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1636
		model.addAttribute("brandMtdAmount", brandMtdAmount);
27638 tejbeer 1637
		model.addAttribute("brandMtdQty", brandMtdQty);
27636 tejbeer 1638
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
27638 tejbeer 1639
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1640
 
27636 tejbeer 1641
		model.addAttribute("customRetailer", customRetailer);
1642
		return "partner-brand-mtd-sale";
1643
	}
1644
 
27637 tejbeer 1645
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1646
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
30564 tejbeer 1647
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27637 tejbeer 1648
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1649
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1650
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1651
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27638 tejbeer 1652
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1653
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 1654
 
1655
		Double accesorieslmtdsale = fofoOrderRepository
1656
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1657
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
1658
				.get(fofoId);
27638 tejbeer 1659
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1660
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1661
				Optional.of(false)).get(fofoId);
1662
 
27637 tejbeer 1663
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
27638 tejbeer 1664
		model.addAttribute("brandLmtdQty", brandLmtdQty);
1665
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
27637 tejbeer 1666
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1667
		model.addAttribute("customRetailer", customRetailer);
1668
		return "partner-brand-lmtd-sale";
1669
	}
1670
 
27660 tejbeer 1671
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1672
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
30564 tejbeer 1673
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27660 tejbeer 1674
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1675
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1676
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1677
 
1678
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
27893 tejbeer 1679
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1680
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
27893 tejbeer 1681
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 1682
 
27893 tejbeer 1683
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1684
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 1685
		Long accesorieslmsqty = fofoOrderRepository
1686
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
27893 tejbeer 1687
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
27660 tejbeer 1688
				.get(fofoId);
1689
 
1690
		model.addAttribute("brandLMSAmount", brandLMSAmount);
1691
		model.addAttribute("brandLmsQty", brandLmsQty);
1692
		model.addAttribute("accesorieslmssale", accesorieslmssale);
1693
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1694
		model.addAttribute("customRetailer", customRetailer);
1695
		return "partner-brand-lms-sale";
1696
	}
1697
 
27640 tejbeer 1698
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1699
	public String getPatnerInStock(HttpServletRequest request,
30564 tejbeer 1700
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27640 tejbeer 1701
 
1702
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1703
 
27660 tejbeer 1704
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
27640 tejbeer 1705
				.selectSumInStockMobileGroupByBrand(fofoId);
27660 tejbeer 1706
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
27640 tejbeer 1707
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
1708
 
27660 tejbeer 1709
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
1710
				.selectInStockItemsByBrand(fofoId);
1711
 
1712
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
1713
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1714
 
1715
		model.addAttribute("stockItemMap", stockItemMap);
1716
		model.addAttribute("mobileStock", mobileStocks);
1717
		model.addAttribute("accesStock", accesStock);
27640 tejbeer 1718
		model.addAttribute("customRetailer", customRetailer);
1719
		return "partner-instock-item";
1720
	}
1721
 
27660 tejbeer 1722
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1723
	public String getOpenTicketByFofoId(HttpServletRequest request,
30564 tejbeer 1724
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27660 tejbeer 1725
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1726
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1727
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
1728
				.collect(Collectors.toList());
1729
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1730
 
1731
		for (TicketAssigned ticketAssign : ticketAssigns) {
1732
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1733
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1734
		}
1735
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1736
		model.addAttribute("ticketAssigns", ticketAssigns);
1737
		model.addAttribute("customRetailer", customRetailer);
1738
		return "open-ticket";
1739
	}
1740
 
27893 tejbeer 1741
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
1742
	public String getPartnerSecondarySale(HttpServletRequest request,
30564 tejbeer 1743
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
27893 tejbeer 1744
			throws Exception {
1745
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1746
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1747
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1748
		LocalDateTime startDate = null;
1749
		LocalDateTime endDate = null;
1750
		List<InStockBrandModel> secondarySale = null;
1751
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
1752
 
1753
		if (timeValue.equals("mtd")) {
1754
			startDate = curDate.withDayOfMonth(1);
1755
			endDate = curDate.with(LocalTime.MAX);
1756
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1757
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1758
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1759
			LOGGER.info("secondarySalemtd" + secondarySale);
1760
		} else if (timeValue.equals("lmtd")) {
1761
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1762
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
1763
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1764
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1765
 
1766
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1767
			LOGGER.info("secondarySalelmtd" + secondarySale);
1768
 
1769
		} else {
1770
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1771
			endDate = curDate.withDayOfMonth(1);
1772
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1773
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1774
 
1775
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1776
			LOGGER.info("secondarySalelms" + secondarySale);
1777
 
1778
		}
1779
 
1780
		LOGGER.info("secondarySale" + secondarySale);
1781
		model.addAttribute("secondarySale", secondarySale);
1782
		model.addAttribute("secondaryItemSale", secondaryItemSale);
1783
		model.addAttribute("customRetailer", customRetailer);
1784
 
1785
		return "partner-secondary-order";
1786
	}
1787
 
28451 tejbeer 1788
	@RequestMapping(value = "/getMobileBrandWise", method = RequestMethod.GET)
1789
	public String getMobileBrandWise(HttpServletRequest request, Model model) throws Exception {
1790
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1791
		String email = loginDetails.getEmailId();
1792
 
1793
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
31662 amit.gupta 1794
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28451 tejbeer 1795
 
1796
		Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
1797
		partnersBrandSaleMap = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds))
1798
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1799
 
1800
		List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
1801
				.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
1802
		for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
1803
			BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
1804
			if (bpt != null) {
1805
				bpt.setAmtd(un.getUnbilledMtd());
1806
				bpt.setUamtdQty(un.getUnbilledMTDQty());
1807
			} else {
1808
				bpt = new BrandWisePartnerSaleModel();
1809
				bpt.setBrand(un.getBrand());
1810
				bpt.setAmtd(un.getUnbilledMtd());
1811
				bpt.setUamtdQty(un.getUnbilledMTDQty());
1812
				bpt.setLms(0);
1813
				bpt.setLmtd(0);
1814
				bpt.setMtd(0);
1815
				bpt.setMtdQty(0);
1816
				bpt.setLmtd(0);
1817
				bpt.setLmtdQty(0);
1818
				partnersBrandSaleMap.put(un.getBrand(), bpt);
1819
			}
1820
		}
1821
 
1822
		model.addAttribute("brandSalesMap", partnersBrandSaleMap);
1823
 
1824
		return "mobile-brand-wise-report";
1825
	}
1826
 
1827
	@RequestMapping(value = "/getAccessoriesBrandWise", method = RequestMethod.GET)
1828
	public String getAccessoriesBrandWise(HttpServletRequest request, Model model) throws Exception {
1829
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1830
		String email = loginDetails.getEmailId();
1831
 
31662 amit.gupta 1832
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28451 tejbeer 1833
 
1834
		List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
1835
 
1836
		accessoriesBrandSales = fofoStoreRepository
1837
				.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
1838
 
1839
		model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1840
		return "accessories-brand-wise-report";
1841
	}
1842
 
1843
	@RequestMapping(value = "/getMobileLMSGraph", method = RequestMethod.GET)
28461 tejbeer 1844
	public String getMobileLMSGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
30564 tejbeer 1845
			@RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
1846
			@RequestParam List<Integer> fofoIds, @RequestParam String filterType, Model model) throws Exception {
28451 tejbeer 1847
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1848
				.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
1849
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1850
 
1851
		ChartModel cm;
1852
		if (warehouseId != 0) {
28468 tejbeer 1853
			cm = adminUser.getBrandWiseLms(Arrays.asList(warehouseId),
30279 tejbeer 1854
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1855
					endDate.toLocalDate(), filterType);
28451 tejbeer 1856
		} else {
28468 tejbeer 1857
			cm = adminUser.getBrandWiseLms(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
30279 tejbeer 1858
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1859
					endDate.toLocalDate(), filterType);
28451 tejbeer 1860
 
1861
		}
1862
 
1863
		LOGGER.info("chartMap" + gson.toJson(cm));
1864
		model.addAttribute("chartMap", gson.toJson(cm));
1865
		return "brand-wise-mobile-lms-chart";
1866
	}
1867
 
28461 tejbeer 1868
	@RequestMapping(value = "/getMobileLMSFilter", method = RequestMethod.GET)
1869
	public String getMobileLMSFilter(HttpServletRequest request,
30564 tejbeer 1870
			@RequestParam(required = false, defaultValue = "0") int warehouseId,
1871
			@RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
1872
			Model model) throws Exception {
28461 tejbeer 1873
 
1874
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1875
		String email = loginDetails.getEmailId();
1876
 
30279 tejbeer 1877
		if (date == null) {
1878
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
28461 tejbeer 1879
 
30279 tejbeer 1880
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1881
			date = startOfMonth.toLocalDate().atStartOfDay();
1882
		}
28461 tejbeer 1883
 
30279 tejbeer 1884
		if (endDate == null) {
1885
			LocalDateTime curDate = LocalDate.now().atTime(LocalTime.MAX);
1886
 
1887
			endDate = curDate;
1888
 
1889
		}
1890
 
1891
		Map<String, Object> map = adminUser.getFilter(warehouseId, email, date, endDate);
28461 tejbeer 1892
		model.addAttribute("warehouseId", warehouseId);
1893
		model.addAllAttributes(map);
1894
 
30279 tejbeer 1895
		return "chart-filter-lms";
28461 tejbeer 1896
	}
1897
 
1898
	@RequestMapping(value = "/getMobileLMPGraph", method = RequestMethod.GET)
1899
	public String getMobileLMPGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
30564 tejbeer 1900
			@RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
1901
			@RequestParam List<Integer> fofoIds, @RequestParam String filterType, Model model) throws Exception {
28461 tejbeer 1902
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1903
				.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
1904
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1905
 
1906
		ChartModel cm;
1907
		if (warehouseId != 0) {
28468 tejbeer 1908
			cm = adminUser.getBrandWiseLmp(Arrays.asList(warehouseId),
30279 tejbeer 1909
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1910
					endDate.toLocalDate(), filterType);
28461 tejbeer 1911
		} else {
28468 tejbeer 1912
			cm = adminUser.getBrandWiseLmp(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
30279 tejbeer 1913
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1914
					endDate.toLocalDate(), filterType);
28461 tejbeer 1915
 
1916
		}
1917
 
1918
		LOGGER.info("chartMap" + gson.toJson(cm));
1919
		model.addAttribute("chartMap", gson.toJson(cm));
1920
		return "brand-wise-mobile-lmp-chart";
1921
	}
1922
 
31273 tejbeer 1923
	@RequestMapping(value = "/getSaleCountByMilestone", method = RequestMethod.GET)
1924
	public String getSaleCountByMilestone(HttpServletRequest request,
31259 tejbeer 1925
			@RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
1926
 
1927
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1928
		String email = loginDetails.getEmailId();
31662 amit.gupta 1929
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
31273 tejbeer 1930
		Map<Integer, Double> last3MonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
1931
				LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now(), 0, false);
31259 tejbeer 1932
 
1933
		if (fofoIds != null && fofoIds.size() > 0) {
31273 tejbeer 1934
			if (warehouseId != 0) {
1935
				fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
1936
						.stream().map(x -> x).collect(Collectors.toSet());
1937
			}
31259 tejbeer 1938
			Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1939
			if (partnerStats != null) {
31263 tejbeer 1940
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x))
1941
						.map(x -> partnerStats.get(x)).collect(Collectors.toList());
31318 tejbeer 1942
				Map<Milestone, List<Integer>> avg3Monthlms = new HashMap<>();
31267 tejbeer 1943
				if (!last3MonthSale.isEmpty()) {
1944
					int days = 60 + LocalDateTime.now().getDayOfMonth();
1945
					for (Entry<Integer, Double> last3MonthEntry : last3MonthSale.entrySet()) {
1946
						if (fofoIds.contains(last3MonthEntry.getKey())) {
1947
							Double monthSale = last3MonthEntry.getValue();
1948
							if (monthSale == null) {
1949
								monthSale = (double) 0;
1950
 
1951
							}
1952
							double avg3MonthSale = (monthSale / days) * 30;
31269 tejbeer 1953
							Milestone milestone = Milestone.get((int) avg3MonthSale);
31318 tejbeer 1954
 
1955
							List<Integer> values = null;
31319 tejbeer 1956
 
31273 tejbeer 1957
							if (avg3Monthlms.containsKey(milestone)) {
31318 tejbeer 1958
 
1959
								values = avg3Monthlms.get(milestone);
1960
								values.add(last3MonthEntry.getKey());
1961
								avg3Monthlms.put(milestone, values);
1962
 
31267 tejbeer 1963
							} else {
31319 tejbeer 1964
								values = new ArrayList<>();
1965
 
31318 tejbeer 1966
								values.add(last3MonthEntry.getKey());
1967
								avg3Monthlms.put(milestone, values);
31267 tejbeer 1968
 
1969
							}
1970
						}
1971
 
1972
					}
1973
 
1974
				}
1975
 
31260 tejbeer 1976
				if (partnerDetails != null) {
31263 tejbeer 1977
 
31318 tejbeer 1978
					Map<Milestone, List<Integer>> mtdMap = partnerDetails.stream()
31285 tejbeer 1979
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getMtd()),
1980
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
31318 tejbeer 1981
					Map<Milestone, List<Integer>> lmtdMap = partnerDetails.stream()
1982
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getLmtd()),
1983
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
31285 tejbeer 1984
 
31318 tejbeer 1985
					Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream()
1986
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getLms()),
1987
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1988
 
31260 tejbeer 1989
					model.addAttribute("mtdMap", mtdMap);
1990
					model.addAttribute("lmtdMap", lmtdMap);
31273 tejbeer 1991
					model.addAttribute("avg3Monthlms", avg3Monthlms);
31260 tejbeer 1992
					model.addAttribute("lmsMap", lmsMap);
1993
				}
1994
 
31259 tejbeer 1995
			}
1996
		}
1997
 
31267 tejbeer 1998
		model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
31273 tejbeer 1999
		model.addAttribute("warehouseId", warehouseId);
2000
		model.addAttribute("milestones", Milestone.values());
31267 tejbeer 2001
 
31273 tejbeer 2002
		return "sale-milestone";
2003
 
2004
	}
2005
 
2006
	@RequestMapping(value = "/getPurchaseCountByMileStone", method = RequestMethod.GET)
2007
	public String getPurchaseCountByMileStone(HttpServletRequest request,
2008
			@RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
2009
 
2010
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2011
		String email = loginDetails.getEmailId();
31662 amit.gupta 2012
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
31273 tejbeer 2013
		Map<Integer, Double> last3MonthS = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
2014
				LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now());
2015
 
2016
		if (fofoIds != null && fofoIds.size() > 0) {
2017
			if (warehouseId != 0) {
2018
				fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
2019
						.stream().map(x -> x).collect(Collectors.toSet());
2020
			}
2021
			Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
2022
			if (partnerStats != null) {
2023
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x))
2024
						.map(x -> partnerStats.get(x)).collect(Collectors.toList());
31320 tejbeer 2025
				Map<Milestone, List<Integer>> avg3MonthS = new HashMap<>();
31273 tejbeer 2026
				if (!last3MonthS.isEmpty()) {
2027
					int days = 60 + LocalDateTime.now().getDayOfMonth();
2028
					for (Entry<Integer, Double> last3MonthSEntry : last3MonthS.entrySet()) {
2029
						if (fofoIds.contains(last3MonthSEntry.getKey())) {
2030
							Double monthSec = last3MonthSEntry.getValue();
2031
							if (monthSec == null) {
2032
								monthSec = (double) 0;
2033
 
2034
							}
2035
							double avg3MonthSale = (monthSec / days) * 30;
2036
							Milestone milestone = Milestone.get((int) avg3MonthSale);
31320 tejbeer 2037
 
2038
							List<Integer> values = null;
31273 tejbeer 2039
							if (avg3MonthS.containsKey(milestone)) {
31320 tejbeer 2040
								values = avg3MonthS.get(milestone);
2041
								values.add(last3MonthSEntry.getKey());
2042
 
2043
								avg3MonthS.put(milestone, values);
31273 tejbeer 2044
							} else {
2045
 
31320 tejbeer 2046
								values = new ArrayList<>();
2047
 
2048
								values.add(last3MonthSEntry.getKey());
2049
 
2050
								avg3MonthS.put(milestone, values);
2051
 
31273 tejbeer 2052
							}
2053
						}
2054
 
2055
					}
2056
 
2057
				}
2058
 
2059
				if (partnerDetails != null) {
31320 tejbeer 2060
					Map<Milestone, List<Integer>> smtdMap = partnerDetails.stream()
2061
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarymtd()),
2062
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
2063
					Map<Milestone, List<Integer>> slmtdMap = partnerDetails.stream()
2064
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylmtd()),
2065
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
2066
					Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream()
2067
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylms()),
2068
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
31273 tejbeer 2069
 
2070
					model.addAttribute("smtdMap", smtdMap);
2071
					model.addAttribute("slmtdMap", slmtdMap);
2072
					model.addAttribute("avg3MonthS", avg3MonthS);
2073
					model.addAttribute("lmsMap", lmsMap);
2074
 
2075
				}
2076
 
2077
			}
31270 tejbeer 2078
		}
31267 tejbeer 2079
 
31273 tejbeer 2080
		model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
31267 tejbeer 2081
		model.addAttribute("warehouseId", warehouseId);
31259 tejbeer 2082
		model.addAttribute("milestones", Milestone.values());
2083
 
31273 tejbeer 2084
		return "purchase-milestone";
31259 tejbeer 2085
 
2086
	}
2087
 
28825 tejbeer 2088
	@RequestMapping(value = "/getActivatedModelWarehouseWise", method = RequestMethod.GET)
2089
	public String getActivatedModelWarehouseWise(HttpServletRequest request, Model model, @RequestParam String brand)
2090
			throws Exception {
2091
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2092
		List<Integer> fofoIds = getFofoIds(loginDetails);
2093
		List<WarehouseWiseActivatedModel> warehouseWiseActivatedModels = activatedImeiRepository
2094
				.selectActivatedModelGroupByWarehouse(brand, fofoIds);
2095
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2096
 
2097
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
2098
 
2099
		List<String> brands = mobileBrands.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
2100
		LOGGER.info("brands" + brands.add("Redmi"));
2101
 
2102
		model.addAttribute("warehouseWiseActivatedModels", warehouseWiseActivatedModels);
2103
		model.addAttribute("warehouseMap", warehouseMap);
2104
		model.addAttribute("brands", brands);
2105
		model.addAttribute("selectedbrand", brand);
2106
		return "warehousewise_activated_model";
2107
	}
2108
 
2109
	@RequestMapping(value = "/getActivatedModelByBrand", method = RequestMethod.GET)
2110
	public String getActivatedModelByBrand(HttpServletRequest request, Model model) throws Exception {
2111
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
31662 amit.gupta 2112
		Set<Integer> fofoIds = csService1.getAuthFofoIds(loginDetails.getEmailId(), true);
31152 tejbeer 2113
 
28825 tejbeer 2114
		List<BrandWiseActivatedModel> activatedModels = activatedImeiRepository
2115
				.selectActivatedModelGroupByBrand(new ArrayList<>(fofoIds));
2116
		model.addAttribute("activatedModels", activatedModels);
2117
		return "activation-brandwise-report";
2118
	}
2119
 
2120
	@RequestMapping(value = "/getWarehouseBrandWiseItemActivatedModel", method = RequestMethod.GET)
2121
	public String getWarehouseBrandWiseItemActivatedModel(HttpServletRequest request, Model model,
30564 tejbeer 2122
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
28825 tejbeer 2123
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2124
		List<Integer> fofoIds = getFofoIds(loginDetails);
2125
 
2126
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2127
		List<WarehouseBrandWiseItemActivatedModel> activatedItems = activatedImeiRepository
2128
				.selectWarehouseBrandActivatedItem(warehouseId, brand, fofoIds);
2129
		model.addAttribute("warehouseMap", warehouseMap);
2130
		model.addAttribute("activatedItems", activatedItems);
2131
		return "warehouse-activated-itemwise-model";
2132
 
2133
	}
2134
 
2135
	@RequestMapping(value = "/getActivatedImeiUpdationDate", method = RequestMethod.GET)
2136
	public String getActivatedImeiUpdationDate(HttpServletRequest request, Model model) throws Exception {
2137
 
2138
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2139
 
2140
		List<ActivationImeiUpdationModel> activationImeiUpdations = activatedImeiRepository
2141
				.selectActivatedUpdationDate();
2142
		model.addAttribute("warehouseMap", warehouseMap);
2143
		model.addAttribute("activationImeiUpdations", activationImeiUpdations);
2144
		return "activation-updation-timestamp";
2145
 
2146
	}
2147
 
2148
	private List<Integer> getFofoIds(LoginDetails loginDetails) throws ProfitMandiBusinessException {
2149
		String email = loginDetails.getEmailId();
2150
 
2151
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
2152
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
2153
 
2154
		Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
2155
		if (emails.contains(authUser.getEmailId())) {
2156
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
2157
			LOGGER.info("fofoIds" + fofoIds);
2158
		}
2159
 
2160
		if (fofoIds == null) {
2161
			List<Position> positions1 = positionRepository.selectAll(authUser.getId());
2162
			if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
2163
					.count() > 0) {
2164
				fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream())
2165
						.map(x -> x.getPartnerId()).collect(Collectors.toSet());
2166
			}
2167
		}
2168
		return new ArrayList<>(fofoIds);
2169
	}
2170
 
31285 tejbeer 2171
	@RequestMapping(value = "/getMonthWiseSale", method = RequestMethod.GET)
2172
	public String getPartnerSaleByMonth(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model)
2173
			throws Exception {
2174
 
31287 tejbeer 2175
		YearMonth now = YearMonth.now();
2176
		YearMonth ym = YearMonth.now().minusMonths(12);
2177
		List<YearMonth> list = new ArrayList<>();
31315 tejbeer 2178
		while (!now.isBefore(ym)) {
2179
			list.add(now);
2180
			now = now.minusMonths(1);
31287 tejbeer 2181
		}
2182
 
2183
		model.addAttribute("yearMonth", list);
2184
 
31285 tejbeer 2185
		List<PartnerMonthlySaleModel> partnerMonthlySaleModels = fofoOrderItemRepository
31301 tejbeer 2186
				.selectPartnerMonthlySale(fofoIds, LocalDateTime.now().minusMonths(12).withDayOfMonth(1));
31287 tejbeer 2187
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
2188
		Map<Integer, Map<YearMonth, Double>> partnerMonthSaleMap = new HashMap<>();
2189
		if (!partnerMonthlySaleModels.isEmpty()) {
2190
 
2191
			partnerMonthSaleMap = partnerMonthlySaleModels.stream()
2192
					.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toMap(
2193
							x -> YearMonth.parse(x.getYearMonth(), dateTimeFormatter), x -> (double) x.getAmount())));
2194
		}
2195
 
31339 tejbeer 2196
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream()
2197
				.filter(x -> fofoIds.contains(x.getKey()))
2198
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
31287 tejbeer 2199
 
2200
		model.addAttribute("customRetailerMap", customRetailerMap);
2201
 
2202
		model.addAttribute("customRetailerMap", customRetailerMap);
2203
 
2204
		model.addAttribute("partnerMonthSaleMap", partnerMonthSaleMap);
2205
		return "monthly-partner-sale";
2206
 
31285 tejbeer 2207
	}
31297 tejbeer 2208
 
2209
	@RequestMapping(value = "/getMonthWisePurchase", method = RequestMethod.GET)
2210
	public String getMonthWisePurchase(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model)
2211
			throws Exception {
2212
 
2213
		YearMonth now = YearMonth.now();
2214
		YearMonth ym = YearMonth.now().minusMonths(12);
2215
		List<YearMonth> list = new ArrayList<>();
31315 tejbeer 2216
		while (!now.isBefore(ym)) {
2217
			list.add(now);
2218
			now = now.minusMonths(1);
31297 tejbeer 2219
		}
2220
 
2221
		model.addAttribute("yearMonth", list);
2222
 
31466 tejbeer 2223
		List<PartnerMonthlySaleModel> partnerMonthlySaleModels = orderRepository.selectSecondaryGroupByYearMonth(
2224
				fofoIds, LocalDate.now().withDayOfMonth(1).atStartOfDay().minusMonths(12));
31361 amit.gupta 2225
		Map<Integer, Map<YearMonth, Double>> partnerMonthPurchaseMap = partnerMonthlySaleModels.stream()
31466 tejbeer 2226
				.collect(Collectors.groupingBy(x -> x.getFofoId(),
2227
						Collectors.groupingBy(
2228
								y -> YearMonth.parse(y.getYearMonth(), DateTimeFormatter.ofPattern("MM-yyyy")),
2229
								Collectors.summingDouble(x -> x.getAmount()))));
31297 tejbeer 2230
 
31339 tejbeer 2231
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream()
2232
				.filter(x -> fofoIds.contains(x.getKey()))
2233
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
31297 tejbeer 2234
		model.addAttribute("customRetailerMap", customRetailerMap);
2235
		model.addAttribute("partnerMonthPurchaseMap", partnerMonthPurchaseMap);
2236
		return "monthly-partner-purchase";
2237
 
2238
	}
21615 kshitij.so 2239
}