Subversion Repositories SmartDukaan

Rev

Rev 30699 | Rev 30831 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22860 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
29585 manish 3
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22860 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30148 amit.gupta 5
import com.spice.profitmandi.common.model.CustomRetailer;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
7
import com.spice.profitmandi.common.model.SchemeItems;
8
import com.spice.profitmandi.common.model.SchemeModel;
29585 manish 9
import com.spice.profitmandi.common.services.ReporticoService;
30326 amit.gupta 10
import com.spice.profitmandi.common.util.ExcelUtils;
11
import com.spice.profitmandi.common.util.FileUtil;
12
import com.spice.profitmandi.common.util.FormattingUtils;
23784 ashik.ali 13
import com.spice.profitmandi.common.web.util.ResponseSender;
30064 amit.gupta 14
import com.spice.profitmandi.dao.entity.catalog.*;
15
import com.spice.profitmandi.dao.entity.fofo.*;
28795 tejbeer 16
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
17
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
27389 amit.gupta 18
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
28491 amit.gupta 19
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
29707 tejbeer 20
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
29899 tejbeer 21
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
29585 manish 22
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
30064 amit.gupta 23
import com.spice.profitmandi.dao.model.*;
24
import com.spice.profitmandi.dao.repository.catalog.*;
29899 tejbeer 25
import com.spice.profitmandi.dao.repository.cs.CsService;
26588 tejbeer 26
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27
import com.spice.profitmandi.dao.repository.dtr.Mongo;
30064 amit.gupta 28
import com.spice.profitmandi.dao.repository.fofo.*;
28795 tejbeer 29
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
30
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
30768 amit.gupta 31
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
23798 amit.gupta 32
import com.spice.profitmandi.service.authentication.RoleManager;
23020 ashik.ali 33
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 34
import com.spice.profitmandi.service.offers.OfferService;
22860 ashik.ali 35
import com.spice.profitmandi.service.scheme.SchemeService;
26588 tejbeer 36
import com.spice.profitmandi.service.user.RetailerService;
29585 manish 37
import com.spice.profitmandi.service.wallet.WalletService;
22860 ashik.ali 38
import com.spice.profitmandi.web.model.LoginDetails;
39
import com.spice.profitmandi.web.util.CookiesProcessor;
23570 amit.gupta 40
import com.spice.profitmandi.web.util.MVCResponseSender;
29585 manish 41
import in.shop2020.model.v1.order.WalletReferenceType;
30064 amit.gupta 42
import org.apache.commons.csv.CSVRecord;
43
import org.apache.logging.log4j.LogManager;
44
import org.apache.logging.log4j.Logger;
45
import org.springframework.beans.factory.annotation.Autowired;
46
import org.springframework.beans.factory.annotation.Qualifier;
47
import org.springframework.core.io.InputStreamResource;
48
import org.springframework.http.HttpHeaders;
49
import org.springframework.http.HttpStatus;
50
import org.springframework.http.ResponseEntity;
51
import org.springframework.stereotype.Controller;
52
import org.springframework.ui.Model;
53
import org.springframework.web.bind.annotation.*;
54
import org.springframework.web.multipart.MultipartFile;
29585 manish 55
 
30064 amit.gupta 56
import javax.servlet.http.HttpServletRequest;
57
import javax.servlet.http.HttpServletResponse;
58
import javax.transaction.Transactional;
59
import java.io.ByteArrayInputStream;
60
import java.io.ByteArrayOutputStream;
61
import java.io.InputStream;
62
import java.time.*;
63
import java.time.format.DateTimeFormatter;
64
import java.util.*;
65
import java.util.stream.Collectors;
66
 
22860 ashik.ali 67
@Controller
25369 amit.gupta 68
@Transactional(rollbackOn = Throwable.class)
22860 ashik.ali 69
public class SchemeController {
30564 tejbeer 70
	// LED TV
71
	private static final List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.MOBILE_CATEGORY_ID,
72
			ProfitMandiConstants.TABLET_CATEGORY_ID, 14202);
22860 ashik.ali 73
 
23568 govind 74
	private static final Logger LOGGER = LogManager.getLogger(SchemeController.class);
22860 ashik.ali 75
 
76
	@Autowired
22927 ashik.ali 77
	private SchemeService schemeService;
27897 amit.gupta 78
 
27876 amit.gupta 79
	@Autowired
80
	private OfferService offerService;
23786 amit.gupta 81
 
22860 ashik.ali 82
	@Autowired
27389 amit.gupta 83
	private StateGstRateRepository stateGstRateRepository;
27612 tejbeer 84
 
27389 amit.gupta 85
	@Autowired
27416 amit.gupta 86
	private ItemRepository itemRepository;
29608 amit.gupta 87
 
29585 manish 88
	@Autowired
89
	private ReporticoService reporticoService;
27612 tejbeer 90
 
27416 amit.gupta 91
	@Autowired
22927 ashik.ali 92
	private SchemeRepository schemeRepository;
22860 ashik.ali 93
 
94
	@Autowired
23556 amit.gupta 95
	private SchemeItemRepository schemeItemRepository;
23786 amit.gupta 96
 
23556 amit.gupta 97
	@Autowired
23570 amit.gupta 98
	private MVCResponseSender mvcResponseSender;
23786 amit.gupta 99
 
23570 amit.gupta 100
	@Autowired
22927 ashik.ali 101
	private CookiesProcessor cookiesProcessor;
23786 amit.gupta 102
 
23020 ashik.ali 103
	@Autowired
23784 ashik.ali 104
	@Qualifier("fofoInventoryService")
23020 ashik.ali 105
	private InventoryService inventoryService;
23556 amit.gupta 106
 
107
	@Autowired
108
	private TagListingRepository tagListingRepository;
23914 govind 109
 
23798 amit.gupta 110
	@Autowired
111
	private RoleManager roleManager;
23786 amit.gupta 112
 
23506 amit.gupta 113
	@Autowired
27394 amit.gupta 114
	private ResponseSender<?> responseSender;
23786 amit.gupta 115
 
23784 ashik.ali 116
	@Autowired
27394 amit.gupta 117
	private FofoStoreRepository fofoStoreRepository;
23786 amit.gupta 118
 
23784 ashik.ali 119
	@Autowired
30651 amit.gupta 120
	private OfferPayoutRepository offerPayoutRepository;
121
 
122
	@Autowired
27394 amit.gupta 123
	private RetailerService retailerService;
22860 ashik.ali 124
 
27394 amit.gupta 125
	@Autowired
126
	private Mongo mongoClient;
29608 amit.gupta 127
 
29585 manish 128
	@Autowired
129
	WalletService walletService;
26588 tejbeer 130
 
131
	@Autowired
29585 manish 132
	PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
133
 
134
	@Autowired
26674 tejbeer 135
	private PartnerTypeChangeService partnerTypeChangeService;
136
 
28795 tejbeer 137
	@Autowired
138
	InventoryItemRepository inventoryItemRepository;
139
 
140
	@Autowired
141
	PriceDropIMEIRepository priceDropIMEIRepository;
142
 
143
	@Autowired
144
	PriceDropRepository priceDropRepository;
145
 
146
	@Autowired
147
	SchemeInOutRepository schemeInOutRepository;
148
 
29707 tejbeer 149
	@Autowired
150
	private CustomerOfferRepository customerOfferRepository;
151
 
152
	@Autowired
153
	private CustomerOfferItemRepository customerOfferItemRepository;
154
 
155
	@Autowired
156
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
157
 
29899 tejbeer 158
	@Autowired
159
	private CsService csService;
160
 
