Subversion Repositories SmartDukaan

Rev

Rev 30831 | Rev 31147 | 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
 
30966 amit.gupta 769
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
28795 tejbeer 770
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
771
				.filter(x -> x.getId() == fofoId).count() > 0) {
772
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
773
					.collect(Collectors.toList());
774
		}
775
		float nlc = tagListing.getSellingPrice();
776
		for (Scheme scheme : schemes) {
777
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
778
				if (tagListing != null) {
30966 amit.gupta 779
					float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
30053 manish 780
					scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
28795 tejbeer 781
					nlc -= amount;
30043 amit.gupta 782
				} else {
28795 tejbeer 783
					scheme.setAmountModel(scheme.getAmount() + "%");
784
				}
785
			} else {
786
				scheme.setAmountModel(scheme.getAmount() + "");
787
				nlc -= scheme.getAmount();
788
			}
789
		}
790
 
791
		return Math.round(nlc);
792
 
793
	}
794
 
30053 manish 795
	@RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
796
	public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
797
 
798
		String status = "CREDITED";
799
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
800
 
801
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
802
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
803
 
804
		YearMonth yearMonth = YearMonth.now();
805
		LOGGER.info("yearMonth" + yearMonth);
806
 
807
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
808
 
809
		LOGGER.info("partnerType" + partnerType);
810
 
811
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
812
 
813
		if (partnerType) {
814
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
815
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
816
							currentDate)
817
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
818
		}
819
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
820
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
821
 
822
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
823
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
824
 
825
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
826
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
827
 
30253 amit.gupta 828
		Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
30564 tejbeer 829
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
830
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30253 amit.gupta 831
 
30053 manish 832
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
833
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
834
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
835
		LOGGER.info("lastMonthCategoryUpgradeMarginMap" + lastMonthCategoryUpgradeMarginMap);
836
 
837
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
838
 
839
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
840
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
841
 
842
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
843
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
844
 
845
		lastMonthFrontEndIncomes.stream().forEach(x -> {
846
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
847
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
848
				lastMonthSaleMarginMap.put(x.getBrand(), x);
849
			} else {
850
				lastMonthSaleMarginMap.put(x.getBrand(), x);
851
			}
852
 
853
		});
854
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
855
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
856
 
857
		Set<String> keySet = new HashSet<String>();
858
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
859
		keySet.addAll(lastMonthSaleMarginMap.keySet());
30235 tejbeer 860
		keySet.addAll(lastMonthPendingIncomeMap.keySet());
30053 manish 861
 
862
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
863
			String brand = x.getKey();
864
			float amount = x.getValue().getAmount();
865
			if (!totalAmountMap.containsKey(brand)) {
866
				totalAmountMap.put(brand, 0f);
867
			}
868
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
869
 
870
		});
30253 amit.gupta 871
 
30235 tejbeer 872
		lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
873
			String brand = x.getKey();
874
			float amount = x.getValue().getAmount();
875
			if (!totalAmountMap.containsKey(brand)) {
876
				totalAmountMap.put(brand, 0f);
877
			}
878
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30053 manish 879
 
30235 tejbeer 880
		});
881
 
30053 manish 882
		Map<Integer, String> monthValueMap = new HashMap<>();
883
		for (int i = 0; i <= 5; i++) {
884
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
885
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
886
		}
887
		model.addAttribute("month", 0);
888
		model.addAttribute("monthValueMap", monthValueMap);
889
		model.addAttribute("keySet", keySet);
30235 tejbeer 890
		model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
30053 manish 891
 
892
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
893
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
894
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
895
		model.addAttribute("status", status);
896
		model.addAttribute("totalAmountMap", totalAmountMap);
897
 
898
		return "last-month-credited-income";
899
	}
900
 
901
	@RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
902
	public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
903
 
904
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
905
 
906
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
907
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
908
		String status = "PENDING";
909
 
910
		LOGGER.info("currentStartMonth" + currentStartMonth);
911
		LOGGER.info("currentDate" + currentDate);
912
 
913
		List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
