Subversion Repositories SmartDukaan

Rev

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