30494 amit.gupta 161
	@Autowired
162
	private CategoryRepository categoryRepository;
163
 
29899 tejbeer 164
	List<String> adminEmail = Arrays.asList("tarun.verma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
30564 tejbeer 165
			"amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com");
29899 tejbeer 166
 
22860 ashik.ali 167
	@RequestMapping(value = "/createScheme", method = RequestMethod.GET)
29899 tejbeer 168
	public String createScheme(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
169
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29608 amit.gupta 170
 
29585 manish 171
		LocalDate currentdate = LocalDate.now();
172
		Month month = currentdate.getMonth().minus(1);
173
		model.addAttribute("month", month);
29608 amit.gupta 174
 
23786 amit.gupta 175
		// Map<Integer, String> itemIdItemDescriptionMap =
176
		// inventoryService.getAllItemIdItemDescriptionMap();
177
		// model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
30564 tejbeer 178
		// List<Category> categories = inventoryService.getAllCategories();
30494 amit.gupta 179
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
180
		categories = categories.stream().sorted(Comparator.comparing(Category::getId)).collect(Collectors.toList());
30564 tejbeer 181
		// Set<String> brands =
182
		// inventoryService.getAllTagListingBrands(ProfitMandiConstants.MOBILE_CATEGORY_ID);
183
		// brands.addAll(inventoryService.getAllTagListingBrands(14206));
29899 tejbeer 184
 
185
		boolean fullAccesss = this.getAccess(loginDetails.getEmailId());
186
 
187
		model.addAttribute("fullAccesss", fullAccesss);
188
 
30494 amit.gupta 189
		model.addAttribute("categories", categories);
25505 amit.gupta 190
		model.addAttribute("retailerTypes", PartnerType.values());
22860 ashik.ali 191
		return "create-scheme";
192
	}
23786 amit.gupta 193
 
29899 tejbeer 194
	private boolean getAccess(String emailId) {
195
 
196
		boolean fullAccesss = false;
197
		List<String> emails = csService
29926 amit.gupta 198
				.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, EscalationType.L3).stream()
29899 tejbeer 199
				.map(x -> x.getEmailId()).collect(Collectors.toList());
200
 
201
		emails.addAll(
29926 amit.gupta 202
				csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, EscalationType.L2)
29899 tejbeer 203
						.stream().map(x -> x.getEmailId()).collect(Collectors.toList()));
204
 
205
		if (adminEmail.contains(emailId)) {
206
			fullAccesss = true;
207
		}
208
 
209
		if (emails.contains(emailId)) {
210
			fullAccesss = false;
211
		}
212
 
213
		return fullAccesss;
214
 
215
	}
216
 
30499 amit.gupta 217
	@RequestMapping(value = "/getCatalogDescriptionByBrands", method = RequestMethod.GET)
30564 tejbeer 218
	public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId,
30651 amit.gupta 219
											@RequestParam List<String> brands, Model model) throws Exception {
30564 tejbeer 220
		Map<Integer, String> catalogIdItemDescriptionMap = inventoryService.getModelDescriptionMap(categoryId, brands);
30148 amit.gupta 221
		model.addAttribute("catalogIdItemDescriptionMap", catalogIdItemDescriptionMap);
23786 amit.gupta 222
		// model.addAttribute("brands", inventoryService.getAllBrands());
23914 govind 223
 
23419 ashik.ali 224
		return "tag-listing-items-description";
23020 ashik.ali 225
	}
23556 amit.gupta 226
 
30494 amit.gupta 227
	@RequestMapping(value = "/getBrandsByCategory", method = RequestMethod.GET)
30564 tejbeer 228
	public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId, Model model)
229
			throws Exception {
230
		Set<String> brands = inventoryService.getAllTagListingBrands(categoryId);
30494 amit.gupta 231
		model.addAttribute("brands", brands);
30499 amit.gupta 232
		model.addAttribute("categoryId", categoryId);
30494 amit.gupta 233
 
234
		return "tag-listing-brands";
235
	}
236
 
23556 amit.gupta 237
	@RequestMapping(value = "/schemes/update-schemes-page", method = RequestMethod.GET)
238
	public String updateShcemes(HttpServletRequest request) throws ProfitMandiBusinessException {
239
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23799 amit.gupta 240
		if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
23556 amit.gupta 241
			throw new ProfitMandiBusinessException("User", loginDetails.getEmailId(), "Unauthorised access");
242
		}
243
		return "update-schemes-page";
244
	}
29608 amit.gupta 245
 
30768 amit.gupta 246
	@Autowired
247
	TransactionRepository transactionRepository;
248
 
29585 manish 249
	@RequestMapping(value = "/payMonthlyInvestment", method = RequestMethod.POST)
250
	public void payMonthlyInvestment(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
29608 amit.gupta 251
 
29585 manish 252
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
253
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
254
		int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
255
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
256
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
257
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
258
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
259
				.filter(x -> x.getShortPercentage() <= 10)
260
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
261
		LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
262
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
263
				startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
29608 amit.gupta 264
 
265
		if (schemeInOuts.isEmpty()) {
266
			throw new ProfitMandiBusinessException("Investment Payout", "", "No data Found");
29585 manish 267
		}
29608 amit.gupta 268
 
29585 manish 269
		Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
270
				.collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
271
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
272
		Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
273
				Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
274
		System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
275
		for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
276
			int fofoId = retailerEntry.getKey();
277
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
278
					: investmentMaintainedDaysMap.get(fofoId);
25256 amit.gupta 279
 
29585 manish 280
			List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
30768 amit.gupta 281
					.flatMap(List::stream).filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING) && x.getRolledBackTimestamp() == null).collect(Collectors.toList());
29585 manish 282
			float totalAmount = 0;
30768 amit.gupta 283
			LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
284
			boolean sameYearMonth = firstBillingDate.getMonth() == startOfPreviousMonth.getMonth() && firstBillingDate.getYear() == startOfPreviousMonth.getYear();
29608 amit.gupta 285
			for (SchemeInOut sio : schemeInouts) {
30768 amit.gupta 286
				if (sameYearMonth) {
287
					sio.setStatusDescription("Investment payout fully disbursed for first month");
29585 manish 288
					sio.setStatus(SchemePayoutStatus.CREDITED);
289
					sio.setCreditTimestamp(LocalDateTime.now());
290
					totalAmount += sio.getAmount();
291
				} else {
30768 amit.gupta 292
					if (investmentMaintainedDays < 8) {
293
						sio.setStatus(SchemePayoutStatus.REJECTED);
294
						//sio.setRolledBackTimestamp(LocalDateTime.now());
295
						sio.setStatusDescription("Investment maintained for " + investmentMaintainedDays + "(< 8) days");
296
					} else if (investmentMaintainedDays < 12) {
297
						sio.setStatus(SchemePayoutStatus.CREDITED);
298
						sio.setAmount(sio.getAmount() / 2);
299
						sio.setCreditTimestamp(LocalDateTime.now());
300
						sio.setStatusDescription("Investment maintained for " + investmentMaintainedDays + "(< 12) days");
301
						totalAmount += sio.getAmount();
302
					} else {
303
						sio.setStatus(SchemePayoutStatus.CREDITED);
304
						sio.setCreditTimestamp(LocalDateTime.now());
305
						totalAmount += sio.getAmount();
306
					}
29585 manish 307
				}
308
			}
