Subversion Repositories SmartDukaan

Rev

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