914
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
915
 
916
		Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
917
 
918
		for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
919
 
920
			lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
921
		}
922
		LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
923
		LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
924
		model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
925
		model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
926
		model.addAttribute("status", status);
927
 
928
		return "last-month-credited-income";
929
	}
930
 
931
	@RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
932
	public String getLastMonthImeiWiseIncome(HttpServletRequest request,
30831 tejbeer 933
			@RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
934
			@RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 935
			throws Exception {
936
 
937
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
938
 
939
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
30410 amit.gupta 940
		LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 941
 
942
		HashSet<String> allImeiSet = new LinkedHashSet<>();
943
		HashSet<String> purchaseSet = new LinkedHashSet<>();
944
		HashSet<String> saleSet = new LinkedHashSet<>();
945
 
946
		List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
30410 amit.gupta 947
				.selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 948
		List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
30410 amit.gupta 949
				catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 950
		List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
30410 amit.gupta 951
				catalogItemId, lastMonthStart, lastMonthEnd);
30253 amit.gupta 952
 
30235 tejbeer 953
		LOGGER.info("lmci {}", lmci);
30053 manish 954
 
955
		Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
956
				.selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
30410 amit.gupta 957
						lastMonthEnd)
30053 manish 958
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
959
 
960
		allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
961
		allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
962
		allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
963
 
964
		List<String> allImeiList = new ArrayList<>(allImeiSet);
965
 
966
		LOGGER.info("allImeiList" + allImeiList);
967
		LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 968
 
30053 manish 969
		List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
970
				.selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
971
		List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
972
				.selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
973
		List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
974
				.selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
30253 amit.gupta 975
 
30053 manish 976
		LOGGER.info("lastMonthFrontEndImei {}", lastMonthFrontEndImeis);
977
		LOGGER.info("lastMonthPurchaseInImei {}", lastMonthPurchaseInImeis);
978
		LOGGER.info("lastMonthCreditedImei {}", lastMonthCreditedImeis);
30253 amit.gupta 979
 
30580 amit.gupta 980
		Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
30831 tejbeer 981
				.filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
982
						.groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30253 amit.gupta 983
 
30053 manish 984
		Map<IncomeImeiDate, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
985
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
986
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
987
 
988
		Map<IncomeImeiDate, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
989
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
990
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
991
		// descriptionSet.add("")
992
		purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
993
		saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
994
 
995
		List<String> purchaseList = new ArrayList<>(purchaseSet);
996
		List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 997
 
30053 manish 998
		Map<IncomeImeiDate, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30253 amit.gupta 999
 
30053 manish 1000
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
1001
 
1002
			IncomeImeiDate imeiDate = entry.getKey();
1003
			Map<String, Double> descriptionAmountMap = entry.getValue();
1004
 
1005
			ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(),
1006
					imeiDate.getLocalDateTime(), null, descriptionAmountMap);
1007
			imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1008
			double totalAmount = imeiWiseIncomeMapOfMap.get(imeiDate).getDescriptionAmountMap().entrySet().stream()
1009
					.collect(Collectors.summingDouble(x -> x.getValue()));
1010
			imeiWiseIncomeMapOfMap.get(imeiDate).setTotalIncome(totalAmount);
1011
		}
1012
 
1013
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1014
			IncomeImeiDate imeiDate = entry.getKey();
1015
			Map<String, Double> descriptionAmountMap = entry.getValue();
1016
			if (!imeiWiseIncomeMapOfMap.containsKey(imeiDate)) {
1017
				ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(), null,
1018
						imeiDate.getLocalDateTime(), descriptionAmountMap);
1019
				imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1020
 
1021
			} else {
1022
				ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(imeiDate);
1023
				modelImeiMap.setSaleDate(imeiDate.getLocalDateTime());
1024
				modelImeiMap.getDescriptionAmountMap().putAll(descriptionAmountMap);
1025
 
1026
			}
1027
			double totalAmount = descriptionAmountMap.entrySet().stream()
1028
					.collect(Collectors.summingDouble(x -> x.getValue()));
