Subversion Repositories SmartDukaan

Rev

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