Subversion Repositories SmartDukaan

Rev

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