1029
			imeiWiseIncomeMapOfMap.get(imeiDate)
1030
					.setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(imeiDate).getTotalIncome());
1031
		}
1032
 
1033
		lastMonthFrontEndImeis.stream().forEach(x -> {
1034
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), null);
1035
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1036
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1037
						.get(incomeImeiDate);
1038
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount();
1039
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1040
				imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
1041
			}
1042
		});
1043
 
30235 tejbeer 1044
		lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1045
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp());
1046
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1047
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1048
						.get(incomeImeiDate);
1049
 
1050
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getPendingSaleAmount();
1051
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1052
 
1053
			} else {
1054
 
1055
				ImeiWiseIncomePairAndMapModel newObjectImeiWiseIncomePairAndMapModel = new ImeiWiseIncomePairAndMapModel();
1056
 
1057
				newObjectImeiWiseIncomePairAndMapModel.setSerialNumber(x.getImei());
1058
				newObjectImeiWiseIncomePairAndMapModel.setPurchseDate(x.getCreateTimeStamp());
1059
				newObjectImeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount());
1060
			}
1061
 
1062
		});
1063
 
1064
		model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
30053 manish 1065
		model.addAttribute("month", month);
1066
		model.addAttribute("purchaseList", purchaseList);
1067
		model.addAttribute("saleList", saleList);
1068
		model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1069
		model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1070
		model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1071
		model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
1072
 
1073
		LOGGER.info("lastMonthPurchaseInMapPairMap {}", lastMonthPurchaseInMapPairMap);
1074
		LOGGER.info("lastMonthCreditedMapPairMap {}", lastMonthCreditedMapPairMap);
1075
		LOGGER.info("imeiWiseIncomeMapOfMap {}", imeiWiseIncomeMapOfMap);
1076
 
1077
		return "last-month-imei-wise-income";
1078
	}
1079
 
1080
	@RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1081
	public String getBrandWiseIncome(HttpServletRequest request,
30831 tejbeer 1082
			@RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1083
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
1084
			@RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 1085
			throws ProfitMandiBusinessException {
1086
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1087
		LOGGER.info("loginDetails {}", loginDetails);
1088
		LOGGER.info("brand" + brand);
1089
		LOGGER.info("month {}", month);
1090
 
30410 amit.gupta 1091
		LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1092
		LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1093
 
30564 tejbeer 1094
		boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1095
				YearMonth.now());
30053 manish 1096
 
30410 amit.gupta 1097
		LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1098
 
30414 amit.gupta 1099
		Map<String, Double> categoryUpgradeBrandModelMap = null;
30410 amit.gupta 1100
		if (partnerTypeUpgraded) {
30414 amit.gupta 1101
			categoryUpgradeBrandModelMap = schemeInOutRepository
30410 amit.gupta 1102
					.selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1103
							monthEnd)
30053 manish 1104
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1105
		}
1106
 
30564 tejbeer 1107
		List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1108
				.selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
30053 manish 1109
 
30564 tejbeer 1110
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1111
				.selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1112
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1113
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1114
 
30564 tejbeer 1115
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1116
				.selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1117
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1118
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1119
 
30410 amit.gupta 1120
		Map<Integer, Double> modelTotalIncomeMap = new HashMap<>();
1121
		Map<Integer, String> modelNameMap = new HashMap<>();
30253 amit.gupta 1122
 
30410 amit.gupta 1123
		modelWiseSchemeOutMargins.stream().forEach(x -> {
30414 amit.gupta 1124
			modelTotalIncomeMap.put(x.getCatalogItemId(), x.getAmount() + x.getPendingSaleAmount());
1125
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + " " + x.getModelName()).trim());
30253 amit.gupta 1126
 
30410 amit.gupta 1127
		});
30414 amit.gupta 1128
		LastMonthBrandWiseIncomeModel totalModel = new LastMonthBrandWiseIncomeModel();
