Subversion Repositories SmartDukaan

Rev

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