Subversion Repositories SmartDukaan

Rev

Rev 30053 | Rev 30122 | 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)
418
				for (int itemId : schemeItems.getItemIds()) {
419
					if (tagListingRepository.selectByItemIdsAndTagIds(new HashSet<>(Arrays.asList(itemId)),
420
							new HashSet<>(Arrays.asList(4, 7))).size() > 0) {
421
						SchemeItem si = new SchemeItem();
422
						si.setItemId(itemId);
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));
433
						throw new ProfitMandiBusinessException("ItemId", itemId, "Invalid Item Id");
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()) {
23914 govind 444
			List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(schemeId);
23786 amit.gupta 445
			if (schemeRepository.selectById(schemeId) != null)
446
				for (int itemId : schemeItems.getItemIds()) {
447
					if (tagListingRepository.selectByItemIdsAndTagIds(new HashSet<>(Arrays.asList(itemId)),
23914 govind 448
							new HashSet<>(Arrays.asList(4, 7))).size() > 0 && (!(itemIds.contains(itemId)))) {
23786 amit.gupta 449
						SchemeItem si = new SchemeItem();
450
						si.setItemId(itemId);
451
						si.setSchemeId(schemeId);
29608 amit.gupta 452
						si.setCreateTimestamp(LocalDateTime.now());
23786 amit.gupta 453
						try {
454
							schemeItemRepository.persist(si);
455
						} catch (Exception e) {
23914 govind 456
							LOGGER.info("Scheme already exist");
23786 amit.gupta 457
						}
458
						model.addAttribute("response", mvcResponseSender.createResponseString(true));
459
					} else {
460
						model.addAttribute("response", mvcResponseSender.createResponseString(false));
23556 amit.gupta 461
					}
462
				}
463
		}
464
		return "response";
465
	}
23914 govind 466
 
467
	@RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
468
	public String deleteShcemes(HttpServletRequest request,
30053 manish 469
			@RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
470
			@RequestParam(name = "itemId", required = false, defaultValue = "0") int itemId, Model model)
23819 govind 471
			throws Exception {
23914 govind 472
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
473
		if (!(schemeId == 0 && itemId == 0) || (!(schemeId == 0 || itemId == 0))) {
474
			schemeItemRepository.deletebyItemIdsandSchemeIds(itemId, schemeId);
475
 
476
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
477
 
478
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
479
 
480
		}
481
		return "response";
482
	}
483
 
484
	@RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
485
	public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
486
			throws Exception {
28924 amit.gupta 487
		extendDatetime = LocalDateTime.of(extendDatetime.toLocalDate(), Utils.MAX_TIME);
23914 govind 488
		List<Scheme> schemes = schemeRepository.selectActiveAll();
489
		if (schemes.size() > 0) {
490
			for (Scheme scheme : schemes) {
25261 amit.gupta 491
				if (scheme.getExpireTimestamp() == null) {
23914 govind 492
					scheme.setEndDateTime(extendDatetime);
493
					schemeRepository.persist(scheme);
23819 govind 494
				}
495
			}
23914 govind 496
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
497
			return "response";
23819 govind 498
		}
23914 govind 499
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
23819 govind 500
		return "response";
501
	}
23786 amit.gupta 502
 
23914 govind 503
	@RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
504
	public String extendSchemeById(HttpServletRequest request,
23819 govind 505
 
30053 manish 506
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
507
			@RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
28924 amit.gupta 508
		extendDatetime = LocalDateTime.of(extendDatetime.toLocalDate(), Utils.MAX_TIME);
23914 govind 509
		Scheme scheme = schemeRepository.selectById(schemeId);
510
		if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
511
			scheme.setEndDateTime(extendDatetime);
512
			schemeRepository.persist(scheme);
513
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
514
			return "response";
515
		}
516
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
517
		return "response";
518
	}
519
 
22860 ashik.ali 520
	@RequestMapping(value = "/createScheme", method = RequestMethod.POST)
23715 govind 521
	public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
30053 manish 522
			@RequestParam(name = "offset", defaultValue = "0") int offset,
523
			@RequestParam(name = "limit", defaultValue = "10") int limit,
524
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
525
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
23715 govind 526
			throws ProfitMandiBusinessException {
22927 ashik.ali 527
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 528
		LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
22927 ashik.ali 529
		schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
530
		LOGGER.info("Scheme saved successfully");
23271 ashik.ali 531
		long size = schemeRepository.selectAllCount();
22927 ashik.ali 532
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
29899 tejbeer 533
 
534
		if (!schemes.isEmpty()) {
535
			for (Scheme scheme : schemes) {
536
				if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
537
					scheme.setAmountModel(scheme.getAmount() + "%");
538
				} else {
539
					scheme.setAmountModel(scheme.getAmount() + "");
540
				}
541
			}
542
		}
22927 ashik.ali 543
		model.addAttribute("schemes", schemes);
544
		model.addAttribute("start", offset + 1);
23271 ashik.ali 545
		model.addAttribute("size", size);
23752 govind 546
		model.addAttribute("searchItem", searchItem);
547
		model.addAttribute("searchTerm", searchTerm);
23914 govind 548
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23715 govind 549
		if (schemes.size() < limit) {
22927 ashik.ali 550
			model.addAttribute("end", offset + schemes.size());
23786 amit.gupta 551
		} else {
22927 ashik.ali 552
			model.addAttribute("end", offset + limit);
553
		}
554
		return "schemes";
23786 amit.gupta 555
 
22860 ashik.ali 556
	}
23786 amit.gupta 557
 
22860 ashik.ali 558
	@RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
23715 govind 559
	public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