30410 amit.gupta 1129
		modelWiseSalesMargins.stream().forEach(x -> {
30413 amit.gupta 1130
			if (!modelWiseSchemeOutMarginsMap.containsKey(x.getCatalogItemId())) {
30410 amit.gupta 1131
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1132
				LastMonthBrandWiseIncomeModel lmbwIncomeModel = new LastMonthBrandWiseIncomeModel();
1133
				lmbwIncomeModel.setAmount(x.getAmount());
1134
				lmbwIncomeModel.setModelName(x.getModelName());
1135
				lmbwIncomeModel.setModelNumber(x.getModelNumber());
1136
				lmbwIncomeModel.setBrand(x.getBrand());
1137
				lmbwIncomeModel.setCatalogItemId(x.getCatalogItemId());
1138
				lmbwIncomeModel.setPendingSaleAmount(x.getPendingSaleAmount());
1139
				lmbwIncomeModel.setQty(x.getQty());
1140
				lmbwIncomeModel.setStatus(SchemePayoutStatus.CREDITED);
30410 amit.gupta 1141
				modelWiseSchemeOutMarginsMap.put(x.getCatalogItemId(), lmbwIncomeModel);
1142
 
30235 tejbeer 1143
			}
30410 amit.gupta 1144
			LastMonthBrandWiseIncomeModel lmbwIncomeModel = modelWiseSchemeOutMarginsMap.get(x.getCatalogItemId());
1145
			lmbwIncomeModel.setQty(x.getQty());
1146
			lmbwIncomeModel.setAmount(lmbwIncomeModel.getAmount() + x.getAmount());
30564 tejbeer 1147
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1148
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1149
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1150
			totalModel.setQty(totalModel.getQty() + x.getQty());
1151
			totalModel.setAmount(totalModel.getAmount() + lmbwIncomeModel.getAmount());
1152
			totalModel.setPendingSaleAmount(totalModel.getPendingSaleAmount());
30253 amit.gupta 1153
 
1154
		});
30410 amit.gupta 1155
		modelWiseSchemeInMargins.stream().forEach(x -> {
1156
			if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1157
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1158
			}
30564 tejbeer 1159
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1160
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1161
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1162
			totalModel.setQty(totalModel.getQty() + x.getQty());
1163
			totalModel.setAmount(totalModel.getAmount() + x.getAmount());
30053 manish 1164
 
30235 tejbeer 1165
		});
30053 manish 1166
 
30410 amit.gupta 1167
		model.addAttribute("month", month);
1168
		model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1169
		model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1170
		model.addAttribute("modelNameMap", modelNameMap);
1171
		model.addAttribute("modelTotalIncomeMap", modelTotalIncomeMap);
30414 amit.gupta 1172
		model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1173
		model.addAttribute("totalModel", totalModel);
30053 manish 1174
 
1175
		return "montly-brand-wise-income";
1176
 
1177
	}
1178
 
1179
	@RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1180
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1181
			throws ProfitMandiBusinessException {
1182
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1183
 
1184
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1185
		LocalDateTime currentMonthEnd = lastMonthStart.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
1186
 
1187
		YearMonth monthYear = YearMonth.now();
1188
 
1189
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
1190
 
1191
		LOGGER.info("partnerType" + partnerType);
1192
 
1193
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
1194
 
1195
		if (partnerType) {
1196
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1197
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), lastMonthStart,
1198
							currentMonthEnd)
1199
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1200
		}
1201
 
1202
		String status = "CREDITED";
1203
		LOGGER.info("lastMonthStart" + lastMonthStart);
1204
		LOGGER.info("currentMonthEnd" + currentMonthEnd);
1205
 
1206
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1207
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1208
 
1209
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1210
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1211
 
1212
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1213
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1214
 
1215
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
1216
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
1217
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
1218
 
1219
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
1220
 
1221
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1222
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1223
 
1224
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1225
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1226
 
1227
		lastMonthFrontEndIncomes.stream().forEach(x -> {
1228
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1229
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1230
 
1231
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1232
			} else {
1233
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1234
			}
1235
 
1236
		});
