Subversion Repositories SmartDukaan

Rev

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