Subversion Repositories SmartDukaan

Rev

Rev 29926 | Rev 30043 | 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;
29927 amit.gupta 6
import com.spice.profitmandi.common.model.*;
29585 manish 7
import com.spice.profitmandi.common.services.ReporticoService;
29927 amit.gupta 8
import com.spice.profitmandi.common.util.*;
23784 ashik.ali 9
import com.spice.profitmandi.common.web.util.ResponseSender;
29927 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;
27876 amit.gupta 19
import com.spice.profitmandi.dao.model.CreateOfferRequest;
25505 amit.gupta 20
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
29927 amit.gupta 21
import com.spice.profitmandi.dao.repository.catalog.*;
29899 tejbeer 22
import com.spice.profitmandi.dao.repository.cs.CsService;
26588 tejbeer 23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24
import com.spice.profitmandi.dao.repository.dtr.Mongo;
29927 amit.gupta 25
import com.spice.profitmandi.dao.repository.fofo.*;
28795 tejbeer 26
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
27
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
23798 amit.gupta 28
import com.spice.profitmandi.service.authentication.RoleManager;
23020 ashik.ali 29
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 30
import com.spice.profitmandi.service.offers.OfferService;
22860 ashik.ali 31
import com.spice.profitmandi.service.scheme.SchemeService;
26588 tejbeer 32
import com.spice.profitmandi.service.user.RetailerService;
29585 manish 33
import com.spice.profitmandi.service.wallet.WalletService;
22860 ashik.ali 34
import com.spice.profitmandi.web.model.LoginDetails;
35
import com.spice.profitmandi.web.util.CookiesProcessor;
23570 amit.gupta 36
import com.spice.profitmandi.web.util.MVCResponseSender;
29585 manish 37
import in.shop2020.model.v1.order.WalletReferenceType;
29927 amit.gupta 38
import org.apache.commons.csv.CSVRecord;
39
import org.apache.logging.log4j.LogManager;
40
import org.apache.logging.log4j.Logger;
41
import org.springframework.beans.factory.annotation.Autowired;
42
import org.springframework.beans.factory.annotation.Qualifier;
43
import org.springframework.core.io.InputStreamResource;
44
import org.springframework.http.HttpHeaders;
45
import org.springframework.http.HttpStatus;
46
import org.springframework.http.ResponseEntity;
47
import org.springframework.stereotype.Controller;
48
import org.springframework.ui.Model;
49
import org.springframework.web.bind.annotation.*;
50
import org.springframework.web.multipart.MultipartFile;
29585 manish 51
 
29927 amit.gupta 52
import javax.servlet.http.HttpServletRequest;
53
import javax.servlet.http.HttpServletResponse;
54
import javax.transaction.Transactional;
55
import java.io.ByteArrayInputStream;
56
import java.io.ByteArrayOutputStream;
57
import java.io.InputStream;
58
import java.time.*;
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,
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
 
23914 govind 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,
522
			@RequestParam(name = "offset", defaultValue = "0") int offset,
23752 govind 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,
27876 amit.gupta 560
			@RequestParam(required = false) LocalDate date,
23752 govind 561
			@RequestParam(name = "limit", defaultValue = "10") int limit,
27897 amit.gupta 562
			@RequestParam(name = "searchItem", required = false, defaultValue = "0") int searchItem,
26802 tejbeer 563
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
564
			@RequestParam(name = "partnerType", required = false, defaultValue = "") PartnerType partnerType,
28795 tejbeer 565
			@RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
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
				}
27612 tejbeer 608
			}
609
 
610
			else {
26802 tejbeer 611
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
612
			}
27612 tejbeer 613
		}
614
 
27897 amit.gupta 615
		else if (searchItem > 0) {
27394 amit.gupta 616
			TagListing tagListing = null;
28134 tejbeer 617
			tagListing = tagListingRepository.selectByItemId(searchItem);
28492 amit.gupta 618
			Item item = itemRepository.selectById(searchItem);
28134 tejbeer 619
			if (tagListing != null) {
620
				model.addAttribute("dp", tagListing.getSellingPrice());
621
				model.addAttribute("mop", tagListing.getMop());
26802 tejbeer 622
			}
29707 tejbeer 623
			schemes = schemeService.selectSchemeByPartnerType(partnerType, date, searchItem, isAdmin, offset, limit)
624
					.stream().filter(x -> {
625
						return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
626
					}).collect(Collectors.toList());
627
			// Remove 411 and 612
29658 amit.gupta 628
			model.addAttribute("schemes", schemes);
27612 tejbeer 629
			if (schemes.size() == 0) {
28795 tejbeer 630
				if (isAdmin)
631
					return "schemes";
632
				else {
27612 tejbeer 633
 
28795 tejbeer 634
					return "schemes-partner";
27389 amit.gupta 635
				}
636
			}
28795 tejbeer 637
			// For 7720(HR) remove investment
638
			int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing, searchItem);