1237
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1238
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1239
		Set<String> keySet = new HashSet<String>();
1240
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1241
		keySet.addAll(lastMonthSaleMarginMap.keySet());
1242
 
1243
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1244
			String brand = x.getKey();
1245
			float amount = x.getValue().getAmount();
1246
			if (!totalAmountMap.containsKey(brand)) {
1247
				totalAmountMap.put(brand, 0f);
1248
			}
1249
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
1250
 
1251
		});
1252
 
1253
		Map<Integer, String> monthValueMap = new HashMap<>();
1254
		for (int i = 0; i <= 5; i++) {
1255
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1256
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1257
		}
1258
		model.addAttribute("monthValueMap", monthValueMap);
1259
 
1260
		model.addAttribute("keySet", keySet);
1261
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1262
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1263
 
1264
		model.addAttribute("totalAmountMap", totalAmountMap);
1265
		model.addAttribute("status", status);
1266
		model.addAttribute("month", yearMonth);
1267
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1268
		LOGGER.info("totalAmountMap {}", totalAmountMap);
1269
		LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
1270
 
1271
		return "last-month-credited-income";
1272
	}
1273
 
23020 ashik.ali 1274
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 1275
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 1276
		return "schemes-download";
1277
	}
23786 amit.gupta 1278
 
23020 ashik.ali 1279
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 1280
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
30831 tejbeer 1281
			@RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
23786 amit.gupta 1282
			throws ProfitMandiBusinessException {
23914 govind 1283
 
23020 ashik.ali 1284
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 1285
 
23020 ashik.ali 1286
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1287
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 1288
 
1289
		final HttpHeaders headers = new HttpHeaders();
1290
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 1291
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 1292
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1293
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1294
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1295
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 1296
	}
23786 amit.gupta 1297
 
22860 ashik.ali 1298
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 1299
	public String getSchemeById(HttpServletRequest request,
30831 tejbeer 1300
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
23786 amit.gupta 1301
			throws ProfitMandiBusinessException {
23343 ashik.ali 1302
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29899 tejbeer 1303
 
1304
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
22860 ashik.ali 1305
		Scheme scheme = schemeService.getSchemeById(schemeId);
29899 tejbeer 1306
		model.addAttribute("fullAccess", fullAccess);
22860 ashik.ali 1307
		model.addAttribute("scheme", scheme);
24445 amit.gupta 1308
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 1309
		return "scheme-details";
1310
	}
23786 amit.gupta 1311
 
22860 ashik.ali 1312
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1313
	public String activeSchemeById(HttpServletRequest request,
30831 tejbeer 1314
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1315
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1316
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1317
			throws ProfitMandiBusinessException {
22860 ashik.ali 1318
		schemeService.activeSchemeById(schemeId);
1319
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
30064 amit.gupta 1320
		for (Scheme scheme : schemes) {
1321
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1322
				scheme.setAmountModel(scheme.getAmount() + "%");
1323
			} else {
1324
				scheme.setAmountModel(scheme.getAmount() + "");
1325
			}
1326
		}
30122 amit.gupta 1327
		return "schemes";
22860 ashik.ali 1328
	}
23786 amit.gupta 1329
 
22860 ashik.ali 1330
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1331
	public String expireSchemeById(HttpServletRequest request,
30831 tejbeer 1332
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1333
			@RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
23786 amit.gupta 1334
			throws ProfitMandiBusinessException {
25069 amit.gupta 1335
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
30122 amit.gupta 1336
		return getDefaultSchemes(request, model);
22860 ashik.ali 1337
	}
23786 amit.gupta 1338
 
23784 ashik.ali 1339
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 1340
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
30831 tejbeer 1341
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1342
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1343
			throws ProfitMandiBusinessException {
23784 ashik.ali 1344
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1345
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1346
	}
26802 tejbeer 1347
 
29707 tejbeer 1348
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1349
	public String getCustomerOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1350
 
1351
		List<CustomerOffer> customerOffers = customerOfferRepository.selectAll();
1352
 
1353
		model.addAttribute("customerOffers", customerOffers);
1354
		return "customer-offer";
1355
 
1356
	}
1357
 
1358
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1359
	public String createCustomerOffer(HttpServletRequest request, @RequestParam String offerName,
30831 tejbeer 1360
			@RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model) throws Exception {
29707 tejbeer 1361
 
1362
		CustomerOffer co = new CustomerOffer();
1363
		co.setOfferName(offerName);
1364
		co.setStartDate(startDate);
1365
		co.setEndDate(endDate);
1366
		co.setCreatedTimestamp(LocalDateTime.now());
1367
		co.setUpdatedTimestamp(LocalDateTime.now());
1368
		customerOfferRepository.persist(co);
1369
 
1370
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1371
 
1372
		return "response";
1373
 
1374
	}
1375
 
1376
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1377
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1378
		List<List<?>> rows = new ArrayList<>();
1379
 
1380
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1381
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1382
 
1383
		final HttpHeaders headers = new HttpHeaders();
1384
		headers.set("Content-Type", "text/csv");
1385
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1386
		headers.setContentLength(baos.toByteArray().length);
1387
 
1388
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1389
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1390
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1391
 
1392
	}
