Subversion Repositories SmartDukaan

Rev

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