Subversion Repositories SmartDukaan

Rev

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