27897 amit.gupta 639
			size = schemeService.selectSchemeCount(partnerType, date, searchItem, isAdmin);
26802 tejbeer 640
			model.addAttribute("start", offset + 1);
641
			model.addAttribute("size", size);
642
			if (schemes.size() < limit) {
643
				model.addAttribute("end", offset + schemes.size());
644
			} else {
645
				model.addAttribute("end", offset + limit);
646
			}
28547 amit.gupta 647
			model.addAttribute("nlc", Math.round(nlc));
28795 tejbeer 648
		} else if (!(searchImei.equals(""))) {
649
 
650
			LOGGER.info("searchImei" + searchImei);
651
 
652
			InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
653
					loginDetails.getFofoId());
28802 tejbeer 654
			Item item = itemRepository.selectById(inventoryItem.getItemId());
28795 tejbeer 655
			Map<Integer, Scheme> schemeMap = new HashMap<>();
656
			if (inventoryItem != null) {
657
 
658
				LOGGER.info("inventoryItem" + inventoryItem);
659
 
660
				schemeInOut = schemeInOutRepository
661
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
662
 
663
				LOGGER.info("schemeInOut" + schemeInOut);
664
 
665
				if (!schemeInOut.isEmpty()) {
666
 
667
					List<Integer> schemeIds = schemeInOut.stream().map(x -> x.getSchemeId())
668
							.collect(Collectors.toList());
669
 
670
					schemes = schemeRepository.selectBySchemeIds(schemeIds);
671
					for (Scheme scheme : schemes) {
672
						if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
673
							scheme.setAmountModel(scheme.getAmount() + "%");
674
						} else {
675
							scheme.setAmountModel(scheme.getAmount() + "");
676
						}
677
					}
678
 
679
					schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
680
				}
681
			}
682
 
683
			model.addAttribute("schemeMap", schemeMap);
28802 tejbeer 684
			model.addAttribute("item", item);
28795 tejbeer 685
 
28796 tejbeer 686
		}
687
		model.addAttribute("schemeInOut", schemeInOut);
28795 tejbeer 688
 
27876 amit.gupta 689
		model.addAttribute("searchItem", searchItem);
690
		model.addAttribute("searchTerm", searchTerm);
691
		model.addAttribute("partnerType", partnerType);
692
		model.addAttribute("isAdmin", isAdmin);
29650 amit.gupta 693
		LOGGER.info("schemes" + schemes);
29707 tejbeer 694
		model.addAttribute("schemes", schemes != null ? schemes.stream().filter(x -> {
695
			return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
29651 amit.gupta 696
		}).collect(Collectors.toList()) : null);
27876 amit.gupta 697
		LOGGER.info("schemes" + schemes);
23786 amit.gupta 698
		// model.addAttribute("roleTypes", loginDetails.getRoleTypes());
29899 tejbeer 699
		if (isAdmin) {
700
 
701
			boolean fullAccess = this.getAccess(loginDetails.getEmailId());
702
 
703
			model.addAttribute("fullAccess", fullAccess);
704
 
27876 amit.gupta 705
			return "schemes";
29899 tejbeer 706
		} else {
27897 amit.gupta 707
			List<CreateOfferRequest> offers = new ArrayList<>();
29883 amit.gupta 708
			Map<Integer, Map<Integer, Long>> offerSlabPayoutMap = new HashMap<>();
28795 tejbeer 709
			List<PriceDropIMEI> priceDropImeis = new ArrayList<>();
28134 tejbeer 710
			if (searchItem > 0) {
27897 amit.gupta 711
				offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(), searchItem);
29899 tejbeer 712
				for (CreateOfferRequest createOfferRequest : offers) {
713
					Map<Integer, Map<Integer, Long>> itemSlabPayoutMap = offerService
714
							.getSlabPayoutMap(createOfferRequest);
715
					Map<Integer, Long> slabPayoutMap = itemSlabPayoutMap.get(searchItem);
29883 amit.gupta 716
					offerSlabPayoutMap.put(createOfferRequest.getId(), slabPayoutMap);
717
				}
27897 amit.gupta 718
			}