1393
 
1394
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1395
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
30831 tejbeer 1396
			HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
29707 tejbeer 1397
 
1398
		List<CSVRecord> records = FileUtil.readFile(file);
1399
 
1400
		for (CSVRecord record : records) {
1401
			if (Integer.parseInt(record.get(0)) == 0) {
1402
				CustomerOfferItem coi = new CustomerOfferItem();
1403
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1404
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1405
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1406
				coi.setCustomerOfferId(offerId);
1407
				coi.setUpdatedTimestamp(LocalDateTime.now());
1408
				coi.setCreatedTimestamp(LocalDateTime.now());
1409
				customerOfferItemRepository.persist(coi);
1410
 
1411
			} else {
1412
				CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1413
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1414
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1415
				coi.setUpdatedTimestamp(LocalDateTime.now());
1416
			}
1417
 
1418
		}
1419
 
1420
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1421
 
1422
		return "response";
1423
 
1424
	}
1425
 
1426
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1427
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1428
 
1429
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1430
		List<List<?>> rows = new ArrayList<>();
1431
 
1432
		for (CustomerOfferItem coi : cois) {
1433
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout()));
1434
 
1435
		}
1436
 
1437
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1438
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1439
 
1440
		final HttpHeaders headers = new HttpHeaders();
1441
		headers.set("Content-Type", "text/csv");
1442
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1443
		headers.setContentLength(baos.toByteArray().length);
1444
 
1445
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1446
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1447
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1448
 
1449
	}
1450
 
1451
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1452
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
30831 tejbeer 1453
			@RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
29707 tejbeer 1454
 
1455
		CustomerOffer co = customerOfferRepository.selectById(id);
1456
		co.setEndDate(endDate);
1457
		co.setUpdatedTimestamp(LocalDateTime.now());
1458
 
1459
		model.addAttribute("co", co);
1460
 
1461
		return "customer-index-offer";
1462
 
1463
	}
1464
 
1465
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1466
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1467
 
1468
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1469
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1470
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1471
 
1472
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1473
		return "samsung-upgrade-offer";
1474
 
1475
	}
1476
 
1477
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1478
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1479
			throws ProfitMandiBusinessException {
1480
 
1481
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1482
		suo.setStatus(UpgradeOfferStatus.approved);
1483
		suo.setApprovedTimestamp(LocalDateTime.now());
1484
		model.addAttribute("suo", suo);
1485
		return "samsung-upgrade-offer-index";
1486
 
1487
	}
1488
 
1489
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1490
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1491
			throws ProfitMandiBusinessException {
1492
 
1493
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1494
		suo.setStatus(UpgradeOfferStatus.rejected);
1495
 
1496
		model.addAttribute("suo", suo);
1497
		return "samsung-upgrade-offer-index";
1498
 
1499
	}
30410 amit.gupta 1500
 
22860 ashik.ali 1501
}