30053 manish 560
			@RequestParam(required = false) LocalDate date,
561
			@RequestParam(name = "limit", defaultValue = "10") int limit,
562
			@RequestParam(name = "searchItem", required = false, defaultValue = "0") int searchItem,
563
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
564
			@RequestParam(name = "partnerType", required = false, defaultValue = "") PartnerType partnerType,
565
			@RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
28795 tejbeer 566
			throws ProfitMandiBusinessException {
23343 ashik.ali 567
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 568
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 569
		if (date == null) {
570
			date = LocalDate.now();
571
		}
572
		model.addAttribute("date", date);
26802 tejbeer 573
 
23343 ashik.ali 574
		List<Scheme> schemes = null;
28796 tejbeer 575
		List<SchemeInOut> schemeInOut = null;
576
 
23343 ashik.ali 577
		long size = 0;
28980 amit.gupta 578
		date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
29649 amit.gupta 579
		final LocalDate date1 = date;
26802 tejbeer 580
		if (partnerType == null) {
29608 amit.gupta 581
			// TODO - SCHEME
582
 
583
			partnerType = partnerTypeChangeService.getTypeOnMonth(loginDetails.getFofoId(), YearMonth.from(date));
584
 
585
			// partnerType =
586
			// partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), date);
23343 ashik.ali 587
		}
27394 amit.gupta 588
		if (!(searchTerm.equals(""))) {
26802 tejbeer 589
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
27612 tejbeer 590
			for (Scheme scheme : schemes) {
591
				if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
27394 amit.gupta 592
					scheme.setAmountModel(scheme.getAmount() + "%");
593
				} else {
594
					scheme.setAmountModel(scheme.getAmount() + "");
595
				}
596
			}
27876 amit.gupta 597
			if (schemes.size() > 0) {
26802 tejbeer 598
				size = schemeRepository.selectAllCount();
599
				LOGGER.info("schemes" + schemes);
600
				model.addAttribute("schemes", schemes);
601
				model.addAttribute("start", offset + 1);
602
				model.addAttribute("size", size);
603
				if (schemes.size() < limit) {
604
					model.addAttribute("end", offset + schemes.size());
27876 amit.gupta 605
				} else {
26802 tejbeer 606
					model.addAttribute("end", offset + limit);
607
				}
30043 amit.gupta 608
			} else {
26802 tejbeer 609
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
610
			}
30043 amit.gupta 611
		} else if (searchItem > 0) {
27394 amit.gupta 612
			TagListing tagListing = null;
28134 tejbeer 613
			tagListing = tagListingRepository.selectByItemId(searchItem);
28492 amit.gupta 614
			Item item = itemRepository.selectById(searchItem);
28134 tejbeer 615
			if (tagListing != null) {
616
				model.addAttribute("dp", tagListing.getSellingPrice());
617
				model.addAttribute("mop", tagListing.getMop());
26802 tejbeer 618
			}
29707 tejbeer 619
			schemes = schemeService.selectSchemeByPartnerType(partnerType, date, searchItem, isAdmin, offset, limit)
620
					.stream().filter(x -> {
621
						return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
622
					}).collect(Collectors.toList());
623
			// Remove 411 and 612
29658 amit.gupta 624
			model.addAttribute("schemes", schemes);
27612 tejbeer 625
			if (schemes.size() == 0) {
28795 tejbeer 626
				if (isAdmin)
627
					return "schemes";
628
				else {
27612 tejbeer 629
 
28795 tejbeer 630
					return "schemes-partner";
27389 amit.gupta 631
				}
632
			}
28795 tejbeer 633
			// For 7720(HR) remove investment
634
			int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing, searchItem);
27897 amit.gupta 635
			size = schemeService.selectSchemeCount(partnerType, date, searchItem, isAdmin);
26802 tejbeer 636
			model.addAttribute("start", offset + 1);
637
			model.addAttribute("size", size);
638
			if (schemes.size() < limit) {
639
				model.addAttribute("end", offset + schemes.size());
640
			} else {
641
				model.addAttribute("end", offset + limit);
642
			}
28547 amit.gupta 643
			model.addAttribute("nlc", Math.round(nlc));
28795 tejbeer 644
		} else if (!(searchImei.equals(""))) {
645
 
646
			LOGGER.info("searchImei" + searchImei);
647
 
648
			InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
649
					loginDetails.getFofoId());
28802 tejbeer 650
			Item item = itemRepository.selectById(inventoryItem.getItemId());
28795 tejbeer 651
			Map<Integer, Scheme> schemeMap = new HashMap<>();
652
			if (inventoryItem != null) {
653
 
654
				LOGGER.info("inventoryItem" + inventoryItem);
655
 
656
				schemeInOut = schemeInOutRepository
657
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
658
 
659
				LOGGER.info("schemeInOut" + schemeInOut);
660
 
661
				if (!schemeInOut.isEmpty()) {
662
 
663
					List<Integer> schemeIds = schemeInOut.stream().map(x -> x.getSchemeId())
664
							.collect(Collectors.toList());
665
 
666
					schemes = schemeRepository.selectBySchemeIds(schemeIds);
667
					for (Scheme scheme : schemes) {
668
						if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
669
							scheme.setAmountModel(scheme.getAmount() + "%");
670
						} else {
671
							scheme.setAmountModel(scheme.getAmount() + "");
672
						}
673
					}
674
 
675
					schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
676
				}
677
			}
678
 
679
			model.addAttribute("schemeMap", schemeMap);
28802 tejbeer 680
			model.addAttribute("item", item);
28795 tejbeer 681
 
28796 tejbeer 682
		}
683
		model.addAttribute("schemeInOut", schemeInOut);