29608 amit.gupta 309
			if (totalAmount > 0) {
310
				String description = "Investment margin paid for "
311
						+ FormattingUtils.formatYearMonth(startOfPreviousMonth.atStartOfDay());
312
				if (investmentMaintainedDays < 12) {
313
					description += ", as maintained for " + investmentMaintainedDays + "(< 12) days";
29585 manish 314
				}
29608 amit.gupta 315
				walletService.addAmountToWallet(fofoId, referenceId, WalletReferenceType.INVESTMENT_PAYOUT, description,
316
						totalAmount, lastOfPreviousMonth.atTime(LocalTime.MAX));
29585 manish 317
			}
30768 amit.gupta 318
			//Its ok to process Margins Pending for activation
319
			schemeService.processActivation();
29585 manish 320
			System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
321
		}
29608 amit.gupta 322
 
30768 amit.gupta 323
 
29585 manish 324
	}
29608 amit.gupta 325
 
29585 manish 326
	@RequestMapping(value = "/evaluateActualInvestmentPayout", method = RequestMethod.GET)
29663 manish 327
	public ResponseEntity<?> evaluateActualInvestmentPayout(HttpServletRequest request, Model model) throws Exception {
328
 
329
		List<List<?>> rows = new ArrayList<>();
330
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
331
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
332
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
333
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
334
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
335
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
336
				.filter(x -> x.getShortPercentage() <= 10)
337
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
338
		LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
339
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
340
				startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
341
		Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
342
				.collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
343
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
344
		Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
345
				Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
346
		System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
347
		for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
348
			int fofoId = retailerEntry.getKey();
349
			List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
350
					.flatMap(List::stream).collect(Collectors.toList());
351
			double totalAmount = schemeInouts.stream().filter(x -> x.getRolledBackTimestamp() == null)
352
					.collect(Collectors.summingDouble(x -> x.getAmount()));
353
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
354
					: investmentMaintainedDaysMap.get(fofoId);
355
			if (investmentMaintainedDays < 8) {
356
				totalAmount = 0;
357
			} else if (investmentMaintainedDays < 12) {
358
				totalAmount = totalAmount / 2;
29585 manish 359
			}
29663 manish 360
			System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
361
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
29608 amit.gupta 362
 
29663 manish 363
			rows.add(Arrays.asList(fofoId, customRetailer.getBusinessName(), customRetailer.getCode(),
364
					investmentMaintainedDays, totalAmount));
29585 manish 365
		}
366
 
29663 manish 367
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
368
				Arrays.asList("fofoId", "Name", "Code", "investmentMaintainedDays", "totalAmount"), rows);
369
 
370
		final HttpHeaders headers = new HttpHeaders();
371
		headers.set("Content-Type", "text/csv");
372
		headers.set("Content-disposition", "inline; filename=investmentMaintainedDays.csv");
373
		headers.setContentLength(baos.toByteArray().length);
374
 
375
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
376
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
377
 
378
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
379
 
380
	}
381
 
29585 manish 382
	@RequestMapping(value = "/processInvestmentDryRun", method = RequestMethod.GET)
29608 amit.gupta 383
	public ResponseEntity<?> processInvestmentDryRun(HttpServletRequest request, Model model) throws Exception {
384
 
29585 manish 385
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
386
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
387
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
388
		List<List<?>> rows = new ArrayList<>();
389
 
29608 amit.gupta 390
		Map<String, String> params = new HashMap<>();
29585 manish 391
 
30682 amit.gupta 392
		params.put("MANUAL_datesBetween_FROMDATE", startOfPreviousMonth.toString());
393
		params.put("MANUAL_datesBetween_TODATE", lastOfPreviousMonth.toString());
29585 manish 394
 
29608 amit.gupta 395
		params.put("type", "INVESTMENT");
29585 manish 396
 
29608 amit.gupta 397
		List<EvaluateSchemeInvestmentPayoutModel> evaluateSchemeInvestmentPayouts = reporticoService.getReports(
398
				EvaluateSchemeInvestmentPayoutModel.class, ReporticoProject.FOCO, "schemepayout.xml", params);
399
		LOGGER.info("reportResponse {}", evaluateSchemeInvestmentPayouts);
400
 
401
		int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
402
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
403
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
404
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
405
				.filter(x -> x.getShortPercentage() <= 10)
406
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
407
 
408
		for (EvaluateSchemeInvestmentPayoutModel esip : evaluateSchemeInvestmentPayouts) {
409
 
410
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(esip.getFofoId()) == null ? 0
411
					: investmentMaintainedDaysMap.get(esip.getFofoId());
412
 
413
			esip.setInvestmentDays(investmentMaintainedDays);
414
 
415
			float processAmount = esip.getPaidAmount() / 2;
416
 
417
			esip.setProcessAmount(processAmount);
418
 
419
			rows.add(Arrays.asList(esip.getCode(), esip.getStoreName(), esip.getFofoId(), esip.getItemId(),
420
					esip.getBrand(), esip.getModelName(), esip.getModelNumber(), esip.getColor(), esip.getSchemeInDp(),
421
					esip.getSchemeOutDp(), esip.getSchemeId(), esip.getName(), esip.getType(), esip.getPartnerType(),
422
					esip.getAmountType(), esip.getAmount(), esip.getPurchaseInvoice(), esip.getSaleInovoice(),
423
					esip.getPaidAmount(), esip.getCreateTimestamp(), esip.getRolledBackTimestamp(),
424
					esip.getSerialNumber(), esip.getInRef(), esip.getOutRef(), esip.getBusinessDate(), esip.getStatus(),
425
					esip.getDescription(), esip.getProcessAmount(), esip.getInvestmentDays()));
29585 manish 426
		}
427
 
29608 amit.gupta 428
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
429
				.getCSVByteStream(Arrays.asList("Code", "Store Name", "Fofo Id", "Item Id", "Brand", "Model Name",
430
						"Model Number", "Color", "Scheme In Dp", "Scheme Out Dp", "Scheme Id", "Name", "Type",
431
						"Partner Type", "Amount Type", "Amount", "Purchase Invoice", "Sale Inovoice", "Paid Amount",
432
						"Create Timestamp", "Rolled Back Timestamp", "Serial Number", "In Ref", "Out Ref",
433
						"Business Date", "Status", "Description", "Process Amount", "Investment Days"), rows);
434
 
435
		final HttpHeaders headers = new HttpHeaders();
436
		headers.set("Content-Type", "text/csv");
437
		headers.set("Content-disposition", "inline; filename=schemePayout.csv");
438
		headers.setContentLength(baos.toByteArray().length);
439
 
440
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
441
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
442
 
30682 amit.gupta 443
		return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
29608 amit.gupta 444
 
445
	}
446
 
23556 amit.gupta 447
	@RequestMapping(value = "/schemes/update", method = RequestMethod.POST)
