Subversion Repositories SmartDukaan

Rev

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