Subversion Repositories SmartDukaan

Rev

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