23786 amit.gupta 448
	public String updateShcemes(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
449
			throws Exception {
450
		for (int schemeId : schemeItems.getSchemeIds()) {
23928 govind 451
			if (schemeRepository.selectById(schemeId) != null)
30122 amit.gupta 452
				for (int catalogId : schemeItems.getCatalogIds()) {
30151 amit.gupta 453
					if (tagListingRepository.selectAllByCatalogIds(Arrays.asList(catalogId)).size() > 0) {
23928 govind 454
						SchemeItem si = new SchemeItem();
30122 amit.gupta 455
						si.setCatalogId(catalogId);
23928 govind 456
						si.setSchemeId(schemeId);
29608 amit.gupta 457
						si.setCreateTimestamp(LocalDateTime.now());
23928 govind 458
						try {
459
							schemeItemRepository.persist(si);
460
						} catch (Exception e) {
461
							LOGGER.info("Scheme aleady exist");
462
						}
463
						model.addAttribute("response", mvcResponseSender.createResponseString(true));
464
					} else {
465
						model.addAttribute("response", mvcResponseSender.createResponseString(false));
30122 amit.gupta 466
						throw new ProfitMandiBusinessException("Catalog Id ", catalogId, "Invalid Catalog Id");
23928 govind 467
					}
468
				}
469
		}
470
		return "response";
471
	}
25256 amit.gupta 472
 
23928 govind 473
	@RequestMapping(value = "/addItemToScheme", method = RequestMethod.POST)
474
	public String updateScheme(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
475
			throws Exception {
476
		for (int schemeId : schemeItems.getSchemeIds()) {
30122 amit.gupta 477
			List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(schemeId);
23786 amit.gupta 478
			if (schemeRepository.selectById(schemeId) != null)
30122 amit.gupta 479
				for (int catalogId : schemeItems.getCatalogIds()) {
480
					if (!(catalogIds.contains(catalogId))) {
23786 amit.gupta 481
						SchemeItem si = new SchemeItem();
30122 amit.gupta 482
						si.setCatalogId(catalogId);
23786 amit.gupta 483
						si.setSchemeId(schemeId);
29608 amit.gupta 484
						si.setCreateTimestamp(LocalDateTime.now());
23786 amit.gupta 485
						try {
486
							schemeItemRepository.persist(si);
487
						} catch (Exception e) {
23914 govind 488
							LOGGER.info("Scheme already exist");
23786 amit.gupta 489
						}
490
						model.addAttribute("response", mvcResponseSender.createResponseString(true));
491
					} else {
30564 tejbeer 492
						throw new ProfitMandiBusinessException("Catalog exist for scheme",
493
								"SchemeId= " + schemeId + ", CatalogId= " + catalogId, "Catalog exist for scheme");
23556 amit.gupta 494
					}
495
				}
496
		}
497
		return "response";
498
	}
23914 govind 499
 
500
	@RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
501
	public String deleteShcemes(HttpServletRequest request,
30651 amit.gupta 502
								@RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
503
								@RequestParam(name = "catalogId", required = false, defaultValue = "0") int catalogId, Model model)
23819 govind 504
			throws Exception {
23914 govind 505
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30122 amit.gupta 506
		if (schemeId > 0 && catalogId > 0) {
507
			schemeItemRepository.deleteByCatalogIdsAndSchemeIds(catalogId, schemeId);
23914 govind 508
 
509
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
510
 
511
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
512
 
513
		}
514
		return "response";
515
	}
516
 
517
	@RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
518
	public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
519
			throws Exception {
520
		List<Scheme> schemes = schemeRepository.selectActiveAll();
521
		if (schemes.size() > 0) {
522
			for (Scheme scheme : schemes) {
25261 amit.gupta 523
				if (scheme.getExpireTimestamp() == null) {
23914 govind 524
					scheme.setEndDateTime(extendDatetime);
525
					schemeRepository.persist(scheme);
23819 govind 526
				}
527
			}
23914 govind 528
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
529
			return "response";
23819 govind 530
		}
23914 govind 531
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
23819 govind 532
		return "response";
533
	}
23786 amit.gupta 534
 
23914 govind 535
	@RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
536
	public String extendSchemeById(HttpServletRequest request,
23819 govind 537
 
30651 amit.gupta 538
								   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
539
								   @RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
23914 govind 540
		Scheme scheme = schemeRepository.selectById(schemeId);
541
		if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
542
			scheme.setEndDateTime(extendDatetime);
543
			schemeRepository.persist(scheme);
544
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
545
			return "response";
546
		}
547
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
548
		return "response";
549
	}
550
 
22860 ashik.ali 551
	@RequestMapping(value = "/createScheme", method = RequestMethod.POST)
30564 tejbeer 552
	public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
30651 amit.gupta 553
							   Model model) throws ProfitMandiBusinessException {
22927 ashik.ali 554
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 555
		LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
22927 ashik.ali 556
		schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
30122 amit.gupta 557
		return getDefaultSchemes(request, model);
558
	}
29899 tejbeer 559
 
30122 amit.gupta 560
	private String getDefaultSchemes(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
561
		return getSchemes(request, 0, null, 30, 0, 0, PartnerType.ALL, "", model);
562
	}
563
 
564
	private List<Scheme> setSchemeAmountModel(List<Scheme> schemes) {
565
		for (Scheme scheme : schemes) {
566
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
567
				scheme.setAmountModel(scheme.getAmount() + "%");
568
			} else {
569
				scheme.setAmountModel(scheme.getAmount() + "");
29899 tejbeer 570
			}
571
		}
30122 amit.gupta 572
		return schemes;
22860 ashik.ali 573
	}
23786 amit.gupta 574
 
30564 tejbeer 575
	// Show 20 recents
22860 ashik.ali 576
	@RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
23715 govind 577
	public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
30651 amit.gupta 578
							 @RequestParam(required = false) LocalDate date,
579
							 @RequestParam(name = "limit", required = false, defaultValue = "30") int limit,
580
							 @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel,
581
							 @RequestParam(name = "searchScheme", required = false, defaultValue = "0") int searchScheme,
582
							 @RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
583
							 @RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
28795 tejbeer 584
			throws ProfitMandiBusinessException {
23343 ashik.ali 585
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 586
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
30122 amit.gupta 587
		if (date != null) {
588
			date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
30274 amit.gupta 589
		} else if (!isAdmin) {
590
			date = LocalDate.now();
27876 amit.gupta 591
		}
26802 tejbeer 592
 
23343 ashik.ali 593
		List<Scheme> schemes = null;
30655 amit.gupta 594
		List<SchemeInOut> schemeInOuts = null;
28796 tejbeer 595
 
30122 amit.gupta 596
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
29608 amit.gupta 597
 
30122 amit.gupta 598
		model.addAttribute("fullAccess", fullAccess);
599
		model.addAttribute("searchImei", searchImei);
600
		model.addAttribute("isAdmin", isAdmin);
601
		model.addAttribute("searchModel", searchModel);
602
		model.addAttribute("searchScheme", searchScheme);
603
		model.addAttribute("partnerType", partnerType);
604
		model.addAttribute("date", date);
29608 amit.gupta 605
 
30122 amit.gupta 606
		final LocalDate date1 = date;
607
		if (searchScheme > 0) {
608
			schemes = Arrays.asList(schemeRepository.selectById(searchScheme));
609
			this.setSchemeAmountModel(schemes);
27876 amit.gupta 610
			if (schemes.size() > 0) {
26802 tejbeer 611
				model.addAttribute("schemes", schemes);
30122 amit.gupta 612
				return "schemes";
30043 amit.gupta 613
			} else {
30122 amit.gupta 614
				throw new ProfitMandiBusinessException("SchemeId", searchScheme, "SchemeId Not Found");
26802 tejbeer 615
			}
30122 amit.gupta 616
		} else if (searchModel > 0) {
617
			Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
30253 amit.gupta 618
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
28134 tejbeer 619
			if (tagListing != null) {
620
				model.addAttribute("dp", tagListing.getSellingPrice());
621
				model.addAttribute("mop", tagListing.getMop());
26802 tejbeer 622
			}
30253 amit.gupta 623
			model.addAttribute("modelName", item.getItemDescriptionNoColor());
624
			if (isAdmin) {
30564 tejbeer 625
				schemes = schemeService
626
						.selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
627
						.filter(x -> x.getId() != 411 && x.getId() != 612).collect(Collectors.toList());
30253 amit.gupta 628
				// Remove 411 and 612
629
				this.setSchemeAmountModel(schemes);
630
				model.addAttribute("schemes", schemes);
631
				// For 7720(HR) remove investment
30564 tejbeer 632
				// int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing,
633
				// searchModel);
634
				// model.addAttribute("nlc", Math.round(nlc));
30253 amit.gupta 635
				return "schemes";
636
			} else {
637
				partnerType = partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), date);
30564 tejbeer 638
				schemes = schemeService
639
						.selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
640
						.filter(x -> {
30253 amit.gupta 641
							return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
642
						}).collect(Collectors.toList());
643
				// Remove 411 and 612
30564 tejbeer 644
				// this.setSchemeAmountModel(schemes);
30253 amit.gupta 645
				int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing);