28795 tejbeer 684
 
27876 amit.gupta 685
		model.addAttribute("searchItem", searchItem);
686
		model.addAttribute("searchTerm", searchTerm);
687
		model.addAttribute("partnerType", partnerType);
688
		model.addAttribute("isAdmin", isAdmin);
29650 amit.gupta 689
		LOGGER.info("schemes" + schemes);
29707 tejbeer 690
		model.addAttribute("schemes", schemes != null ? schemes.stream().filter(x -> {
691
			return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
29651 amit.gupta 692
		}).collect(Collectors.toList()) : null);
27876 amit.gupta 693
		LOGGER.info("schemes" + schemes);
23786 amit.gupta 694
		// model.addAttribute("roleTypes", loginDetails.getRoleTypes());
29899 tejbeer 695
		if (isAdmin) {
696
 
697
			boolean fullAccess = this.getAccess(loginDetails.getEmailId());
698
 
699
			model.addAttribute("fullAccess", fullAccess);
700
 
27876 amit.gupta 701
			return "schemes";
29899 tejbeer 702
		} else {
30043 amit.gupta 703
			List<CreateOfferRequest> offers = null;
29883 amit.gupta 704
			Map<Integer, Map<Integer, Long>> offerSlabPayoutMap = new HashMap<>();
28795 tejbeer 705
			List<PriceDropIMEI> priceDropImeis = new ArrayList<>();
28134 tejbeer 706
			if (searchItem > 0) {
27897 amit.gupta 707
				offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(), searchItem);
29899 tejbeer 708
				for (CreateOfferRequest createOfferRequest : offers) {
709
					Map<Integer, Map<Integer, Long>> itemSlabPayoutMap = offerService
710
							.getSlabPayoutMap(createOfferRequest);
711
					Map<Integer, Long> slabPayoutMap = itemSlabPayoutMap.get(searchItem);
29883 amit.gupta 712
					offerSlabPayoutMap.put(createOfferRequest.getId(), slabPayoutMap);
713
				}
30043 amit.gupta 714
			} else {
715
				offers = new ArrayList<>();
27897 amit.gupta 716
			}
28795 tejbeer 717
			if (!(searchImei.equals(""))) {
718
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
719
						loginDetails.getFofoId());
720
 
721
				priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
722
				for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
723
					int priceDropId = priceDropIMEI.getPriceDropId();
724
					PriceDrop pd = priceDropRepository.selectById(priceDropId);
725
 
726
					priceDropIMEI.setPriceDrop(pd);
727
				}
728
			}
28136 tejbeer 729
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
730
 
27876 amit.gupta 731
			model.addAttribute("offers", offers);
29883 amit.gupta 732
			model.addAttribute("offerSlabPayoutMap", offerSlabPayoutMap);
28136 tejbeer 733
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 734
			model.addAttribute("fofoId", fs.getId());
735
			model.addAttribute("priceDropImeis", priceDropImeis);
27876 amit.gupta 736
			return "schemes-partner";
737
		}
29899 tejbeer 738
 
22860 ashik.ali 739
	}
23786 amit.gupta 740
 
28795 tejbeer 741
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing, int itemId)
742
			throws ProfitMandiBusinessException {
743
 
744
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
745
				.filter(x -> x.getId() == fofoId).count() > 0) {
746
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
747
					.collect(Collectors.toList());
748
		}
749
		float nlc = tagListing.getSellingPrice();
750
		for (Scheme scheme : schemes) {
751
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
752
				if (tagListing != null) {
753
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
754
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
755
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
30053 manish 756
					scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
28795 tejbeer 757
					nlc -= amount;
30043 amit.gupta 758
				} else {
28795 tejbeer 759
					scheme.setAmountModel(scheme.getAmount() + "%");
760
				}
761
			} else {
762
				scheme.setAmountModel(scheme.getAmount() + "");
763
				nlc -= scheme.getAmount();
764
			}
765
		}
766
 
767
		return Math.round(nlc);
768
 
769
	}
770
 
30053 manish 771
	@RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
772
	public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
773
 
774
		String status = "CREDITED";
775
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
776
 
777
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
778
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
779
 
780
		YearMonth yearMonth = YearMonth.now();
781
		LOGGER.info("yearMonth" + yearMonth);
782
 
783
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
784
 
785
		LOGGER.info("partnerType" + partnerType);
786
 
787
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
788
 
789
		if (partnerType) {
790
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
791
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
792
							currentDate)
793
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
794
		}
795
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
796
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
797
 
798
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
799
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
800
 
801
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
802
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
803
 
804
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
805
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
806
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
807
		LOGGER.info("lastMonthCategoryUpgradeMarginMap" + lastMonthCategoryUpgradeMarginMap);
808
 
809
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
810
 
811
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
812
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
813
 
814
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
815
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
816
 
817
		lastMonthFrontEndIncomes.stream().forEach(x -> {
818
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
819
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
820
				lastMonthSaleMarginMap.put(x.getBrand(), x);
821
			} else {
822
				lastMonthSaleMarginMap.put(x.getBrand(), x);
823
			}
824
 
825
		});
826
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
827
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
828
 
829
		Set<String> keySet = new HashSet<String>();
830
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
831
		keySet.addAll(lastMonthSaleMarginMap.keySet());
832
 
833
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
834
			String brand = x.getKey();
835
			float amount = x.getValue().getAmount();
836
			if (!totalAmountMap.containsKey(brand)) {
837
				totalAmountMap.put(brand, 0f);
838
			}
839
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
840
 
841
		});
842
 
843
		Map<Integer, String> monthValueMap = new HashMap<>();