28795 tejbeer 719
			if (!(searchImei.equals(""))) {
720
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
721
						loginDetails.getFofoId());
722
 
723
				priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
724
				for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
725
					int priceDropId = priceDropIMEI.getPriceDropId();
726
					PriceDrop pd = priceDropRepository.selectById(priceDropId);
727
 
728
					priceDropIMEI.setPriceDrop(pd);
729
				}
730
			}
28136 tejbeer 731
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
732
 
27876 amit.gupta 733
			model.addAttribute("offers", offers);
29883 amit.gupta 734
			model.addAttribute("offerSlabPayoutMap", offerSlabPayoutMap);
28136 tejbeer 735
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 736
			model.addAttribute("fofoId", fs.getId());
737
			model.addAttribute("priceDropImeis", priceDropImeis);
27876 amit.gupta 738
			return "schemes-partner";
739
		}
29899 tejbeer 740
 
22860 ashik.ali 741
	}
23786 amit.gupta 742
 
28795 tejbeer 743
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing, int itemId)
744
			throws ProfitMandiBusinessException {
745
 
746
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
747
				.filter(x -> x.getId() == fofoId).count() > 0) {
748
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
749
					.collect(Collectors.toList());
750
		}
751
		float nlc = tagListing.getSellingPrice();
752
		for (Scheme scheme : schemes) {
753
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
754
				if (tagListing != null) {
755
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
756
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
757
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
758
					scheme.setAmountModel(
29927 amit.gupta 759
							FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
28795 tejbeer 760
					nlc -= amount;
761
				}
762
 
763
				else {
764
					scheme.setAmountModel(scheme.getAmount() + "%");
765
				}
766
			} else {
767
				scheme.setAmountModel(scheme.getAmount() + "");
768
				nlc -= scheme.getAmount();
769
			}
770
		}
771
 
772
		return Math.round(nlc);
773
 
774
	}
775
 
22860 ashik.ali 776
	@RequestMapping(value = "/getPaginatedSchemes", method = RequestMethod.GET)
27876 amit.gupta 777
	public String getPaginatedSchemes(HttpServletRequest request, @RequestParam(required = false) LocalDate date,
23786 amit.gupta 778
			@RequestParam(name = "offset", defaultValue = "0") int offset,
26802 tejbeer 779
			@RequestParam(name = "limit", defaultValue = "10") int limit,
27876 amit.gupta 780
			@RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
26802 tejbeer 781
			Model model) throws ProfitMandiBusinessException {
782
 
23343 ashik.ali 783
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 784
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 785
		if (date == null) {
786
			date = LocalDate.now();
787
		}
23271 ashik.ali 788
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
27876 amit.gupta 789
		List<Scheme> schemes = schemeRepository.selectAll();
26802 tejbeer 790
		int itemId = 0;
27394 amit.gupta 791
		TagListing tagListing = null;
27897 amit.gupta 792
 
27612 tejbeer 793
		for (Scheme scheme : schemes) {
794
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
795
				if (itemId > 0) {
27394 amit.gupta 796
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
797
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
798
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
27612 tejbeer 799
					scheme.setAmountModel(
29927 amit.gupta 800
							FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
27394 amit.gupta 801
				} else {
802
					scheme.setAmountModel(scheme.getAmount() + "%");
803
				}
804
			} else {
27876 amit.gupta 805
				scheme.setAmountModel("" + scheme.getAmount());
27394 amit.gupta 806
			}
807
		}
26802 tejbeer 808
 
22860 ashik.ali 809
		model.addAttribute("schemes", schemes);
26912 tejbeer 810
		model.addAttribute("partnerType", partnerType);
23914 govind 811
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 812
		return "schemes-paginated";
813
	}
23786 amit.gupta 814
 
23020 ashik.ali 815
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 816
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 817
		return "schemes-download";
818
	}
23786 amit.gupta 819
 
23020 ashik.ali 820
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 821
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
23914 govind 822
			@RequestParam(name = ProfitMandiConstants.START_DATE_TIME) String startDateTimeString,