646
				// For 7720(HR) remove investment
647
				model.addAttribute("schemes", schemes);
648
				model.addAttribute("nlc", Math.round(nlc));
30274 amit.gupta 649
 
650
				Map<Integer, Map<Integer, Long>> offerSlabPayoutMap = new HashMap<>();
30564 tejbeer 651
				List<CreateOfferRequest> offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(),
652
						searchModel);
30274 amit.gupta 653
				if (offers.size() > 0) {
654
					for (CreateOfferRequest createOfferRequest : offers) {
655
						Map<Integer, Map<Integer, Long>> catalogSlabPayoutMap = offerService
656
								.getSlabPayoutMap(createOfferRequest);
657
						Map<Integer, Long> slabPayoutMap = catalogSlabPayoutMap.get(searchModel);
658
						offerSlabPayoutMap.put(createOfferRequest.getId(), slabPayoutMap);
659
					}
660
					model.addAttribute("offers", offers);
661
					model.addAttribute("offerSlabPayoutMap", offerSlabPayoutMap);
662
 
663
					LOGGER.info("offer");
664
				}
665
				FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
666
				model.addAttribute("partnerCode", fs.getCode());
667
				model.addAttribute("fofoId", fs.getId());
668
 
30253 amit.gupta 669
				return "schemes-partner";
28795 tejbeer 670
 
30253 amit.gupta 671
			}
672
 
30122 amit.gupta 673
		} else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
674
 
28795 tejbeer 675
			LOGGER.info("searchImei" + searchImei);
676
 
30651 amit.gupta 677
			InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
678
					loginDetails.getFofoId());
28802 tejbeer 679
			Item item = itemRepository.selectById(inventoryItem.getItemId());
28795 tejbeer 680
			Map<Integer, Scheme> schemeMap = new HashMap<>();
30651 amit.gupta 681
			double netEarnings = 0;
28795 tejbeer 682
			if (inventoryItem != null) {
30651 amit.gupta 683
				//Offer payout
684
				List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(), searchImei);
685
				Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream().map(x -> offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId())).collect(Collectors.toMap(x -> x.getId(), x -> x));
28795 tejbeer 686
 
687
 
30655 amit.gupta 688
				schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
28795 tejbeer 689
 
30655 amit.gupta 690
				if (!schemeInOuts.isEmpty()) {
691
					netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED)).collect(Collectors.summingDouble(x -> x.getAmount()));
692
					List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
28795 tejbeer 693
 
694
					schemes = schemeRepository.selectBySchemeIds(schemeIds);
695
					for (Scheme scheme : schemes) {
696
						if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
697
							scheme.setAmountModel(scheme.getAmount() + "%");
698
						} else {
699
							scheme.setAmountModel(scheme.getAmount() + "");
700
						}
701
					}
702
 
703
					schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
704
				}
30651 amit.gupta 705
				List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
706
						.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
707
				if (priceDropImeis.size() > 0) {
708
 
709
					for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
710
						int priceDropId = priceDropIMEI.getPriceDropId();
711
						PriceDrop pd = priceDropRepository.selectById(priceDropId);
712
						priceDropIMEI.setPriceDrop(pd);
713
					}
714
					model.addAttribute("priceDropImeis", priceDropImeis);
715
				}
30655 amit.gupta 716
				netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
30651 amit.gupta 717
				model.addAttribute("offerPayouts", offerPayouts);
718
				model.addAttribute("offerRequestMap", offerRequestMap);
719
				model.addAttribute("inventoryItem", inventoryItem);
720
				model.addAttribute("inventoryItem", inventoryItem);
721
 
28795 tejbeer 722
			}
30651 amit.gupta 723
			model.addAttribute("netEarnings", netEarnings);
30253 amit.gupta 724
			model.addAttribute("fofoId", loginDetails.getFofoId());
28795 tejbeer 725
			model.addAttribute("schemeMap", schemeMap);
28802 tejbeer 726
			model.addAttribute("item", item);
30655 amit.gupta 727
			model.addAttribute("schemeInOut", schemeInOuts);
30122 amit.gupta 728
			return "schemes-partner";
28796 tejbeer 729
		}
28795 tejbeer 730
 
29899 tejbeer 731
		if (isAdmin) {
30699 amit.gupta 732
			schemes = schemeRepository.selectAll(0, 100);
30122 amit.gupta 733
			this.setSchemeAmountModel(schemes);
734
			model.addAttribute("schemes", schemes);
27876 amit.gupta 735
			return "schemes";
29899 tejbeer 736
		} else {
30122 amit.gupta 737
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
28795 tejbeer 738
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
739
						loginDetails.getFofoId());
30564 tejbeer 740
				List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
741
						.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
30274 amit.gupta 742
				if (priceDropImeis.size() > 0) {
28795 tejbeer 743
 
30274 amit.gupta 744
					for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
745
						int priceDropId = priceDropIMEI.getPriceDropId();
746
						PriceDrop pd = priceDropRepository.selectById(priceDropId);
747
						priceDropIMEI.setPriceDrop(pd);
748
					}
749
					model.addAttribute("priceDropImeis", priceDropImeis);
28795 tejbeer 750
				}
751
			}
28136 tejbeer 752
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
753
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 754
			model.addAttribute("fofoId", fs.getId());
27876 amit.gupta 755
			return "schemes-partner";
756
		}
29899 tejbeer 757
 
22860 ashik.ali 758
	}
23786 amit.gupta 759
 
30253 amit.gupta 760
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing)
28795 tejbeer 761
			throws ProfitMandiBusinessException {
30253 amit.gupta 762
		int itemId = item.getId();
28795 tejbeer 763
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
764
				.filter(x -> x.getId() == fofoId).count() > 0) {
765
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
766
					.collect(Collectors.toList());
767
		}
768
		float nlc = tagListing.getSellingPrice();
769
		for (Scheme scheme : schemes) {
770
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
771
				if (tagListing != null) {
772
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
773
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
774
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
30053 manish 775
					scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
28795 tejbeer 776
					nlc -= amount;
30043 amit.gupta 777
				} else {
28795 tejbeer 778
					scheme.setAmountModel(scheme.getAmount() + "%");
779
				}
780
			} else {
781
				scheme.setAmountModel(scheme.getAmount() + "");
782
				nlc -= scheme.getAmount();
783
			}
784
		}
785
 
786
		return Math.round(nlc);
787
 
788
	}
789
 
30053 manish 790
	@RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
791
	public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
792
 
793
		String status = "CREDITED";
794
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
795
 
796
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
797
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
798
 
799
		YearMonth yearMonth = YearMonth.now();
800
		LOGGER.info("yearMonth" + yearMonth);
801
 
802
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
803
 
804
		LOGGER.info("partnerType" + partnerType);
805
 
806
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
807
 
808
		if (partnerType) {
809
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
810
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
811
							currentDate)
812
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
813
		}