844
		for (int i = 0; i <= 5; i++) {
845
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
846
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
847
		}
848
		model.addAttribute("month", 0);
849
		model.addAttribute("monthValueMap", monthValueMap);
850
		model.addAttribute("keySet", keySet);
851
 
852
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
853
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
854
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
855
		model.addAttribute("status", status);
856
		model.addAttribute("totalAmountMap", totalAmountMap);
857
 
858
		return "last-month-credited-income";
859
	}
860
 
861
	@RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
862
	public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
863
 
864
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
865
 
866
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
867
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
868
		String status = "PENDING";
869
 
870
		LOGGER.info("currentStartMonth" + currentStartMonth);
871
		LOGGER.info("currentDate" + currentDate);
872
 
873
		List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
874
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
875
 
876
		Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
877
 
878
		for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
879
 
880
			lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
881
		}
882
		LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
883
		LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
884
		model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
885
		model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
886
		model.addAttribute("status", status);
887
 
888
		return "last-month-credited-income";
889
	}
890
 
891
	@RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
892
	public String getLastMonthImeiWiseIncome(HttpServletRequest request,
893
			@RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
894
			@RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
895
			throws Exception {
896
 
897
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
898
 
899
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
900
		LocalDateTime currentMonthEnd = lastMonthStart.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
901
 
902
		HashSet<String> allImeiSet = new LinkedHashSet<>();
903
		HashSet<String> purchaseSet = new LinkedHashSet<>();
904
		HashSet<String> saleSet = new LinkedHashSet<>();
905
 
906
		List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
907
				.selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, currentMonthEnd);
908
		List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
909
				catalogItemId, lastMonthStart, currentMonthEnd);
910
		List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
911
				catalogItemId, lastMonthStart, currentMonthEnd);
912
 
913
		Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
914
				.selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
915
						currentMonthEnd)
916
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
917
 
918
		allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
919
		allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
920
		allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
921
 
922
		List<String> allImeiList = new ArrayList<>(allImeiSet);
923
 
924
		LOGGER.info("allImeiList" + allImeiList);
925
		LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
926
		List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
927
				.selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
928
		List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
929
				.selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
930
		List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
931
				.selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
932
 
933
		LOGGER.info("lastMonthFrontEndImei {}", lastMonthFrontEndImeis);
934
		LOGGER.info("lastMonthPurchaseInImei {}", lastMonthPurchaseInImeis);
935
		LOGGER.info("lastMonthCreditedImei {}", lastMonthCreditedImeis);
936
 
937
		Map<IncomeImeiDate, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
938
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
939
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
940
 
941
		Map<IncomeImeiDate, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
942
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
943
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
944
		// descriptionSet.add("")
945
 
946
		purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
947
		saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
948
 
949
		List<String> purchaseList = new ArrayList<>(purchaseSet);
950
		List<String> saleList = new ArrayList<>(saleSet);
951
		Map<IncomeImeiDate, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
952
 
953
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
954
 
955
			IncomeImeiDate imeiDate = entry.getKey();
956
			Map<String, Double> descriptionAmountMap = entry.getValue();
957
 
958
			ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(),
959
					imeiDate.getLocalDateTime(), null, descriptionAmountMap);
960
			imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
961
			double totalAmount = imeiWiseIncomeMapOfMap.get(imeiDate).getDescriptionAmountMap().entrySet().stream()
962
					.collect(Collectors.summingDouble(x -> x.getValue()));
963
			imeiWiseIncomeMapOfMap.get(imeiDate).setTotalIncome(totalAmount);
964
		}
965
 
966
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
967
			IncomeImeiDate imeiDate = entry.getKey();
968
			Map<String, Double> descriptionAmountMap = entry.getValue();
969
			if (!imeiWiseIncomeMapOfMap.containsKey(imeiDate)) {
970
				ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(), null,
971
						imeiDate.getLocalDateTime(), descriptionAmountMap);
972
				imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
973
 
974
			} else {
975
				ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(imeiDate);
976
				modelImeiMap.setSaleDate(imeiDate.getLocalDateTime());
977
				modelImeiMap.getDescriptionAmountMap().putAll(descriptionAmountMap);
978
 
979
			}
980
			double totalAmount = descriptionAmountMap.entrySet().stream()
981
					.collect(Collectors.summingDouble(x -> x.getValue()));
982
			imeiWiseIncomeMapOfMap.get(imeiDate)
983
					.setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(imeiDate).getTotalIncome());
984
		}
985
 
986
		lastMonthFrontEndImeis.stream().forEach(x -> {
987
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), null);
988
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
989
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
990
						.get(incomeImeiDate);
991
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount();
992
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
993
				imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
994
			}
995
		});
996
 
997
		model.addAttribute("month", month);
998
		model.addAttribute("purchaseList", purchaseList);
999
		model.addAttribute("saleList", saleList);
1000
		model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1001
		model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1002
		model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1003
		model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
1004
 
1005
		LOGGER.info("lastMonthPurchaseInMapPairMap {}", lastMonthPurchaseInMapPairMap);
1006
		LOGGER.info("lastMonthCreditedMapPairMap {}", lastMonthCreditedMapPairMap);
1007
		LOGGER.info("imeiWiseIncomeMapOfMap {}", imeiWiseIncomeMapOfMap);
1008
 
1009
		return "last-month-imei-wise-income";
1010
	}
1011
 