823
			@RequestParam(name = ProfitMandiConstants.END_DATE_TIME) String endDateTimeString, Model model)
23786 amit.gupta 824
			throws ProfitMandiBusinessException {
23914 govind 825
		LocalDateTime startDateTime = StringUtils.toDateTime(startDateTimeString,
24406 amit.gupta 826
				DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
827
		LocalDateTime endDateTime = StringUtils.toDateTime(endDateTimeString, DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
23914 govind 828
 
23020 ashik.ali 829
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 830
 
23020 ashik.ali 831
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
832
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 833
 
834
		final HttpHeaders headers = new HttpHeaders();
835
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 836
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 837
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
838
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
839
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
840
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 841
	}
23786 amit.gupta 842
 
22860 ashik.ali 843
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 844
	public String getSchemeById(HttpServletRequest request,
845
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
846
			throws ProfitMandiBusinessException {
23343 ashik.ali 847
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29899 tejbeer 848
 
849
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
22860 ashik.ali 850
		Scheme scheme = schemeService.getSchemeById(schemeId);
29899 tejbeer 851
		model.addAttribute("fullAccess", fullAccess);
22860 ashik.ali 852
		model.addAttribute("scheme", scheme);
24445 amit.gupta 853
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 854
		return "scheme-details";
23914 govind 855
 
22860 ashik.ali 856
	}
23786 amit.gupta 857
 
22860 ashik.ali 858
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 859
	public String activeSchemeById(HttpServletRequest request,
860
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
861
			@RequestParam(name = "offset", defaultValue = "0") int offset,
862
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
863
			throws ProfitMandiBusinessException {
22860 ashik.ali 864
		schemeService.activeSchemeById(schemeId);
865
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
866
		model.addAttribute("schemes", schemes);
867
		return "schemes-paginated";
868
	}
23786 amit.gupta 869
 
22860 ashik.ali 870
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 871
	public String expireSchemeById(HttpServletRequest request,
872
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
25069 amit.gupta 873
			@RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp,
23786 amit.gupta 874
			@RequestParam(name = "offset", defaultValue = "0") int offset,
875
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
876
			throws ProfitMandiBusinessException {
28924 amit.gupta 877
		expiryTimestamp = LocalDateTime.of(expiryTimestamp.toLocalDate(), Utils.MAX_TIME);
25069 amit.gupta 878
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
22860 ashik.ali 879
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
880
		model.addAttribute("schemes", schemes);
881
		return "schemes-paginated";
882
	}
23786 amit.gupta 883
 
23784 ashik.ali 884
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 885
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
886
			@RequestParam(name = "offset", defaultValue = "0") int offset,
887
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
888
			throws ProfitMandiBusinessException {
23784 ashik.ali 889
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
890
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
891
	}
26802 tejbeer 892
 
26763 tejbeer 893
	@RequestMapping(value = "/searchSchemeByCategory")
894
	public String getSchemeByCategory(HttpServletRequest request,
895
			@RequestParam(name = "offset", defaultValue = "0") int offset,
896
			@RequestParam(name = "limit", defaultValue = "10") int limit,
897
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
898
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
899
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
900
			throws ProfitMandiBusinessException {
901
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
902
		List<Scheme> schemes = null;
903
		long size = 0;
26802 tejbeer 904
 
905
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
906
 
907
		if (!(schemes.size() == 0)) {
908
			size = schemeRepository.selectAllCount();
909
			LOGGER.info("schemes" + schemes);
910
			model.addAttribute("schemes", schemes);
911
			model.addAttribute("start", offset + 1);
912
			model.addAttribute("size", size);
913
			model.addAttribute("searchTerm", searchTerm);
914
			model.addAttribute("searchItem", searchItem);
915
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
916
			if (schemes.size() < limit) {
917
				model.addAttribute("end", offset + schemes.size());
918
			} else {
919
				model.addAttribute("end", offset + limit);
26763 tejbeer 920
			}
26802 tejbeer 921
		}
922
 
26763 tejbeer 923
		return "schemes";
924
	}
26802 tejbeer 925
 
26763 tejbeer 926
	@RequestMapping(value = "/getSchemeByCategoryPaginated")
927
	public String getSchemeByCategoryPaginated(HttpServletRequest request,
928
			@RequestParam(name = "offset", defaultValue = "0") int offset,
929
			@RequestParam(name = "limit", defaultValue = "10") int limit,
930
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
931
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
932
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
933
			throws ProfitMandiBusinessException {
934
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
935
		LOGGER.info("In search Item....");
936
		List<Scheme> schemes = null;
26802 tejbeer 937
 
26763 tejbeer 938
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
23506 amit.gupta 939
 
26763 tejbeer 940
		model.addAttribute("schemes", schemes);
941
		model.addAttribute("searchItem", searchItem);
942
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
943
		return "schemes-paginated";
944
	}
945
 
23752 govind 946
	@RequestMapping(value = "/searchScheme")
947
	public String getSchemeBySchemeId(HttpServletRequest request,
948
			@RequestParam(name = "offset", defaultValue = "0") int offset,
949
			@RequestParam(name = "limit", defaultValue = "10") int limit,
950
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
951
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
952
			throws ProfitMandiBusinessException {
953
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
954
		List<Scheme> schemes = null;
955
		long size = 0;
956
		if (!(searchTerm.equals("")) && searchItem.equals("")) {
957
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
23786 amit.gupta 958
			if (!(schemes.size() == 0)) {
959
				size = schemeRepository.selectAllCount();
960
				LOGGER.info("schemes" + schemes);
961
				model.addAttribute("schemes", schemes);
962
				model.addAttribute("start", offset + 1);
963
				model.addAttribute("size", size);
964
				model.addAttribute("searchTerm", searchTerm);
965
				model.addAttribute("searchItem", searchItem);
23914 govind 966
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23786 amit.gupta 967
				if (schemes.size() < limit) {
968
					model.addAttribute("end", offset + schemes.size());
969
				} else {
970
					model.addAttribute("end", offset + limit);
971
				}
23752 govind 972
			} else {
23786 amit.gupta 973
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
23752 govind 974
			}
975
		} else if (!(searchItem.equals("")) && searchTerm.equals("")) {
976
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
23786 amit.gupta 977
			if (!(schemeIds.size() == 0)) {
23752 govind 978
				LOGGER.info("schemeIds in searchItemScheme" + schemeIds);
979
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
980
				size = schemeIds.size();
981
				LOGGER.info("Size" + size);
982
				model.addAttribute("schemes", schemes);
983
				model.addAttribute("start", offset + 1);
984
				model.addAttribute("size", size);
985
				model.addAttribute("searchItem", searchItem);
986
				model.addAttribute("searchTerm", searchTerm);
23914 govind 987
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 988
				if (schemes.size() < limit) {
989
					model.addAttribute("end", offset + schemes.size());
990
				} else {
991
					model.addAttribute("end", offset + limit);
992
				}
993
 
994
			} else {
995
				throw new ProfitMandiBusinessException("SchemeIds", searchItem, "SchemeId Not Found");
996
			}
997
		} else {
23798 amit.gupta 998
			if (roleManager.isAdmin(loginDetails.getRoleIds())) {
23752 govind 999
				schemes = schemeRepository.selectAll(offset, limit);
1000
				size = schemeRepository.selectAllCount();
1001
			} else {
1002
				schemes = schemeRepository.selectActiveAll(offset, limit);
1003
				size = schemeRepository.selectAllActiveCount();
1004
			}
1005
			model.addAttribute("schemes", schemes);
1006
			model.addAttribute("start", offset + 1);
1007
			model.addAttribute("size", size);
1008
			model.addAttribute("searchItem", searchItem);
1009
			model.addAttribute("searchTerm", searchTerm);
23914 govind 1010
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 1011
			if (schemes.size() < limit) {
1012
				model.addAttribute("end", offset + schemes.size());
1013
			} else {
1014
				model.addAttribute("end", offset + limit);
1015
			}
1016
		}
1017
		return "schemes";
1018
	}
1019
 
1020
	@RequestMapping(value = "/searchItemSchemePanigated")
1021
	public String getSchemeByItemPanigated(HttpServletRequest request,
1022
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1023
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1024
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
1025
			throws ProfitMandiBusinessException {
23914 govind 1026
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23752 govind 1027
		LOGGER.info("In search Item....");
1028
		List<Scheme> schemes = null;
1029
		if (!searchItem.equals("")) {
1030
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
1031
			if (schemeIds != null) {
1032
				LOGGER.info(schemeIds);
1033
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
1034
 
1035
			}
1036
		}
1037
		model.addAttribute("schemes", schemes);
1038
		model.addAttribute("searchItem", searchItem);
23914 govind 1039
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 1040
		return "schemes-paginated";
1041
 
1042
	}
29707 tejbeer 1043
 
1044
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1045
	public String getCustomerOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1046
 
1047
		List<CustomerOffer> customerOffers = customerOfferRepository.selectAll();
1048
 
1049
		model.addAttribute("customerOffers", customerOffers);
1050
		return "customer-offer";
1051
 
1052
	}
1053
 
1054
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1055
	public String createCustomerOffer(HttpServletRequest request, @RequestParam String offerName,
1056
			@RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model) throws Exception {
1057
 
1058
		CustomerOffer co = new CustomerOffer();
1059
		co.setOfferName(offerName);
1060
		co.setStartDate(startDate);
1061
		co.setEndDate(endDate);
1062
		co.setCreatedTimestamp(LocalDateTime.now());
1063
		co.setUpdatedTimestamp(LocalDateTime.now());
1064
		customerOfferRepository.persist(co);
1065
 
1066
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1067
 
1068
		return "response";
1069
 
1070
	}
1071
 
1072
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1073
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1074
		List<List<?>> rows = new ArrayList<>();
1075
 
1076
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1077
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1078
 
1079
		final HttpHeaders headers = new HttpHeaders();
1080
		headers.set("Content-Type", "text/csv");
1081
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1082
		headers.setContentLength(baos.toByteArray().length);
1083
 
1084
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1085
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1086
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1087
 
1088
	}
1089
 
1090
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1091
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1092
			HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
1093
 
1094
		List<CSVRecord> records = FileUtil.readFile(file);
1095
 
1096
		for (CSVRecord record : records) {
1097
			if (Integer.parseInt(record.get(0)) == 0) {
1098
				CustomerOfferItem coi = new CustomerOfferItem();
1099
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1100
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1101
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1102
				coi.setCustomerOfferId(offerId);
1103
				coi.setUpdatedTimestamp(LocalDateTime.now());
1104
				coi.setCreatedTimestamp(LocalDateTime.now());
1105
				customerOfferItemRepository.persist(coi);
1106
 
1107
			} else {
1108
				CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1109
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1110
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1111
				coi.setUpdatedTimestamp(LocalDateTime.now());
1112
 
1113
			}
1114
 
1115
		}
1116
 
1117
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1118
 
1119
		return "response";
1120
 
1121
	}
1122
 
1123
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1124
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1125
 
1126
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1127
		List<List<?>> rows = new ArrayList<>();
1128
 
1129
		for (CustomerOfferItem coi : cois) {
1130
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout()));
1131
 
1132
		}
1133
 
1134
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1135
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1136
 
1137
		final HttpHeaders headers = new HttpHeaders();
1138
		headers.set("Content-Type", "text/csv");
1139
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1140
		headers.setContentLength(baos.toByteArray().length);
1141
 
1142
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1143
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1144
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1145
 
1146
	}
1147
 
1148
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1149
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1150
			@RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
1151
 
1152
		CustomerOffer co = customerOfferRepository.selectById(id);
1153
		co.setEndDate(endDate);
1154
		co.setUpdatedTimestamp(LocalDateTime.now());
1155
 
1156
		model.addAttribute("co", co);
1157
 
1158
		return "customer-index-offer";
1159
 
1160
	}
1161
 
1162
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1163
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1164
 
1165
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1166
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1167
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1168
 
1169
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1170
		return "samsung-upgrade-offer";
1171
 
1172
	}
1173
 
1174
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1175
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1176
			throws ProfitMandiBusinessException {
1177
 
1178
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1179
		suo.setStatus(UpgradeOfferStatus.approved);
1180
		suo.setApprovedTimestamp(LocalDateTime.now());
1181
		model.addAttribute("suo", suo);
1182
		return "samsung-upgrade-offer-index";
1183
 
1184
	}
1185
 
1186
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1187
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1188
			throws ProfitMandiBusinessException {
1189
 
1190
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1191
		suo.setStatus(UpgradeOfferStatus.rejected);
1192
 
1193
		model.addAttribute("suo", suo);
1194
		return "samsung-upgrade-offer-index";
1195
 
1196
	}
1197
 
22860 ashik.ali 1198
}