814
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
815
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
816
 
817
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
818
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
819
 
820
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
821
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
822
 
30253 amit.gupta 823
		Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
30564 tejbeer 824
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
825
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30253 amit.gupta 826
 
30053 manish 827
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
828
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
829
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
830
		LOGGER.info("lastMonthCategoryUpgradeMarginMap" + lastMonthCategoryUpgradeMarginMap);
831
 
832
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
833
 
834
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
835
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
836
 
837
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
838
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
839
 
840
		lastMonthFrontEndIncomes.stream().forEach(x -> {
841
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
842
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
843
				lastMonthSaleMarginMap.put(x.getBrand(), x);
844
			} else {
845
				lastMonthSaleMarginMap.put(x.getBrand(), x);
846
			}
847
 
848
		});
849
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
850
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
851
 
852
		Set<String> keySet = new HashSet<String>();
853
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
854
		keySet.addAll(lastMonthSaleMarginMap.keySet());
30235 tejbeer 855
		keySet.addAll(lastMonthPendingIncomeMap.keySet());
30053 manish 856
 
857
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
858
			String brand = x.getKey();
859
			float amount = x.getValue().getAmount();
860
			if (!totalAmountMap.containsKey(brand)) {
861
				totalAmountMap.put(brand, 0f);
862
			}
863
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
864
 
865
		});
30253 amit.gupta 866
 
30235 tejbeer 867
		lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
868
			String brand = x.getKey();
869
			float amount = x.getValue().getAmount();
870
			if (!totalAmountMap.containsKey(brand)) {
871
				totalAmountMap.put(brand, 0f);
872
			}
873
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30053 manish 874
 
30235 tejbeer 875
		});
876
 
30053 manish 877
		Map<Integer, String> monthValueMap = new HashMap<>();
878
		for (int i = 0; i <= 5; i++) {
879
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
880
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
881
		}
882
		model.addAttribute("month", 0);
883
		model.addAttribute("monthValueMap", monthValueMap);
884
		model.addAttribute("keySet", keySet);
30235 tejbeer 885
		model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
30053 manish 886
 
887
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
888
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
889
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
890
		model.addAttribute("status", status);
891
		model.addAttribute("totalAmountMap", totalAmountMap);
892
 
893
		return "last-month-credited-income";
894
	}
895
 
896
	@RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
897
	public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
898
 
899
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
900
 
901
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
902
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
903
		String status = "PENDING";
904
 
905
		LOGGER.info("currentStartMonth" + currentStartMonth);
906
		LOGGER.info("currentDate" + currentDate);
907
 
908
		List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
909
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
910
 
911
		Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
912
 
913
		for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
914
 
915
			lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
916
		}
917
		LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
918
		LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
919
		model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
920
		model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
921
		model.addAttribute("status", status);
922
 
923
		return "last-month-credited-income";
924
	}
925
 
926
	@RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
927
	public String getLastMonthImeiWiseIncome(HttpServletRequest request,
30651 amit.gupta 928
											 @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
929
											 @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 930
			throws Exception {
931
 
932
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
933
 
934
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
30410 amit.gupta 935
		LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 936
 
937
		HashSet<String> allImeiSet = new LinkedHashSet<>();
938
		HashSet<String> purchaseSet = new LinkedHashSet<>();
939
		HashSet<String> saleSet = new LinkedHashSet<>();
940
 
941
		List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
30410 amit.gupta 942
				.selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 943
		List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
30410 amit.gupta 944
				catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 945
		List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
30410 amit.gupta 946
				catalogItemId, lastMonthStart, lastMonthEnd);
30253 amit.gupta 947
 
30235 tejbeer 948
		LOGGER.info("lmci {}", lmci);
30053 manish 949
 
950
		Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
951
				.selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
30410 amit.gupta 952
						lastMonthEnd)
30053 manish 953
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
954
 
955
		allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
956
		allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
957
		allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
958
 
959
		List<String> allImeiList = new ArrayList<>(allImeiSet);
960
 
961
		LOGGER.info("allImeiList" + allImeiList);
962
		LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 963
 
30053 manish 964
		List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
965
				.selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
966
		List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
967
				.selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
968
		List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
969
				.selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
30253 amit.gupta 970
 
30053 manish 971
		LOGGER.info("lastMonthFrontEndImei {}", lastMonthFrontEndImeis);
972
		LOGGER.info("lastMonthPurchaseInImei {}", lastMonthPurchaseInImeis);
973
		LOGGER.info("lastMonthCreditedImei {}", lastMonthCreditedImeis);
30253 amit.gupta 974
 
30580 amit.gupta 975
		Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
30564 tejbeer 976
				.filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING))
30580 amit.gupta 977
				.collect(Collectors.groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30253 amit.gupta 978
 
30053 manish 979
		Map<IncomeImeiDate, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
980
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
981
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
982
 
983
		Map<IncomeImeiDate, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
984
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
985
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
986
		// descriptionSet.add("")
987
		purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
988
		saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
989
 
990
		List<String> purchaseList = new ArrayList<>(purchaseSet);
991
		List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 992
 
30053 manish 993
		Map<IncomeImeiDate, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30253 amit.gupta 994
 
30053 manish 995
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
996
 
997
			IncomeImeiDate imeiDate = entry.getKey();
998
			Map<String, Double> descriptionAmountMap = entry.getValue();
999
 
1000
			ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(),
1001
					imeiDate.getLocalDateTime(), null, descriptionAmountMap);
1002
			imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1003
			double totalAmount = imeiWiseIncomeMapOfMap.get(imeiDate).getDescriptionAmountMap().entrySet().stream()
1004
					.collect(Collectors.summingDouble(x -> x.getValue()));
1005
			imeiWiseIncomeMapOfMap.get(imeiDate).setTotalIncome(totalAmount);
1006
		}
1007
 
1008
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1009
			IncomeImeiDate imeiDate = entry.getKey();
1010
			Map<String, Double> descriptionAmountMap = entry.getValue();
1011
			if (!imeiWiseIncomeMapOfMap.containsKey(imeiDate)) {
1012
				ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(), null,
1013
						imeiDate.getLocalDateTime(), descriptionAmountMap);
1014
				imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1015
 
1016
			} else {
1017
				ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(imeiDate);
1018
				modelImeiMap.setSaleDate(imeiDate.getLocalDateTime());
1019
				modelImeiMap.getDescriptionAmountMap().putAll(descriptionAmountMap);
1020
 
1021
			}
1022
			double totalAmount = descriptionAmountMap.entrySet().stream()
1023
					.collect(Collectors.summingDouble(x -> x.getValue()));
1024
			imeiWiseIncomeMapOfMap.get(imeiDate)
1025
					.setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(imeiDate).getTotalIncome());
1026
		}
1027
 
1028
		lastMonthFrontEndImeis.stream().forEach(x -> {
1029
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), null);
1030
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1031
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1032
						.get(incomeImeiDate);
1033
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount();
1034
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1035
				imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
1036
			}
1037
		});
1038
 
30235 tejbeer 1039
		lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1040
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp());
1041
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1042
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1043
						.get(incomeImeiDate);
1044
 
1045
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getPendingSaleAmount();
1046
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1047
 
1048
			} else {
1049
 
1050
				ImeiWiseIncomePairAndMapModel newObjectImeiWiseIncomePairAndMapModel = new ImeiWiseIncomePairAndMapModel();
1051
 
1052
				newObjectImeiWiseIncomePairAndMapModel.setSerialNumber(x.getImei());
1053
				newObjectImeiWiseIncomePairAndMapModel.setPurchseDate(x.getCreateTimeStamp());
1054
				newObjectImeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount());