1012
	@RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1013
	public String getBrandWiseIncome(HttpServletRequest request,
1014
			@RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1015
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
1016
			@RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
1017
			throws ProfitMandiBusinessException {
1018
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1019
		LOGGER.info("loginDetails {}", loginDetails);
1020
		LOGGER.info("brand" + brand);
1021
		LOGGER.info("month {}", month);
1022
 
1023
		model.addAttribute("month", month);
1024
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1025
		LocalDateTime currentMonthEnd = lastMonthStart.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
1026
 
1027
		List<LastMonthBrandWiseIncomeModel> lastMonthModelWiseIncomes = null;
1028
		List<LastMonthBrandWiseIncomeModel> modelWiseFrontIncomes = null;
1029
		List<LastMonthBrandWiseIncomeModel> purchaseInModelWiseIncomes = null;
1030
 
1031
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), YearMonth.now());
1032
 
1033
		LOGGER.info("partnerType" + partnerType);
1034
 
1035
		Map<String, Double> categoryUpradeBrandModelMap = new HashMap<>();
1036
 
1037
		if (partnerType) {
1038
			categoryUpradeBrandModelMap = schemeInOutRepository
1039
					.selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, lastMonthStart,
1040
							currentMonthEnd)
1041
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1042
		}
1043
		LOGGER.info("partnerType {}", partnerType);
1044
		LOGGER.info("categoryUpradeBrandModelMap {}", categoryUpradeBrandModelMap);
1045
 
1046
		if (status.equals("PENDING")) {
1047
		}
1048
 
1049
		if (status.equals("CREDITED")) {
1050
			lastMonthModelWiseIncomes = schemeInOutRepository.selectLastMonthBrandWiseIncome(loginDetails.getFofoId(),
1051
					brand, lastMonthStart, currentMonthEnd);
1052
			modelWiseFrontIncomes = schemeInOutRepository.selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand,
1053
					lastMonthStart, currentMonthEnd);
1054
			purchaseInModelWiseIncomes = schemeInOutRepository.selectLastMonthPurchaseBrandWiseIncome(
1055
					loginDetails.getFofoId(), brand, lastMonthStart, currentMonthEnd);
1056
			LOGGER.info("modelWiseFrontIncomes {}", modelWiseFrontIncomes);
1057
			LOGGER.info("lastMonthModelWiseIncomes {}", lastMonthModelWiseIncomes);
1058
			LOGGER.info("purchaseInModelWiseIncomes {}", purchaseInModelWiseIncomes);
1059
			Map<String, LastMonthBrandWiseIncomeModel> modelWiseMap = lastMonthModelWiseIncomes.stream()
1060
					.collect(Collectors.toMap(x -> x.getModelNumber(), x -> x));
1061
 
1062
			Map<String, LastMonthBrandWiseIncomeModel> purchaseWiseMap = purchaseInModelWiseIncomes.stream()
1063
					.collect(Collectors.toMap(x -> x.getModelNumber(), x -> x));
1064
 
1065
			Map<String, Double> modelWiseTotalAmount = new HashMap<>();
1066
			modelWiseFrontIncomes.stream().forEach(x -> {
1067
				if (modelWiseMap.containsKey(x.getModelNumber())) {
1068
 
1069
					x.setAmount(x.getAmount() + modelWiseMap.get(x.getModelNumber()).getAmount());
1070
 
1071
					modelWiseMap.put(x.getModelNumber(), x);
1072
				} else {
1073
					modelWiseMap.put(x.getModelNumber(), x);
1074
				}
1075
				if (modelWiseTotalAmount.containsKey(x.getModelNumber())) {
1076
 
1077
					double amount = x.getAmount() + modelWiseTotalAmount.get(x.getModelNumber());
1078
					modelWiseTotalAmount.put(x.getModelNumber(), amount);
1079
				} else {
1080
					modelWiseTotalAmount.put(x.getModelNumber(), x.getAmount());
1081
				}
1082
 
1083
			});
1084
			for (LastMonthBrandWiseIncomeModel pmi : purchaseInModelWiseIncomes) {
1085
 
1086
				if (!modelWiseMap.containsKey(pmi.getModelNumber())) {
1087
 
1088
					modelWiseMap.put(pmi.getModelNumber(), null);
1089
				}
1090
 
1091
				if (modelWiseTotalAmount.containsKey(pmi.getModelNumber())) {
1092
 
1093
					double amount = pmi.getAmount() + modelWiseTotalAmount.get(pmi.getModelNumber());
1094
					modelWiseTotalAmount.put(pmi.getModelNumber(), amount);
1095
				} else {
1096
					modelWiseTotalAmount.put(pmi.getModelNumber(), pmi.getAmount());
1097
				}
1098
 
1099
			}
1100
 
1101
			model.addAttribute("purchaseWiseMap", purchaseWiseMap);
1102
			model.addAttribute("categoryUpradeBrandModelMap", categoryUpradeBrandModelMap);
1103
			model.addAttribute("modelWiseMap", modelWiseMap);
1104
			model.addAttribute("modelWiseTotalAmount", modelWiseTotalAmount);
1105
 
1106
		}
1107
 
1108
		return "montly-brand-wise-income";
1109
 
1110
	}
1111
 
1112
	@RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1113
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1114
			throws ProfitMandiBusinessException {
1115
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1116
 
1117
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1118
		LocalDateTime currentMonthEnd = lastMonthStart.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
1119
 
1120
		YearMonth monthYear = YearMonth.now();
1121
 
1122
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
1123
 
1124
		LOGGER.info("partnerType" + partnerType);
1125
 
1126
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
1127
 
1128
		if (partnerType) {
1129
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1130
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), lastMonthStart,
1131
							currentMonthEnd)
1132
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1133
		}
1134
 
1135
		String status = "CREDITED";
1136
		LOGGER.info("lastMonthStart" + lastMonthStart);
