Subversion Repositories SmartDukaan

Rev

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