1055
			}
1056
 
1057
		});
1058
 
1059
		model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
30053 manish 1060
		model.addAttribute("month", month);
1061
		model.addAttribute("purchaseList", purchaseList);
1062
		model.addAttribute("saleList", saleList);
1063
		model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1064
		model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1065
		model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1066
		model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
1067
 
1068
		LOGGER.info("lastMonthPurchaseInMapPairMap {}", lastMonthPurchaseInMapPairMap);
1069
		LOGGER.info("lastMonthCreditedMapPairMap {}", lastMonthCreditedMapPairMap);
1070
		LOGGER.info("imeiWiseIncomeMapOfMap {}", imeiWiseIncomeMapOfMap);
1071
 
1072
		return "last-month-imei-wise-income";
1073
	}
1074
 
1075
	@RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1076
	public String getBrandWiseIncome(HttpServletRequest request,
30651 amit.gupta 1077
									 @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1078
									 @RequestParam(name = "status", required = false, defaultValue = "") String status,
1079
									 @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 1080
			throws ProfitMandiBusinessException {
1081
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1082
		LOGGER.info("loginDetails {}", loginDetails);
1083
		LOGGER.info("brand" + brand);
1084
		LOGGER.info("month {}", month);
1085
 
30410 amit.gupta 1086
		LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1087
		LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1088
 
30564 tejbeer 1089
		boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1090
				YearMonth.now());
30053 manish 1091
 
30410 amit.gupta 1092
		LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1093
 
30414 amit.gupta 1094
		Map<String, Double> categoryUpgradeBrandModelMap = null;
30410 amit.gupta 1095
		if (partnerTypeUpgraded) {
30414 amit.gupta 1096
			categoryUpgradeBrandModelMap = schemeInOutRepository
30410 amit.gupta 1097
					.selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1098
							monthEnd)
30053 manish 1099
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1100
		}
1101
 
30564 tejbeer 1102
		List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1103
				.selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
30053 manish 1104
 
30564 tejbeer 1105
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1106
				.selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1107
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1108
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1109
 
30564 tejbeer 1110
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1111
				.selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1112
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1113
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1114
 
30410 amit.gupta 1115
		Map<Integer, Double> modelTotalIncomeMap = new HashMap<>();
1116
		Map<Integer, String> modelNameMap = new HashMap<>();
30253 amit.gupta 1117
 
30410 amit.gupta 1118
		modelWiseSchemeOutMargins.stream().forEach(x -> {
30414 amit.gupta 1119
			modelTotalIncomeMap.put(x.getCatalogItemId(), x.getAmount() + x.getPendingSaleAmount());
1120
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + " " + x.getModelName()).trim());
30253 amit.gupta 1121
 
30410 amit.gupta 1122
		});
30414 amit.gupta 1123
		LastMonthBrandWiseIncomeModel totalModel = new LastMonthBrandWiseIncomeModel();
30410 amit.gupta 1124
		modelWiseSalesMargins.stream().forEach(x -> {
30413 amit.gupta 1125
			if (!modelWiseSchemeOutMarginsMap.containsKey(x.getCatalogItemId())) {
30410 amit.gupta 1126
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1127
				LastMonthBrandWiseIncomeModel lmbwIncomeModel = new LastMonthBrandWiseIncomeModel();
1128
				lmbwIncomeModel.setAmount(x.getAmount());
1129
				lmbwIncomeModel.setModelName(x.getModelName());
1130
				lmbwIncomeModel.setModelNumber(x.getModelNumber());
1131
				lmbwIncomeModel.setBrand(x.getBrand());
1132
				lmbwIncomeModel.setCatalogItemId(x.getCatalogItemId());
1133
				lmbwIncomeModel.setPendingSaleAmount(x.getPendingSaleAmount());
1134
				lmbwIncomeModel.setQty(x.getQty());
1135
				lmbwIncomeModel.setStatus(SchemePayoutStatus.CREDITED);
30410 amit.gupta 1136
				modelWiseSchemeOutMarginsMap.put(x.getCatalogItemId(), lmbwIncomeModel);
1137
 
30235 tejbeer 1138
			}
30410 amit.gupta 1139
			LastMonthBrandWiseIncomeModel lmbwIncomeModel = modelWiseSchemeOutMarginsMap.get(x.getCatalogItemId());
1140
			lmbwIncomeModel.setQty(x.getQty());
1141
			lmbwIncomeModel.setAmount(lmbwIncomeModel.getAmount() + x.getAmount());
30564 tejbeer 1142
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1143
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1144
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1145
			totalModel.setQty(totalModel.getQty() + x.getQty());
1146
			totalModel.setAmount(totalModel.getAmount() + lmbwIncomeModel.getAmount());
1147
			totalModel.setPendingSaleAmount(totalModel.getPendingSaleAmount());
30253 amit.gupta 1148
 
1149
		});
30410 amit.gupta 1150
		modelWiseSchemeInMargins.stream().forEach(x -> {
1151
			if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1152
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1153
			}
30564 tejbeer 1154
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1155
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1156
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1157
			totalModel.setQty(totalModel.getQty() + x.getQty());
1158
			totalModel.setAmount(totalModel.getAmount() + x.getAmount());
30053 manish 1159
 
30235 tejbeer 1160
		});
30053 manish 1161
 
30410 amit.gupta 1162
		model.addAttribute("month", month);
1163
		model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1164
		model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1165
		model.addAttribute("modelNameMap", modelNameMap);
1166
		model.addAttribute("modelTotalIncomeMap", modelTotalIncomeMap);
30414 amit.gupta 1167
		model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1168
		model.addAttribute("totalModel", totalModel);
30053 manish 1169
 
1170
		return "montly-brand-wise-income";
1171
 
1172
	}
1173
 
1174
	@RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1175
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1176
			throws ProfitMandiBusinessException {
1177
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1178
 
1179
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1180
		LocalDateTime currentMonthEnd = lastMonthStart.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
1181
 
1182
		YearMonth monthYear = YearMonth.now();
1183
 
1184
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
1185
 
1186
		LOGGER.info("partnerType" + partnerType);
1187
 
1188
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
1189
 
1190
		if (partnerType) {
1191
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1192
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), lastMonthStart,
1193
							currentMonthEnd)
1194
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1195
		}
1196
 
1197
		String status = "CREDITED";
1198
		LOGGER.info("lastMonthStart" + lastMonthStart);
1199
		LOGGER.info("currentMonthEnd" + currentMonthEnd);
1200
 
1201
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1202
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1203
 
1204
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1205
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1206
 
1207
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1208
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1209
 
1210
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
1211
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
1212
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
1213
 
1214
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
1215
 
1216
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1217
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1218
 
1219
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1220
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1221
 
1222
		lastMonthFrontEndIncomes.stream().forEach(x -> {
1223
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1224
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1225
 
1226
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1227
			} else {
1228
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1229
			}
1230
 
1231
		});
1232
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1233
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1234
		Set<String> keySet = new HashSet<String>();
1235
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1236
		keySet.addAll(lastMonthSaleMarginMap.keySet());
1237
 
1238
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1239
			String brand = x.getKey();
1240
			float amount = x.getValue().getAmount();
1241
			if (!totalAmountMap.containsKey(brand)) {
1242
				totalAmountMap.put(brand, 0f);
1243
			}
1244
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
1245
 
1246
		});
1247
 
1248
		Map<Integer, String> monthValueMap = new HashMap<>();
1249
		for (int i = 0; i <= 5; i++) {
1250
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1251
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1252
		}
