Subversion Repositories SmartDukaan

Rev

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