Subversion Repositories SmartDukaan

Rev

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