1253
		model.addAttribute("monthValueMap", monthValueMap);
1254
 
1255
		model.addAttribute("keySet", keySet);
1256
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1257
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1258
 
1259
		model.addAttribute("totalAmountMap", totalAmountMap);
1260
		model.addAttribute("status", status);
1261
		model.addAttribute("month", yearMonth);
1262
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1263
		LOGGER.info("totalAmountMap {}", totalAmountMap);
1264
		LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
1265
 
1266
		return "last-month-credited-income";
1267
	}
1268
 
23020 ashik.ali 1269
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 1270
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 1271
		return "schemes-download";
1272
	}
23786 amit.gupta 1273
 
23020 ashik.ali 1274
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 1275
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
30651 amit.gupta 1276
																  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
23786 amit.gupta 1277
			throws ProfitMandiBusinessException {
23914 govind 1278
 
23020 ashik.ali 1279
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 1280
 
23020 ashik.ali 1281
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1282
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 1283
 
1284
		final HttpHeaders headers = new HttpHeaders();
1285
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 1286
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 1287
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1288
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1289
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1290
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 1291
	}
23786 amit.gupta 1292
 
22860 ashik.ali 1293
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 1294
	public String getSchemeById(HttpServletRequest request,
30651 amit.gupta 1295
								@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
23786 amit.gupta 1296
			throws ProfitMandiBusinessException {
23343 ashik.ali 1297
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29899 tejbeer 1298
 
1299
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
22860 ashik.ali 1300
		Scheme scheme = schemeService.getSchemeById(schemeId);
29899 tejbeer 1301
		model.addAttribute("fullAccess", fullAccess);
22860 ashik.ali 1302
		model.addAttribute("scheme", scheme);
24445 amit.gupta 1303
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 1304
		return "scheme-details";
1305
	}
23786 amit.gupta 1306
 
22860 ashik.ali 1307
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1308
	public String activeSchemeById(HttpServletRequest request,
30651 amit.gupta 1309
								   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1310
								   @RequestParam(name = "offset", defaultValue = "0") int offset,
1311
								   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1312
			throws ProfitMandiBusinessException {
22860 ashik.ali 1313
		schemeService.activeSchemeById(schemeId);
1314
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
30064 amit.gupta 1315
		for (Scheme scheme : schemes) {
1316
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1317
				scheme.setAmountModel(scheme.getAmount() + "%");
1318
			} else {
1319
				scheme.setAmountModel(scheme.getAmount() + "");
1320
			}
1321
		}
30122 amit.gupta 1322
		return "schemes";
22860 ashik.ali 1323
	}
23786 amit.gupta 1324
 
22860 ashik.ali 1325
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1326
	public String expireSchemeById(HttpServletRequest request,
30651 amit.gupta 1327
								   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1328
								   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
23786 amit.gupta 1329
			throws ProfitMandiBusinessException {
25069 amit.gupta 1330
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
30122 amit.gupta 1331
		return getDefaultSchemes(request, model);
22860 ashik.ali 1332
	}
23786 amit.gupta 1333
 
23784 ashik.ali 1334
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 1335
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
30651 amit.gupta 1336
											@RequestParam(name = "offset", defaultValue = "0") int offset,
1337
											@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1338
			throws ProfitMandiBusinessException {
23784 ashik.ali 1339
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1340
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1341
	}
26802 tejbeer 1342
 
29707 tejbeer 1343
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1344
	public String getCustomerOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1345
 
1346
		List<CustomerOffer> customerOffers = customerOfferRepository.selectAll();
1347
 
1348
		model.addAttribute("customerOffers", customerOffers);
1349
		return "customer-offer";
1350
 
1351
	}
1352
 
1353
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1354
	public String createCustomerOffer(HttpServletRequest request, @RequestParam String offerName,
30651 amit.gupta 1355
									  @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model) throws Exception {
29707 tejbeer 1356
 
1357
		CustomerOffer co = new CustomerOffer();
1358
		co.setOfferName(offerName);
1359
		co.setStartDate(startDate);
1360
		co.setEndDate(endDate);
1361
		co.setCreatedTimestamp(LocalDateTime.now());
1362
		co.setUpdatedTimestamp(LocalDateTime.now());
1363
		customerOfferRepository.persist(co);
1364
 
1365
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1366
 
1367
		return "response";
1368
 
1369
	}
1370
 
1371
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1372
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1373
		List<List<?>> rows = new ArrayList<>();
1374
 
1375
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1376
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1377
 
1378
		final HttpHeaders headers = new HttpHeaders();
1379
		headers.set("Content-Type", "text/csv");
1380
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1381
		headers.setContentLength(baos.toByteArray().length);
1382
 
1383
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1384
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1385
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1386
 
1387
	}
1388
 
1389
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1390
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
30651 amit.gupta 1391
										  HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
29707 tejbeer 1392
 
1393
		List<CSVRecord> records = FileUtil.readFile(file);
1394
 
1395
		for (CSVRecord record : records) {
1396
			if (Integer.parseInt(record.get(0)) == 0) {
1397
				CustomerOfferItem coi = new CustomerOfferItem();
1398
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1399
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1400
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1401
				coi.setCustomerOfferId(offerId);
1402
				coi.setUpdatedTimestamp(LocalDateTime.now());
1403
				coi.setCreatedTimestamp(LocalDateTime.now());
1404
				customerOfferItemRepository.persist(coi);
1405
 
1406
			} else {
1407
				CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1408
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1409
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1410
				coi.setUpdatedTimestamp(LocalDateTime.now());
1411
			}
1412
 
1413
		}
1414
 
1415
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1416
 
1417
		return "response";
1418
 
1419
	}
1420
 
1421
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1422
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1423
 
1424
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1425
		List<List<?>> rows = new ArrayList<>();
1426
 
1427
		for (CustomerOfferItem coi : cois) {
1428
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout()));
1429
 
1430
		}
1431
 
1432
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1433
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1434
 
1435
		final HttpHeaders headers = new HttpHeaders();
1436
		headers.set("Content-Type", "text/csv");
1437
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1438
		headers.setContentLength(baos.toByteArray().length);
1439
 
1440
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1441
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1442
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1443
 
1444
	}
1445
 
1446
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1447
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
30651 amit.gupta 1448
									  @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
29707 tejbeer 1449
 
1450
		CustomerOffer co = customerOfferRepository.selectById(id);
1451
		co.setEndDate(endDate);
1452
		co.setUpdatedTimestamp(LocalDateTime.now());
1453
 
1454
		model.addAttribute("co", co);
1455
 
1456
		return "customer-index-offer";
1457
 
1458
	}
1459
 
1460
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1461
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1462
 
1463
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1464
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1465
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1466
 
1467
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1468
		return "samsung-upgrade-offer";
1469
 
1470
	}
1471
 
1472
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1473
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1474
			throws ProfitMandiBusinessException {
1475
 
1476
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1477
		suo.setStatus(UpgradeOfferStatus.approved);
1478
		suo.setApprovedTimestamp(LocalDateTime.now());
1479
		model.addAttribute("suo", suo);
1480
		return "samsung-upgrade-offer-index";
1481
 
1482
	}
1483
 
1484
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1485
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1486
			throws ProfitMandiBusinessException {
1487
 
1488
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1489
		suo.setStatus(UpgradeOfferStatus.rejected);
1490
 
1491
		model.addAttribute("suo", suo);
1492
		return "samsung-upgrade-offer-index";
1493
 
1494
	}
30410 amit.gupta 1495
 
22860 ashik.ali 1496
}