1137
		LOGGER.info("currentMonthEnd" + currentMonthEnd);
1138
 
1139
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1140
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1141
 
1142
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1143
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1144
 
1145
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1146
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1147
 
1148
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
1149
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
1150
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
1151
 
1152
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
1153
 
1154
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1155
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1156
 
1157
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1158
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1159
 
1160
		lastMonthFrontEndIncomes.stream().forEach(x -> {
1161
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1162
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1163
 
1164
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1165
			} else {
1166
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1167
			}
1168
 
1169
		});
1170
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1171
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1172
		Set<String> keySet = new HashSet<String>();
1173
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1174
		keySet.addAll(lastMonthSaleMarginMap.keySet());
1175
 
1176
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1177
			String brand = x.getKey();
1178
			float amount = x.getValue().getAmount();
1179
			if (!totalAmountMap.containsKey(brand)) {
1180
				totalAmountMap.put(brand, 0f);
1181
			}
1182
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
1183
 
1184
		});
1185
 
1186
		Map<Integer, String> monthValueMap = new HashMap<>();
1187
		for (int i = 0; i <= 5; i++) {
1188
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1189
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1190
		}
1191
		model.addAttribute("monthValueMap", monthValueMap);
1192
 
1193
		model.addAttribute("keySet", keySet);
1194
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1195
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1196
 
1197
		model.addAttribute("totalAmountMap", totalAmountMap);
1198
		model.addAttribute("status", status);
1199
		model.addAttribute("month", yearMonth);
1200
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1201
		LOGGER.info("totalAmountMap {}", totalAmountMap);
1202
		LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
1203
 
1204
		return "last-month-credited-income";
1205
	}
1206
 
22860 ashik.ali 1207
	@RequestMapping(value = "/getPaginatedSchemes", method = RequestMethod.GET)
27876 amit.gupta 1208
	public String getPaginatedSchemes(HttpServletRequest request, @RequestParam(required = false) LocalDate date,
30053 manish 1209
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1210
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1211
			@RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
1212
			Model model) throws ProfitMandiBusinessException {
26802 tejbeer 1213
 
23343 ashik.ali 1214
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 1215
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 1216
		if (date == null) {
1217
			date = LocalDate.now();
1218
		}
23271 ashik.ali 1219
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
27876 amit.gupta 1220
		List<Scheme> schemes = schemeRepository.selectAll();
26802 tejbeer 1221
		int itemId = 0;
27394 amit.gupta 1222
		TagListing tagListing = null;
27897 amit.gupta 1223
 
27612 tejbeer 1224
		for (Scheme scheme : schemes) {
1225
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1226
				if (itemId > 0) {
27394 amit.gupta 1227
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
1228
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
1229
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
30053 manish 1230
					scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
27394 amit.gupta 1231
				} else {
1232
					scheme.setAmountModel(scheme.getAmount() + "%");
1233
				}
1234
			} else {
27876 amit.gupta 1235
				scheme.setAmountModel("" + scheme.getAmount());
27394 amit.gupta 1236
			}
1237
		}
26802 tejbeer 1238
 
22860 ashik.ali 1239
		model.addAttribute("schemes", schemes);
26912 tejbeer 1240
		model.addAttribute("partnerType", partnerType);
23914 govind 1241
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 1242
		return "schemes-paginated";
1243
	}
23786 amit.gupta 1244
 
23020 ashik.ali 1245
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 1246
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 1247
		return "schemes-download";
1248
	}
23786 amit.gupta 1249
 
23020 ashik.ali 1250
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 1251
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
30053 manish 1252
			@RequestParam(name = ProfitMandiConstants.START_DATE_TIME) String startDateTimeString,
1253
			@RequestParam(name = ProfitMandiConstants.END_DATE_TIME) String endDateTimeString, Model model)
23786 amit.gupta 1254
			throws ProfitMandiBusinessException {
23914 govind 1255
		LocalDateTime startDateTime = StringUtils.toDateTime(startDateTimeString,
24406 amit.gupta 1256
				DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
1257
		LocalDateTime endDateTime = StringUtils.toDateTime(endDateTimeString, DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
23914 govind 1258
 
23020 ashik.ali 1259
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 1260
 
23020 ashik.ali 1261
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1262
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 1263
 
1264
		final HttpHeaders headers = new HttpHeaders();
1265
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 1266
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 1267
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1268
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1269
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1270
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 1271
	}
23786 amit.gupta 1272
 
22860 ashik.ali 1273
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 1274
	public String getSchemeById(HttpServletRequest request,
30053 manish 1275
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
23786 amit.gupta 1276
			throws ProfitMandiBusinessException {
23343 ashik.ali 1277
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29899 tejbeer 1278
 
1279
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
22860 ashik.ali 1280
		Scheme scheme = schemeService.getSchemeById(schemeId);
29899 tejbeer 1281
		model.addAttribute("fullAccess", fullAccess);
22860 ashik.ali 1282
		model.addAttribute("scheme", scheme);
24445 amit.gupta 1283
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 1284
		return "scheme-details";
23914 govind 1285
 
22860 ashik.ali 1286
	}
23786 amit.gupta 1287
 
22860 ashik.ali 1288
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1289
	public String activeSchemeById(HttpServletRequest request,
30053 manish 1290
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1291
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1292
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1293
			throws ProfitMandiBusinessException {
22860 ashik.ali 1294
		schemeService.activeSchemeById(schemeId);
1295
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
30064 amit.gupta 1296
		for (Scheme scheme : schemes) {
1297
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1298
				scheme.setAmountModel(scheme.getAmount() + "%");
1299
			} else {
1300
				scheme.setAmountModel(scheme.getAmount() + "");
1301
			}
1302
		}
22860 ashik.ali 1303
		model.addAttribute("schemes", schemes);
1304
		return "schemes-paginated";
1305
	}
23786 amit.gupta 1306
 
22860 ashik.ali 1307
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1308
	public String expireSchemeById(HttpServletRequest request,
30053 manish 1309
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1310
			@RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp,
1311
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1312
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1313
			throws ProfitMandiBusinessException {
28924 amit.gupta 1314
		expiryTimestamp = LocalDateTime.of(expiryTimestamp.toLocalDate(), Utils.MAX_TIME);
25069 amit.gupta 1315
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
22860 ashik.ali 1316
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1317
		model.addAttribute("schemes", schemes);
1318
		return "schemes-paginated";
1319
	}
23786 amit.gupta 1320
 
23784 ashik.ali 1321
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 1322
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
30053 manish 1323
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1324
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1325
			throws ProfitMandiBusinessException {
23784 ashik.ali 1326
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1327
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1328
	}
26802 tejbeer 1329
 
26763 tejbeer 1330
	@RequestMapping(value = "/searchSchemeByCategory")
1331
	public String getSchemeByCategory(HttpServletRequest request,
30053 manish 1332
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1333
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1334
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
1335
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
1336
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
26763 tejbeer 1337
			throws ProfitMandiBusinessException {
1338
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1339
		List<Scheme> schemes = null;
1340
		long size = 0;
26802 tejbeer 1341
 
1342
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
1343
 
1344
		if (!(schemes.size() == 0)) {
1345
			size = schemeRepository.selectAllCount();
1346
			LOGGER.info("schemes" + schemes);
1347
			model.addAttribute("schemes", schemes);
1348
			model.addAttribute("start", offset + 1);
1349
			model.addAttribute("size", size);
1350
			model.addAttribute("searchTerm", searchTerm);
1351
			model.addAttribute("searchItem", searchItem);
1352
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
1353
			if (schemes.size() < limit) {
1354
				model.addAttribute("end", offset + schemes.size());
1355
			} else {
1356
				model.addAttribute("end", offset + limit);
26763 tejbeer 1357
			}
26802 tejbeer 1358
		}
1359
 
26763 tejbeer 1360
		return "schemes";
1361
	}
26802 tejbeer 1362
 
26763 tejbeer 1363
	@RequestMapping(value = "/getSchemeByCategoryPaginated")
1364
	public String getSchemeByCategoryPaginated(HttpServletRequest request,
30053 manish 1365
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1366
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1367
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
1368
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
1369
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
26763 tejbeer 1370
			throws ProfitMandiBusinessException {
1371
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1372
		LOGGER.info("In search Item....");
1373
		List<Scheme> schemes = null;
26802 tejbeer 1374
 
26763 tejbeer 1375
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
23506 amit.gupta 1376
 
26763 tejbeer 1377
		model.addAttribute("schemes", schemes);
1378
		model.addAttribute("searchItem", searchItem);
1379
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
1380
		return "schemes-paginated";
1381
	}
1382
 
23752 govind 1383
	@RequestMapping(value = "/searchScheme")
1384
	public String getSchemeBySchemeId(HttpServletRequest request,
30053 manish 1385
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1386
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1387
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
1388
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
23752 govind 1389
			throws ProfitMandiBusinessException {
1390
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1391
		List<Scheme> schemes = null;
1392
		long size = 0;
1393
		if (!(searchTerm.equals("")) && searchItem.equals("")) {
1394
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
23786 amit.gupta 1395
			if (!(schemes.size() == 0)) {
1396
				size = schemeRepository.selectAllCount();
1397
				LOGGER.info("schemes" + schemes);
1398
				model.addAttribute("schemes", schemes);
1399
				model.addAttribute("start", offset + 1);
1400
				model.addAttribute("size", size);
1401
				model.addAttribute("searchTerm", searchTerm);
1402
				model.addAttribute("searchItem", searchItem);
23914 govind 1403
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23786 amit.gupta 1404
				if (schemes.size() < limit) {
1405
					model.addAttribute("end", offset + schemes.size());
1406
				} else {
1407
					model.addAttribute("end", offset + limit);
1408
				}
23752 govind 1409
			} else {
23786 amit.gupta 1410
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
23752 govind 1411
			}
1412
		} else if (!(searchItem.equals("")) && searchTerm.equals("")) {
1413
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
23786 amit.gupta 1414
			if (!(schemeIds.size() == 0)) {
23752 govind 1415
				LOGGER.info("schemeIds in searchItemScheme" + schemeIds);
1416
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
1417
				size = schemeIds.size();
1418
				LOGGER.info("Size" + size);
1419
				model.addAttribute("schemes", schemes);
1420
				model.addAttribute("start", offset + 1);
1421
				model.addAttribute("size", size);
1422
				model.addAttribute("searchItem", searchItem);
1423
				model.addAttribute("searchTerm", searchTerm);
23914 govind 1424
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 1425
				if (schemes.size() < limit) {
1426
					model.addAttribute("end", offset + schemes.size());
1427
				} else {
1428
					model.addAttribute("end", offset + limit);
1429
				}
1430
 
1431
			} else {
1432
				throw new ProfitMandiBusinessException("SchemeIds", searchItem, "SchemeId Not Found");
1433
			}
1434
		} else {
23798 amit.gupta 1435
			if (roleManager.isAdmin(loginDetails.getRoleIds())) {
23752 govind 1436
				schemes = schemeRepository.selectAll(offset, limit);
1437
				size = schemeRepository.selectAllCount();
1438
			} else {
1439
				schemes = schemeRepository.selectActiveAll(offset, limit);
1440
				size = schemeRepository.selectAllActiveCount();
1441
			}
1442
			model.addAttribute("schemes", schemes);
1443
			model.addAttribute("start", offset + 1);
1444
			model.addAttribute("size", size);
1445
			model.addAttribute("searchItem", searchItem);
1446
			model.addAttribute("searchTerm", searchTerm);
23914 govind 1447
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 1448
			if (schemes.size() < limit) {
1449
				model.addAttribute("end", offset + schemes.size());
1450
			} else {
1451
				model.addAttribute("end", offset + limit);
1452
			}
1453
		}
1454
		return "schemes";
1455
	}
1456
 
1457
	@RequestMapping(value = "/searchItemSchemePanigated")
1458
	public String getSchemeByItemPanigated(HttpServletRequest request,
30053 manish 1459
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1460
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1461
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
23752 govind 1462
			throws ProfitMandiBusinessException {
23914 govind 1463
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23752 govind 1464
		LOGGER.info("In search Item....");
1465
		List<Scheme> schemes = null;
1466
		if (!searchItem.equals("")) {
1467
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
1468
			if (schemeIds != null) {
1469
				LOGGER.info(schemeIds);
1470
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
1471
 
1472
			}
1473
		}
1474
		model.addAttribute("schemes", schemes);
1475
		model.addAttribute("searchItem", searchItem);
23914 govind 1476
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 1477
		return "schemes-paginated";
1478
 
1479
	}
29707 tejbeer 1480
 
1481
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1482
	public String getCustomerOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1483
 
1484
		List<CustomerOffer> customerOffers = customerOfferRepository.selectAll();
1485
 
1486
		model.addAttribute("customerOffers", customerOffers);
1487
		return "customer-offer";
1488
 
1489
	}
1490
 
1491
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1492
	public String createCustomerOffer(HttpServletRequest request, @RequestParam String offerName,
30053 manish 1493
			@RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model) throws Exception {
29707 tejbeer 1494
 
1495
		CustomerOffer co = new CustomerOffer();
1496
		co.setOfferName(offerName);
1497
		co.setStartDate(startDate);
1498
		co.setEndDate(endDate);
1499
		co.setCreatedTimestamp(LocalDateTime.now());
1500
		co.setUpdatedTimestamp(LocalDateTime.now());
1501
		customerOfferRepository.persist(co);
1502
 
1503
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1504
 
1505
		return "response";
1506
 
1507
	}
1508
 
1509
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1510
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1511
		List<List<?>> rows = new ArrayList<>();
1512
 
1513
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1514
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1515
 
1516
		final HttpHeaders headers = new HttpHeaders();
1517
		headers.set("Content-Type", "text/csv");
1518
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1519
		headers.setContentLength(baos.toByteArray().length);
1520
 
1521
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1522
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1523
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1524
 
1525
	}
1526
 
1527
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1528
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
30053 manish 1529
			HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
29707 tejbeer 1530
 
1531
		List<CSVRecord> records = FileUtil.readFile(file);
1532
 
1533
		for (CSVRecord record : records) {
1534
			if (Integer.parseInt(record.get(0)) == 0) {
1535
				CustomerOfferItem coi = new CustomerOfferItem();
1536
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1537
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1538
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1539
				coi.setCustomerOfferId(offerId);
1540
				coi.setUpdatedTimestamp(LocalDateTime.now());
1541
				coi.setCreatedTimestamp(LocalDateTime.now());
1542
				customerOfferItemRepository.persist(coi);
1543
 
1544
			} else {
1545
				CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1546
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1547
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1548
				coi.setUpdatedTimestamp(LocalDateTime.now());
1549
 
1550
			}
1551
 
1552
		}
1553
 
1554
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1555
 
1556
		return "response";
1557
 
1558
	}
1559
 
1560
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1561
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1562
 
1563
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1564
		List<List<?>> rows = new ArrayList<>();
1565
 
1566
		for (CustomerOfferItem coi : cois) {
1567
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout()));
1568
 
1569
		}
1570
 
1571
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1572
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1573
 
1574
		final HttpHeaders headers = new HttpHeaders();
1575
		headers.set("Content-Type", "text/csv");
1576
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1577
		headers.setContentLength(baos.toByteArray().length);
1578
 
1579
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1580
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1581
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1582
 
1583
	}
1584
 
1585
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1586
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
30053 manish 1587
			@RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
29707 tejbeer 1588
 
1589
		CustomerOffer co = customerOfferRepository.selectById(id);
1590
		co.setEndDate(endDate);
1591
		co.setUpdatedTimestamp(LocalDateTime.now());
1592
 
1593
		model.addAttribute("co", co);
1594
 
1595
		return "customer-index-offer";
1596
 
1597
	}
1598
 
1599
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1600
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1601
 
1602
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1603
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1604
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1605
 
1606
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1607
		return "samsung-upgrade-offer";
1608
 
1609
	}
1610
 
1611
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1612
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1613
			throws ProfitMandiBusinessException {
1614
 
1615
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1616
		suo.setStatus(UpgradeOfferStatus.approved);
1617
		suo.setApprovedTimestamp(LocalDateTime.now());
1618
		model.addAttribute("suo", suo);
1619
		return "samsung-upgrade-offer-index";
1620
 
1621
	}
1622
 
1623
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1624
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1625
			throws ProfitMandiBusinessException {
1626
 
1627
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1628
		suo.setStatus(UpgradeOfferStatus.rejected);
1629
 
1630
		model.addAttribute("suo", suo);
1631
		return "samsung-upgrade-offer-index";
1632
 
1633
	}
22860 ashik.ali 1634
}