Subversion Repositories SmartDukaan

Rev

Rev 31170 | Rev 31281 | 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
 
31147 tejbeer 3
import com.google.gson.Gson;
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;
30326 amit.gupta 11
import com.spice.profitmandi.common.util.ExcelUtils;
12
import com.spice.profitmandi.common.util.FileUtil;
13
import com.spice.profitmandi.common.util.FormattingUtils;
23784 ashik.ali 14
import com.spice.profitmandi.common.web.util.ResponseSender;
31170 amit.gupta 15
import com.spice.profitmandi.dao.entity.catalog.*;
16
import com.spice.profitmandi.dao.entity.cs.Region;
17
import com.spice.profitmandi.dao.entity.fofo.*;
28795 tejbeer 18
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
19
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
27389 amit.gupta 20
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
28491 amit.gupta 21
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
29707 tejbeer 22
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
29899 tejbeer 23
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
29585 manish 24
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
31170 amit.gupta 25
import com.spice.profitmandi.dao.model.*;
26
import com.spice.profitmandi.dao.repository.catalog.*;
29899 tejbeer 27
import com.spice.profitmandi.dao.repository.cs.CsService;
31170 amit.gupta 28
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
26588 tejbeer 29
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
30
import com.spice.profitmandi.dao.repository.dtr.Mongo;
31170 amit.gupta 31
import com.spice.profitmandi.dao.repository.fofo.*;
28795 tejbeer 32
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
33
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
30768 amit.gupta 34
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
23798 amit.gupta 35
import com.spice.profitmandi.service.authentication.RoleManager;
23020 ashik.ali 36
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 37
import com.spice.profitmandi.service.offers.OfferService;
31147 tejbeer 38
import com.spice.profitmandi.service.offers.PartnerCriteria;
22860 ashik.ali 39
import com.spice.profitmandi.service.scheme.SchemeService;
26588 tejbeer 40
import com.spice.profitmandi.service.user.RetailerService;
29585 manish 41
import com.spice.profitmandi.service.wallet.WalletService;
22860 ashik.ali 42
import com.spice.profitmandi.web.model.LoginDetails;
43
import com.spice.profitmandi.web.util.CookiesProcessor;
23570 amit.gupta 44
import com.spice.profitmandi.web.util.MVCResponseSender;
29585 manish 45
import in.shop2020.model.v1.order.WalletReferenceType;
31170 amit.gupta 46
import org.apache.commons.csv.CSVRecord;
47
import org.apache.commons.lang.StringUtils;
48
import org.apache.logging.log4j.LogManager;
49
import org.apache.logging.log4j.Logger;
50
import org.springframework.beans.factory.annotation.Autowired;
51
import org.springframework.beans.factory.annotation.Qualifier;
52
import org.springframework.core.io.InputStreamResource;
53
import org.springframework.http.HttpHeaders;
54
import org.springframework.http.HttpStatus;
55
import org.springframework.http.ResponseEntity;
56
import org.springframework.stereotype.Controller;
57
import org.springframework.ui.Model;
58
import org.springframework.web.bind.annotation.*;
59
import org.springframework.web.multipart.MultipartFile;
29585 manish 60
 
31170 amit.gupta 61
import javax.servlet.http.HttpServletRequest;
62
import javax.servlet.http.HttpServletResponse;
63
import javax.transaction.Transactional;
64
import java.io.ByteArrayInputStream;
65
import java.io.ByteArrayOutputStream;
66
import java.io.InputStream;
67
import java.time.*;
68
import java.time.format.DateTimeFormatter;
69
import java.util.*;
70
import java.util.stream.Collectors;
71
 
22860 ashik.ali 72
@Controller
25369 amit.gupta 73
@Transactional(rollbackOn = Throwable.class)
22860 ashik.ali 74
public class SchemeController {
30564 tejbeer 75
	// LED TV
76
	private static final List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.MOBILE_CATEGORY_ID,
77
			ProfitMandiConstants.TABLET_CATEGORY_ID, 14202);
22860 ashik.ali 78
 
23568 govind 79
	private static final Logger LOGGER = LogManager.getLogger(SchemeController.class);
22860 ashik.ali 80
 
81
	@Autowired
22927 ashik.ali 82
	private SchemeService schemeService;
27897 amit.gupta 83
 
27876 amit.gupta 84
	@Autowired
85
	private OfferService offerService;
23786 amit.gupta 86
 
22860 ashik.ali 87
	@Autowired
27389 amit.gupta 88
	private StateGstRateRepository stateGstRateRepository;
27612 tejbeer 89
 
27389 amit.gupta 90
	@Autowired
27416 amit.gupta 91
	private ItemRepository itemRepository;
29608 amit.gupta 92
 
29585 manish 93
	@Autowired
94
	private ReporticoService reporticoService;
27612 tejbeer 95
 
27416 amit.gupta 96
	@Autowired
22927 ashik.ali 97
	private SchemeRepository schemeRepository;
22860 ashik.ali 98
 
99
	@Autowired
23556 amit.gupta 100
	private SchemeItemRepository schemeItemRepository;
23786 amit.gupta 101
 
23556 amit.gupta 102
	@Autowired
23570 amit.gupta 103
	private MVCResponseSender mvcResponseSender;
23786 amit.gupta 104
 
23570 amit.gupta 105
	@Autowired
22927 ashik.ali 106
	private CookiesProcessor cookiesProcessor;
23786 amit.gupta 107
 
23020 ashik.ali 108
	@Autowired
23784 ashik.ali 109
	@Qualifier("fofoInventoryService")
23020 ashik.ali 110
	private InventoryService inventoryService;
23556 amit.gupta 111
 
112
	@Autowired
113
	private TagListingRepository tagListingRepository;
23914 govind 114
 
23798 amit.gupta 115
	@Autowired
116
	private RoleManager roleManager;
23786 amit.gupta 117
 
23506 amit.gupta 118
	@Autowired
27394 amit.gupta 119
	private ResponseSender<?> responseSender;
23786 amit.gupta 120
 
23784 ashik.ali 121
	@Autowired
27394 amit.gupta 122
	private FofoStoreRepository fofoStoreRepository;
23786 amit.gupta 123
 
23784 ashik.ali 124
	@Autowired
30651 amit.gupta 125
	private OfferPayoutRepository offerPayoutRepository;
126
 
127
	@Autowired
27394 amit.gupta 128
	private RetailerService retailerService;
22860 ashik.ali 129
 
27394 amit.gupta 130
	@Autowired
131
	private Mongo mongoClient;
29608 amit.gupta 132
 
29585 manish 133
	@Autowired
134
	WalletService walletService;
26588 tejbeer 135
 
136
	@Autowired
29585 manish 137
	PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
138
 
139
	@Autowired
26674 tejbeer 140
	private PartnerTypeChangeService partnerTypeChangeService;
141
 
28795 tejbeer 142
	@Autowired
143
	InventoryItemRepository inventoryItemRepository;
144
 
145
	@Autowired
146
	PriceDropIMEIRepository priceDropIMEIRepository;
147
 
148
	@Autowired
149
	PriceDropRepository priceDropRepository;
150
 
151
	@Autowired
152
	SchemeInOutRepository schemeInOutRepository;
153
 
29707 tejbeer 154
	@Autowired
155
	private CustomerOfferRepository customerOfferRepository;
156
 
157
	@Autowired
158
	private CustomerOfferItemRepository customerOfferItemRepository;
159
 
160
	@Autowired
161
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
162
 
29899 tejbeer 163
	@Autowired
164
	private CsService csService;
165
 
30494 amit.gupta 166
	@Autowired
167
	private CategoryRepository categoryRepository;
168
 
31147 tejbeer 169
	@Autowired
170
	private Gson gson;
171
 
29899 tejbeer 172
	List<String> adminEmail = Arrays.asList("tarun.verma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
30831 tejbeer 173
			"amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com", "raksha.vyas@smartdukaan.com");
29899 tejbeer 174
 
31170 amit.gupta 175
	@Autowired
176
	SchemeRegionRepository schemeRegionRepository;
29608 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
 
31170 amit.gupta 201
	@Autowired
202
	RegionRepository regionRepository;
23914 govind 203
 
30494 amit.gupta 204
	@RequestMapping(value = "/getBrandsByCategory", method = RequestMethod.GET)
30564 tejbeer 205
	public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId, Model model)
206
			throws Exception {
207
		Set<String> brands = inventoryService.getAllTagListingBrands(categoryId);
30494 amit.gupta 208
		model.addAttribute("brands", brands);
30499 amit.gupta 209
		model.addAttribute("categoryId", categoryId);
30494 amit.gupta 210
 
211
		return "tag-listing-brands";
212
	}
213
 
23556 amit.gupta 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
 
30768 amit.gupta 223
	@Autowired
224
	TransactionRepository transactionRepository;
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))
30831 tejbeer 258
					.flatMap(List::stream)
259
					.filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING) && x.getRolledBackTimestamp() == null)
260
					.collect(Collectors.toList());
29585 manish 261
			float totalAmount = 0;
30768 amit.gupta 262
			LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
30831 tejbeer 263
			boolean sameYearMonth = firstBillingDate.getMonth() == startOfPreviousMonth.getMonth()
264
					&& firstBillingDate.getYear() == startOfPreviousMonth.getYear();
29608 amit.gupta 265
			for (SchemeInOut sio : schemeInouts) {
30768 amit.gupta 266
				if (sameYearMonth) {
267
					sio.setStatusDescription("Investment payout fully disbursed for first month");
29585 manish 268
					sio.setStatus(SchemePayoutStatus.CREDITED);
269
					sio.setCreditTimestamp(LocalDateTime.now());
270
					totalAmount += sio.getAmount();
271
				} else {
30768 amit.gupta 272
					if (investmentMaintainedDays < 8) {
273
						sio.setStatus(SchemePayoutStatus.REJECTED);
30831 tejbeer 274
						// sio.setRolledBackTimestamp(LocalDateTime.now());
275
						sio.setStatusDescription(
276
								"Investment maintained for " + investmentMaintainedDays + "(< 8) days");
30768 amit.gupta 277
					} else if (investmentMaintainedDays < 12) {
278
						sio.setStatus(SchemePayoutStatus.CREDITED);
279
						sio.setAmount(sio.getAmount() / 2);
280
						sio.setCreditTimestamp(LocalDateTime.now());
30831 tejbeer 281
						sio.setStatusDescription(
282
								"Investment maintained for " + investmentMaintainedDays + "(< 12) days");
30768 amit.gupta 283
						totalAmount += sio.getAmount();
284
					} else {
285
						sio.setStatus(SchemePayoutStatus.CREDITED);
286
						sio.setCreditTimestamp(LocalDateTime.now());
287
						totalAmount += sio.getAmount();
288
					}
29585 manish 289
				}
290
			}
29608 amit.gupta 291
			if (totalAmount > 0) {
292
				String description = "Investment margin paid for "
293
						+ FormattingUtils.formatYearMonth(startOfPreviousMonth.atStartOfDay());
294
				if (investmentMaintainedDays < 12) {
295
					description += ", as maintained for " + investmentMaintainedDays + "(< 12) days";
29585 manish 296
				}
29608 amit.gupta 297
				walletService.addAmountToWallet(fofoId, referenceId, WalletReferenceType.INVESTMENT_PAYOUT, description,
298
						totalAmount, lastOfPreviousMonth.atTime(LocalTime.MAX));
29585 manish 299
			}
30831 tejbeer 300
			// Its ok to process Margins Pending for activation
30768 amit.gupta 301
			schemeService.processActivation();
29585 manish 302
			System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
303
		}
29608 amit.gupta 304
 
29585 manish 305
	}
29608 amit.gupta 306
 
29585 manish 307
	@RequestMapping(value = "/evaluateActualInvestmentPayout", method = RequestMethod.GET)
29663 manish 308
	public ResponseEntity<?> evaluateActualInvestmentPayout(HttpServletRequest request, Model model) throws Exception {
309
 
310
		List<List<?>> rows = new ArrayList<>();
311
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
312
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
313
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
314
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
315
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
316
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
317
				.filter(x -> x.getShortPercentage() <= 10)
318
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
319
		LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
320
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
321
				startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
322
		Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
323
				.collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
324
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
325
		Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
326
				Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
327
		System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
328
		for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
329
			int fofoId = retailerEntry.getKey();
330
			List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
331
					.flatMap(List::stream).collect(Collectors.toList());
332
			double totalAmount = schemeInouts.stream().filter(x -> x.getRolledBackTimestamp() == null)
333
					.collect(Collectors.summingDouble(x -> x.getAmount()));
334
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
335
					: investmentMaintainedDaysMap.get(fofoId);
336
			if (investmentMaintainedDays < 8) {
337
				totalAmount = 0;
338
			} else if (investmentMaintainedDays < 12) {
339
				totalAmount = totalAmount / 2;
29585 manish 340
			}
29663 manish 341
			System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
342
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
29608 amit.gupta 343
 
29663 manish 344
			rows.add(Arrays.asList(fofoId, customRetailer.getBusinessName(), customRetailer.getCode(),
345
					investmentMaintainedDays, totalAmount));
29585 manish 346
		}
347
 
29663 manish 348
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
349
				Arrays.asList("fofoId", "Name", "Code", "investmentMaintainedDays", "totalAmount"), rows);
350
 
351
		final HttpHeaders headers = new HttpHeaders();
352
		headers.set("Content-Type", "text/csv");
353
		headers.set("Content-disposition", "inline; filename=investmentMaintainedDays.csv");
354
		headers.setContentLength(baos.toByteArray().length);
355
 
356
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
357
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
358
 
359
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
360
 
361
	}
362
 
29585 manish 363
	@RequestMapping(value = "/processInvestmentDryRun", method = RequestMethod.GET)
29608 amit.gupta 364
	public ResponseEntity<?> processInvestmentDryRun(HttpServletRequest request, Model model) throws Exception {
365
 
29585 manish 366
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
367
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
368
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
369
		List<List<?>> rows = new ArrayList<>();
370
 
29608 amit.gupta 371
		Map<String, String> params = new HashMap<>();
29585 manish 372
 
30682 amit.gupta 373
		params.put("MANUAL_datesBetween_FROMDATE", startOfPreviousMonth.toString());
374
		params.put("MANUAL_datesBetween_TODATE", lastOfPreviousMonth.toString());
29585 manish 375
 
29608 amit.gupta 376
		params.put("type", "INVESTMENT");
29585 manish 377
 
29608 amit.gupta 378
		List<EvaluateSchemeInvestmentPayoutModel> evaluateSchemeInvestmentPayouts = reporticoService.getReports(
379
				EvaluateSchemeInvestmentPayoutModel.class, ReporticoProject.FOCO, "schemepayout.xml", params);
380
		LOGGER.info("reportResponse {}", evaluateSchemeInvestmentPayouts);
381
 
382
		int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
383
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
384
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
385
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
386
				.filter(x -> x.getShortPercentage() <= 10)
387
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
388
 
389
		for (EvaluateSchemeInvestmentPayoutModel esip : evaluateSchemeInvestmentPayouts) {
390
 
391
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(esip.getFofoId()) == null ? 0
392
					: investmentMaintainedDaysMap.get(esip.getFofoId());
393
 
394
			esip.setInvestmentDays(investmentMaintainedDays);
395
 
396
			float processAmount = esip.getPaidAmount() / 2;
397
 
398
			esip.setProcessAmount(processAmount);
399
 
400
			rows.add(Arrays.asList(esip.getCode(), esip.getStoreName(), esip.getFofoId(), esip.getItemId(),
401
					esip.getBrand(), esip.getModelName(), esip.getModelNumber(), esip.getColor(), esip.getSchemeInDp(),
402
					esip.getSchemeOutDp(), esip.getSchemeId(), esip.getName(), esip.getType(), esip.getPartnerType(),
403
					esip.getAmountType(), esip.getAmount(), esip.getPurchaseInvoice(), esip.getSaleInovoice(),
404
					esip.getPaidAmount(), esip.getCreateTimestamp(), esip.getRolledBackTimestamp(),
405
					esip.getSerialNumber(), esip.getInRef(), esip.getOutRef(), esip.getBusinessDate(), esip.getStatus(),
406
					esip.getDescription(), esip.getProcessAmount(), esip.getInvestmentDays()));
29585 manish 407
		}
408
 
29608 amit.gupta 409
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
410
				.getCSVByteStream(Arrays.asList("Code", "Store Name", "Fofo Id", "Item Id", "Brand", "Model Name",
411
						"Model Number", "Color", "Scheme In Dp", "Scheme Out Dp", "Scheme Id", "Name", "Type",
412
						"Partner Type", "Amount Type", "Amount", "Purchase Invoice", "Sale Inovoice", "Paid Amount",
413
						"Create Timestamp", "Rolled Back Timestamp", "Serial Number", "In Ref", "Out Ref",
414
						"Business Date", "Status", "Description", "Process Amount", "Investment Days"), rows);
415
 
416
		final HttpHeaders headers = new HttpHeaders();
417
		headers.set("Content-Type", "text/csv");
418
		headers.set("Content-disposition", "inline; filename=schemePayout.csv");
419
		headers.setContentLength(baos.toByteArray().length);
420
 
421
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
422
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
423
 
30682 amit.gupta 424
		return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
29608 amit.gupta 425
 
426
	}
427
 
23556 amit.gupta 428
	@RequestMapping(value = "/schemes/update", method = RequestMethod.POST)
23786 amit.gupta 429
	public String updateShcemes(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
430
			throws Exception {
431
		for (int schemeId : schemeItems.getSchemeIds()) {
23928 govind 432
			if (schemeRepository.selectById(schemeId) != null)
30122 amit.gupta 433
				for (int catalogId : schemeItems.getCatalogIds()) {
30151 amit.gupta 434
					if (tagListingRepository.selectAllByCatalogIds(Arrays.asList(catalogId)).size() > 0) {
23928 govind 435
						SchemeItem si = new SchemeItem();
30122 amit.gupta 436
						si.setCatalogId(catalogId);
23928 govind 437
						si.setSchemeId(schemeId);
29608 amit.gupta 438
						si.setCreateTimestamp(LocalDateTime.now());
23928 govind 439
						try {
440
							schemeItemRepository.persist(si);
441
						} catch (Exception e) {
442
							LOGGER.info("Scheme aleady exist");
443
						}
31238 amit.gupta 444
						model.addAttribute("response1", mvcResponseSender.createResponseString(true));
23928 govind 445
					} else {
31238 amit.gupta 446
						model.addAttribute("response1", mvcResponseSender.createResponseString(false));
30122 amit.gupta 447
						throw new ProfitMandiBusinessException("Catalog Id ", catalogId, "Invalid Catalog Id");
23928 govind 448
					}
449
				}
450
		}
451
		return "response";
452
	}
25256 amit.gupta 453
 
23928 govind 454
	@RequestMapping(value = "/addItemToScheme", method = RequestMethod.POST)
455
	public String updateScheme(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
456
			throws Exception {
457
		for (int schemeId : schemeItems.getSchemeIds()) {
30122 amit.gupta 458
			List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(schemeId);
23786 amit.gupta 459
			if (schemeRepository.selectById(schemeId) != null)
30122 amit.gupta 460
				for (int catalogId : schemeItems.getCatalogIds()) {
461
					if (!(catalogIds.contains(catalogId))) {
23786 amit.gupta 462
						SchemeItem si = new SchemeItem();
30122 amit.gupta 463
						si.setCatalogId(catalogId);
23786 amit.gupta 464
						si.setSchemeId(schemeId);
29608 amit.gupta 465
						si.setCreateTimestamp(LocalDateTime.now());
23786 amit.gupta 466
						try {
467
							schemeItemRepository.persist(si);
468
						} catch (Exception e) {
23914 govind 469
							LOGGER.info("Scheme already exist");
23786 amit.gupta 470
						}
31238 amit.gupta 471
						model.addAttribute("response1", mvcResponseSender.createResponseString(true));
23786 amit.gupta 472
					} else {
30564 tejbeer 473
						throw new ProfitMandiBusinessException("Catalog exist for scheme",
474
								"SchemeId= " + schemeId + ", CatalogId= " + catalogId, "Catalog exist for scheme");
23556 amit.gupta 475
					}
476
				}
477
		}
478
		return "response";
479
	}
23914 govind 480
 
31170 amit.gupta 481
	@RequestMapping(value = "/createScheme", method = RequestMethod.GET)
482
	public String createScheme(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
23914 govind 483
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
484
 
31170 amit.gupta 485
		LocalDate currentdate = LocalDate.now();
486
		Month month = currentdate.getMonth().minus(1);
487
		model.addAttribute("month", month);
23914 govind 488
 
31170 amit.gupta 489
		// Map<Integer, String> itemIdItemDescriptionMap =
490
		// inventoryService.getAllItemIdItemDescriptionMap();
491
		// model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
492
		// List<Category> categories = inventoryService.getAllCategories();
493
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
494
		categories = categories.stream().sorted(Comparator.comparing(Category::getId)).collect(Collectors.toList());
495
		// Set<String> brands =
496
		// inventoryService.getAllTagListingBrands(ProfitMandiConstants.MOBILE_CATEGORY_ID);
497
		// brands.addAll(inventoryService.getAllTagListingBrands(14206));
23914 govind 498
 
31170 amit.gupta 499
		boolean fullAccesss = this.getAccess(loginDetails.getEmailId());
500
 
501
		List<Region> regionList = regionRepository.selectAll();
502
 
503
		model.addAttribute("fullAccesss", fullAccesss);
504
		model.addAttribute("regionList", regionList);
505
 
506
		model.addAttribute("categories", categories);
507
		model.addAttribute("retailerTypes", PartnerType.values());
508
		return "create-scheme";
23914 govind 509
	}
510
 
511
	@RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
512
	public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
513
			throws Exception {
514
		List<Scheme> schemes = schemeRepository.selectActiveAll();
515
		if (schemes.size() > 0) {
516
			for (Scheme scheme : schemes) {
25261 amit.gupta 517
				if (scheme.getExpireTimestamp() == null) {
23914 govind 518
					scheme.setEndDateTime(extendDatetime);
519
					schemeRepository.persist(scheme);
23819 govind 520
				}
521
			}
31238 amit.gupta 522
			model.addAttribute("response1", mvcResponseSender.createResponseString(true));
23914 govind 523
			return "response";
23819 govind 524
		}
31238 amit.gupta 525
		model.addAttribute("response1", mvcResponseSender.createResponseString(false));
23819 govind 526
		return "response";
527
	}
23786 amit.gupta 528
 
31170 amit.gupta 529
	@RequestMapping(value = "/getCatalogDescriptionByBrands", method = RequestMethod.GET)
530
	public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId,
531
											@RequestParam List<String> brands, Model model) throws Exception {
532
		Map<Integer, String> catalogIdItemDescriptionMap = inventoryService.getModelDescriptionMap(categoryId, brands);
533
		model.addAttribute("catalogIdItemDescriptionMap", catalogIdItemDescriptionMap);
534
		// model.addAttribute("brands", inventoryService.getAllBrands());
23819 govind 535
 
31170 amit.gupta 536
		return "tag-listing-items-description";
23914 govind 537
	}
538
 
22860 ashik.ali 539
	@RequestMapping(value = "/createScheme", method = RequestMethod.POST)
30564 tejbeer 540
	public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
31170 amit.gupta 541
							   Model model) throws ProfitMandiBusinessException {
22927 ashik.ali 542
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 543
		LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
22927 ashik.ali 544
		schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
30122 amit.gupta 545
		return getDefaultSchemes(request, model);
546
	}
29899 tejbeer 547
 
30122 amit.gupta 548
	private String getDefaultSchemes(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
549
		return getSchemes(request, 0, null, 30, 0, 0, PartnerType.ALL, "", model);
550
	}
551
 
552
	private List<Scheme> setSchemeAmountModel(List<Scheme> schemes) {
553
		for (Scheme scheme : schemes) {
554
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
555
				scheme.setAmountModel(scheme.getAmount() + "%");
556
			} else {
557
				scheme.setAmountModel(scheme.getAmount() + "");
29899 tejbeer 558
			}
559
		}
30122 amit.gupta 560
		return schemes;
22860 ashik.ali 561
	}
23786 amit.gupta 562
 
30564 tejbeer 563
	// Show 20 recents
31170 amit.gupta 564
 
565
	@RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
566
	public String deleteShcemes(HttpServletRequest request,
567
								@RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
568
								@RequestParam(name = "catalogId", required = false, defaultValue = "0") int catalogId, Model model)
569
			throws Exception {
570
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
571
		if (schemeId > 0 && catalogId > 0) {
572
			schemeItemRepository.deleteByCatalogIdsAndSchemeIds(catalogId, schemeId);
573
 
31238 amit.gupta 574
			model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31170 amit.gupta 575
 
576
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
577
 
578
		}
579
		return "response";
580
	}
581
 
582
	@RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
583
	public String extendSchemeById(HttpServletRequest request,
584
 
585
								   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
586
								   @RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
587
		Scheme scheme = schemeRepository.selectById(schemeId);
588
		if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
589
			scheme.setEndDateTime(extendDatetime);
590
			schemeRepository.persist(scheme);
31238 amit.gupta 591
			model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31170 amit.gupta 592
			return "response";
593
		}
31238 amit.gupta 594
		model.addAttribute("response1", mvcResponseSender.createResponseString(false));
31170 amit.gupta 595
		return "response";
596
	}
597
 
22860 ashik.ali 598
	@RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
23715 govind 599
	public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
31170 amit.gupta 600
							 @RequestParam(required = false) LocalDate date,
601
							 @RequestParam(name = "limit", required = false, defaultValue = "30") int limit,
602
							 @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel,
603
							 @RequestParam(name = "searchScheme", required = false, defaultValue = "0") int searchScheme,
604
							 @RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
605
							 @RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
28795 tejbeer 606
			throws ProfitMandiBusinessException {
23343 ashik.ali 607
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 608
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
30122 amit.gupta 609
		if (date != null) {
610
			date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
30274 amit.gupta 611
		} else if (!isAdmin) {
612
			date = LocalDate.now();
27876 amit.gupta 613
		}
26802 tejbeer 614
 
23343 ashik.ali 615
		List<Scheme> schemes = null;
30655 amit.gupta 616
		List<SchemeInOut> schemeInOuts = null;
28796 tejbeer 617
 
30122 amit.gupta 618
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
29608 amit.gupta 619
 
30122 amit.gupta 620
		model.addAttribute("fullAccess", fullAccess);
621
		model.addAttribute("searchImei", searchImei);
622
		model.addAttribute("isAdmin", isAdmin);
623
		model.addAttribute("searchModel", searchModel);
624
		model.addAttribute("searchScheme", searchScheme);
625
		model.addAttribute("partnerType", partnerType);
626
		model.addAttribute("date", date);
29608 amit.gupta 627
 
30122 amit.gupta 628
		final LocalDate date1 = date;
629
		if (searchScheme > 0) {
630
			schemes = Arrays.asList(schemeRepository.selectById(searchScheme));
631
			this.setSchemeAmountModel(schemes);
27876 amit.gupta 632
			if (schemes.size() > 0) {
26802 tejbeer 633
				model.addAttribute("schemes", schemes);
31170 amit.gupta 634
				List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
635
				Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
636
				model.addAttribute("schemeRegionMap", schemeRegionMap);
30122 amit.gupta 637
				return "schemes";
30043 amit.gupta 638
			} else {
30122 amit.gupta 639
				throw new ProfitMandiBusinessException("SchemeId", searchScheme, "SchemeId Not Found");
26802 tejbeer 640
			}
30122 amit.gupta 641
		} else if (searchModel > 0) {
642
			Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
30253 amit.gupta 643
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
28134 tejbeer 644
			if (tagListing != null) {
645
				model.addAttribute("dp", tagListing.getSellingPrice());
646
				model.addAttribute("mop", tagListing.getMop());
26802 tejbeer 647
			}
30253 amit.gupta 648
			model.addAttribute("modelName", item.getItemDescriptionNoColor());
649
			if (isAdmin) {
30564 tejbeer 650
				schemes = schemeService
651
						.selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
652
						.filter(x -> x.getId() != 411 && x.getId() != 612).collect(Collectors.toList());
30253 amit.gupta 653
				this.setSchemeAmountModel(schemes);
654
				model.addAttribute("schemes", schemes);
31170 amit.gupta 655
				List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
656
				Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
657
				model.addAttribute("schemeRegionMap", schemeRegionMap);
30253 amit.gupta 658
				return "schemes";
659
			} else {
660
				partnerType = partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), date);
30564 tejbeer 661
				schemes = schemeService
31170 amit.gupta 662
						.selectSchemeByPartnerTypeFofoId(partnerType, date, searchModel, loginDetails.getFofoId(), offset, limit).stream()
30564 tejbeer 663
						.filter(x -> {
30253 amit.gupta 664
							return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
665
						}).collect(Collectors.toList());
666
				// Remove 411 and 612
30564 tejbeer 667
				// this.setSchemeAmountModel(schemes);
30253 amit.gupta 668
				int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing);
669
				// For 7720(HR) remove investment
670
				model.addAttribute("schemes", schemes);
671
				model.addAttribute("nlc", Math.round(nlc));
30274 amit.gupta 672
 
673
				Map<Integer, Map<Integer, Long>> offerSlabPayoutMap = new HashMap<>();
30564 tejbeer 674
				List<CreateOfferRequest> offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(),
675
						searchModel);
30274 amit.gupta 676
				if (offers.size() > 0) {
677
					for (CreateOfferRequest createOfferRequest : offers) {
678
						Map<Integer, Map<Integer, Long>> catalogSlabPayoutMap = offerService
679
								.getSlabPayoutMap(createOfferRequest);
680
						Map<Integer, Long> slabPayoutMap = catalogSlabPayoutMap.get(searchModel);
681
						offerSlabPayoutMap.put(createOfferRequest.getId(), slabPayoutMap);
682
					}
683
					model.addAttribute("offers", offers);
684
					model.addAttribute("offerSlabPayoutMap", offerSlabPayoutMap);
685
 
686
					LOGGER.info("offer");
687
				}
688
				FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
689
				model.addAttribute("partnerCode", fs.getCode());
690
				model.addAttribute("fofoId", fs.getId());
691
 
30253 amit.gupta 692
				return "schemes-partner";
28795 tejbeer 693
 
30253 amit.gupta 694
			}
695
 
30122 amit.gupta 696
		} else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
697
 
28795 tejbeer 698
			LOGGER.info("searchImei" + searchImei);
699
 
30651 amit.gupta 700
			InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
701
					loginDetails.getFofoId());
28802 tejbeer 702
			Item item = itemRepository.selectById(inventoryItem.getItemId());
28795 tejbeer 703
			Map<Integer, Scheme> schemeMap = new HashMap<>();
30651 amit.gupta 704
			double netEarnings = 0;
28795 tejbeer 705
			if (inventoryItem != null) {
30831 tejbeer 706
				// Offer payout
707
				List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(),
708
						searchImei);
709
				Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream()
710
						.map(x -> offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId()))
711
						.collect(Collectors.toMap(x -> x.getId(), x -> x));
28795 tejbeer 712
 
30831 tejbeer 713
				schemeInOuts = schemeInOutRepository
714
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
28795 tejbeer 715
 
30655 amit.gupta 716
				if (!schemeInOuts.isEmpty()) {
30831 tejbeer 717
					netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
718
							.collect(Collectors.summingDouble(x -> x.getAmount()));
719
					List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId())
720
							.collect(Collectors.toList());
28795 tejbeer 721
 
722
					schemes = schemeRepository.selectBySchemeIds(schemeIds);
723
					for (Scheme scheme : schemes) {
724
						if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
725
							scheme.setAmountModel(scheme.getAmount() + "%");
726
						} else {
727
							scheme.setAmountModel(scheme.getAmount() + "");
728
						}
729
					}
730
 
731
					schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
732
				}
30651 amit.gupta 733
				List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
734
						.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
735
				if (priceDropImeis.size() > 0) {
736
 
737
					for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
738
						int priceDropId = priceDropIMEI.getPriceDropId();
739
						PriceDrop pd = priceDropRepository.selectById(priceDropId);
740
						priceDropIMEI.setPriceDrop(pd);
741
					}
742
					model.addAttribute("priceDropImeis", priceDropImeis);
743
				}
30655 amit.gupta 744
				netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
30651 amit.gupta 745
				model.addAttribute("offerPayouts", offerPayouts);
746
				model.addAttribute("offerRequestMap", offerRequestMap);
747
				model.addAttribute("inventoryItem", inventoryItem);
748
				model.addAttribute("inventoryItem", inventoryItem);
749
 
28795 tejbeer 750
			}
30651 amit.gupta 751
			model.addAttribute("netEarnings", netEarnings);
30253 amit.gupta 752
			model.addAttribute("fofoId", loginDetails.getFofoId());
28795 tejbeer 753
			model.addAttribute("schemeMap", schemeMap);
28802 tejbeer 754
			model.addAttribute("item", item);
30655 amit.gupta 755
			model.addAttribute("schemeInOut", schemeInOuts);
30122 amit.gupta 756
			return "schemes-partner";
28796 tejbeer 757
		}
28795 tejbeer 758
 
29899 tejbeer 759
		if (isAdmin) {
30699 amit.gupta 760
			schemes = schemeRepository.selectAll(0, 100);
30122 amit.gupta 761
			this.setSchemeAmountModel(schemes);
31170 amit.gupta 762
			List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
763
			Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
30122 amit.gupta 764
			model.addAttribute("schemes", schemes);
31170 amit.gupta 765
			model.addAttribute("schemeRegionMap", schemeRegionMap);
766
 
27876 amit.gupta 767
			return "schemes";
29899 tejbeer 768
		} else {
30122 amit.gupta 769
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
28795 tejbeer 770
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
771
						loginDetails.getFofoId());
30564 tejbeer 772
				List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
773
						.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
30274 amit.gupta 774
				if (priceDropImeis.size() > 0) {
28795 tejbeer 775
 
30274 amit.gupta 776
					for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
777
						int priceDropId = priceDropIMEI.getPriceDropId();
778
						PriceDrop pd = priceDropRepository.selectById(priceDropId);
779
						priceDropIMEI.setPriceDrop(pd);
780
					}
781
					model.addAttribute("priceDropImeis", priceDropImeis);
28795 tejbeer 782
				}
783
			}
28136 tejbeer 784
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
785
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 786
			model.addAttribute("fofoId", fs.getId());
27876 amit.gupta 787
			return "schemes-partner";
788
		}
29899 tejbeer 789
 
22860 ashik.ali 790
	}
23786 amit.gupta 791
 
30966 amit.gupta 792
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
28795 tejbeer 793
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
794
				.filter(x -> x.getId() == fofoId).count() > 0) {
795
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
796
					.collect(Collectors.toList());
797
		}
798
		float nlc = tagListing.getSellingPrice();
799
		for (Scheme scheme : schemes) {
800
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
801
				if (tagListing != null) {
30966 amit.gupta 802
					float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
30053 manish 803
					scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
28795 tejbeer 804
					nlc -= amount;
30043 amit.gupta 805
				} else {
28795 tejbeer 806
					scheme.setAmountModel(scheme.getAmount() + "%");
807
				}
808
			} else {
809
				scheme.setAmountModel(scheme.getAmount() + "");
810
				nlc -= scheme.getAmount();
811
			}
812
		}
813
 
814
		return Math.round(nlc);
815
 
816
	}
817
 
30053 manish 818
	@RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
819
	public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
820
 
821
		String status = "CREDITED";
822
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
823
 
824
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
825
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
826
 
827
		YearMonth yearMonth = YearMonth.now();
828
		LOGGER.info("yearMonth" + yearMonth);
829
 
830
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
831
 
832
		LOGGER.info("partnerType" + partnerType);
833
 
834
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
835
 
836
		if (partnerType) {
837
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
838
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
839
							currentDate)
840
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
841
		}
842
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
843
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
844
 
845
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
846
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
847
 
848
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
849
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
850
 
30253 amit.gupta 851
		Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
30564 tejbeer 852
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
853
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30253 amit.gupta 854
 
30053 manish 855
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
856
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
857
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
858
		LOGGER.info("lastMonthCategoryUpgradeMarginMap" + lastMonthCategoryUpgradeMarginMap);
859
 
860
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
861
 
862
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
863
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
864
 
865
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
866
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
867
 
868
		lastMonthFrontEndIncomes.stream().forEach(x -> {
869
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
870
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
871
				lastMonthSaleMarginMap.put(x.getBrand(), x);
872
			} else {
873
				lastMonthSaleMarginMap.put(x.getBrand(), x);
874
			}
875
 
876
		});
877
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
878
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
879
 
880
		Set<String> keySet = new HashSet<String>();
881
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
882
		keySet.addAll(lastMonthSaleMarginMap.keySet());
30235 tejbeer 883
		keySet.addAll(lastMonthPendingIncomeMap.keySet());
30053 manish 884
 
885
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
886
			String brand = x.getKey();
887
			float amount = x.getValue().getAmount();
888
			if (!totalAmountMap.containsKey(brand)) {
889
				totalAmountMap.put(brand, 0f);
890
			}
891
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
892
 
893
		});
30253 amit.gupta 894
 
30235 tejbeer 895
		lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
896
			String brand = x.getKey();
897
			float amount = x.getValue().getAmount();
898
			if (!totalAmountMap.containsKey(brand)) {
899
				totalAmountMap.put(brand, 0f);
900
			}
901
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30053 manish 902
 
30235 tejbeer 903
		});
904
 
30053 manish 905
		Map<Integer, String> monthValueMap = new HashMap<>();
906
		for (int i = 0; i <= 5; i++) {
907
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
908
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
909
		}
910
		model.addAttribute("month", 0);
911
		model.addAttribute("monthValueMap", monthValueMap);
912
		model.addAttribute("keySet", keySet);
30235 tejbeer 913
		model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
30053 manish 914
 
915
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
916
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
917
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
918
		model.addAttribute("status", status);
919
		model.addAttribute("totalAmountMap", totalAmountMap);
920
 
921
		return "last-month-credited-income";
922
	}
923
 
924
	@RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
925
	public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
926
 
927
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
928
 
929
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
930
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
931
		String status = "PENDING";
932
 
933
		LOGGER.info("currentStartMonth" + currentStartMonth);
934
		LOGGER.info("currentDate" + currentDate);
935
 
936
		List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
937
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
938
 
939
		Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
940
 
941
		for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
942
 
943
			lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
944
		}
945
		LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
946
		LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
947
		model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
948
		model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
949
		model.addAttribute("status", status);
950
 
951
		return "last-month-credited-income";
952
	}
953
 
954
	@RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
955
	public String getLastMonthImeiWiseIncome(HttpServletRequest request,
31170 amit.gupta 956
											 @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
957
											 @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 958
			throws Exception {
959
 
960
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
961
 
962
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
30410 amit.gupta 963
		LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 964
 
965
		HashSet<String> allImeiSet = new LinkedHashSet<>();
966
		HashSet<String> purchaseSet = new LinkedHashSet<>();
967
		HashSet<String> saleSet = new LinkedHashSet<>();
968
 
969
		List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
30410 amit.gupta 970
				.selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 971
		List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
30410 amit.gupta 972
				catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 973
		List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
30410 amit.gupta 974
				catalogItemId, lastMonthStart, lastMonthEnd);
30253 amit.gupta 975
 
30235 tejbeer 976
		LOGGER.info("lmci {}", lmci);
30053 manish 977
 
978
		Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
979
				.selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
30410 amit.gupta 980
						lastMonthEnd)
30053 manish 981
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
982
 
983
		allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
984
		allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
985
		allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
986
 
987
		List<String> allImeiList = new ArrayList<>(allImeiSet);
988
 
989
		LOGGER.info("allImeiList" + allImeiList);
990
		LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 991
 
30053 manish 992
		List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
993
				.selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
994
		List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
995
				.selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
996
		List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
997
				.selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
30253 amit.gupta 998
 
30053 manish 999
		LOGGER.info("lastMonthFrontEndImei {}", lastMonthFrontEndImeis);
1000
		LOGGER.info("lastMonthPurchaseInImei {}", lastMonthPurchaseInImeis);
1001
		LOGGER.info("lastMonthCreditedImei {}", lastMonthCreditedImeis);
30253 amit.gupta 1002
 
30580 amit.gupta 1003
		Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
30831 tejbeer 1004
				.filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
1005
						.groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30253 amit.gupta 1006
 
30053 manish 1007
		Map<IncomeImeiDate, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
1008
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
1009
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1010
 
1011
		Map<IncomeImeiDate, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
1012
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
1013
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1014
		// descriptionSet.add("")
1015
		purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
1016
		saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
1017
 
1018
		List<String> purchaseList = new ArrayList<>(purchaseSet);
1019
		List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 1020
 
30053 manish 1021
		Map<IncomeImeiDate, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30253 amit.gupta 1022
 
30053 manish 1023
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
1024
 
1025
			IncomeImeiDate imeiDate = entry.getKey();
1026
			Map<String, Double> descriptionAmountMap = entry.getValue();
1027
 
1028
			ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(),
1029
					imeiDate.getLocalDateTime(), null, descriptionAmountMap);
1030
			imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1031
			double totalAmount = imeiWiseIncomeMapOfMap.get(imeiDate).getDescriptionAmountMap().entrySet().stream()
1032
					.collect(Collectors.summingDouble(x -> x.getValue()));
1033
			imeiWiseIncomeMapOfMap.get(imeiDate).setTotalIncome(totalAmount);
1034
		}
1035
 
1036
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1037
			IncomeImeiDate imeiDate = entry.getKey();
1038
			Map<String, Double> descriptionAmountMap = entry.getValue();
1039
			if (!imeiWiseIncomeMapOfMap.containsKey(imeiDate)) {
1040
				ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(), null,
1041
						imeiDate.getLocalDateTime(), descriptionAmountMap);
1042
				imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1043
 
1044
			} else {
1045
				ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(imeiDate);
1046
				modelImeiMap.setSaleDate(imeiDate.getLocalDateTime());
1047
				modelImeiMap.getDescriptionAmountMap().putAll(descriptionAmountMap);
1048
 
1049
			}
1050
			double totalAmount = descriptionAmountMap.entrySet().stream()
1051
					.collect(Collectors.summingDouble(x -> x.getValue()));
1052
			imeiWiseIncomeMapOfMap.get(imeiDate)
1053
					.setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(imeiDate).getTotalIncome());
1054
		}
1055
 
1056
		lastMonthFrontEndImeis.stream().forEach(x -> {
1057
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), null);
1058
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1059
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1060
						.get(incomeImeiDate);
1061
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount();
1062
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1063
				imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
1064
			}
1065
		});
1066
 
30235 tejbeer 1067
		lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1068
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp());
1069
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1070
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1071
						.get(incomeImeiDate);
1072
 
1073
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getPendingSaleAmount();
1074
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1075
 
1076
			} else {
1077
 
1078
				ImeiWiseIncomePairAndMapModel newObjectImeiWiseIncomePairAndMapModel = new ImeiWiseIncomePairAndMapModel();
1079
 
1080
				newObjectImeiWiseIncomePairAndMapModel.setSerialNumber(x.getImei());
1081
				newObjectImeiWiseIncomePairAndMapModel.setPurchseDate(x.getCreateTimeStamp());
1082
				newObjectImeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount());
1083
			}
1084
 
1085
		});
1086
 
1087
		model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
30053 manish 1088
		model.addAttribute("month", month);
1089
		model.addAttribute("purchaseList", purchaseList);
1090
		model.addAttribute("saleList", saleList);
1091
		model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1092
		model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1093
		model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1094
		model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
1095
 
1096
		LOGGER.info("lastMonthPurchaseInMapPairMap {}", lastMonthPurchaseInMapPairMap);
1097
		LOGGER.info("lastMonthCreditedMapPairMap {}", lastMonthCreditedMapPairMap);
1098
		LOGGER.info("imeiWiseIncomeMapOfMap {}", imeiWiseIncomeMapOfMap);
1099
 
1100
		return "last-month-imei-wise-income";
1101
	}
1102
 
1103
	@RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1104
	public String getBrandWiseIncome(HttpServletRequest request,
31170 amit.gupta 1105
									 @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1106
									 @RequestParam(name = "status", required = false, defaultValue = "") String status,
1107
									 @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 1108
			throws ProfitMandiBusinessException {
1109
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1110
		LOGGER.info("loginDetails {}", loginDetails);
1111
		LOGGER.info("brand" + brand);
1112
		LOGGER.info("month {}", month);
1113
 
30410 amit.gupta 1114
		LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1115
		LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1116
 
30564 tejbeer 1117
		boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1118
				YearMonth.now());
30053 manish 1119
 
30410 amit.gupta 1120
		LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1121
 
30414 amit.gupta 1122
		Map<String, Double> categoryUpgradeBrandModelMap = null;
30410 amit.gupta 1123
		if (partnerTypeUpgraded) {
30414 amit.gupta 1124
			categoryUpgradeBrandModelMap = schemeInOutRepository
30410 amit.gupta 1125
					.selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1126
							monthEnd)
30053 manish 1127
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1128
		}
1129
 
30564 tejbeer 1130
		List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1131
				.selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
30053 manish 1132
 
30564 tejbeer 1133
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1134
				.selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1135
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1136
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1137
 
30564 tejbeer 1138
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1139
				.selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1140
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1141
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1142
 
30410 amit.gupta 1143
		Map<Integer, Double> modelTotalIncomeMap = new HashMap<>();
1144
		Map<Integer, String> modelNameMap = new HashMap<>();
30253 amit.gupta 1145
 
30410 amit.gupta 1146
		modelWiseSchemeOutMargins.stream().forEach(x -> {
30414 amit.gupta 1147
			modelTotalIncomeMap.put(x.getCatalogItemId(), x.getAmount() + x.getPendingSaleAmount());
1148
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + " " + x.getModelName()).trim());
30253 amit.gupta 1149
 
30410 amit.gupta 1150
		});
30414 amit.gupta 1151
		LastMonthBrandWiseIncomeModel totalModel = new LastMonthBrandWiseIncomeModel();
30410 amit.gupta 1152
		modelWiseSalesMargins.stream().forEach(x -> {
30413 amit.gupta 1153
			if (!modelWiseSchemeOutMarginsMap.containsKey(x.getCatalogItemId())) {
30410 amit.gupta 1154
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1155
				LastMonthBrandWiseIncomeModel lmbwIncomeModel = new LastMonthBrandWiseIncomeModel();
1156
				lmbwIncomeModel.setAmount(x.getAmount());
1157
				lmbwIncomeModel.setModelName(x.getModelName());
1158
				lmbwIncomeModel.setModelNumber(x.getModelNumber());
1159
				lmbwIncomeModel.setBrand(x.getBrand());
1160
				lmbwIncomeModel.setCatalogItemId(x.getCatalogItemId());
1161
				lmbwIncomeModel.setPendingSaleAmount(x.getPendingSaleAmount());
1162
				lmbwIncomeModel.setQty(x.getQty());
1163
				lmbwIncomeModel.setStatus(SchemePayoutStatus.CREDITED);
30410 amit.gupta 1164
				modelWiseSchemeOutMarginsMap.put(x.getCatalogItemId(), lmbwIncomeModel);
1165
 
30235 tejbeer 1166
			}
30410 amit.gupta 1167
			LastMonthBrandWiseIncomeModel lmbwIncomeModel = modelWiseSchemeOutMarginsMap.get(x.getCatalogItemId());
1168
			lmbwIncomeModel.setQty(x.getQty());
1169
			lmbwIncomeModel.setAmount(lmbwIncomeModel.getAmount() + x.getAmount());
30564 tejbeer 1170
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1171
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1172
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1173
			totalModel.setQty(totalModel.getQty() + x.getQty());
1174
			totalModel.setAmount(totalModel.getAmount() + lmbwIncomeModel.getAmount());
1175
			totalModel.setPendingSaleAmount(totalModel.getPendingSaleAmount());
30253 amit.gupta 1176
 
1177
		});
30410 amit.gupta 1178
		modelWiseSchemeInMargins.stream().forEach(x -> {
1179
			if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1180
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1181
			}
30564 tejbeer 1182
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1183
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1184
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1185
			totalModel.setQty(totalModel.getQty() + x.getQty());
1186
			totalModel.setAmount(totalModel.getAmount() + x.getAmount());
30053 manish 1187
 
30235 tejbeer 1188
		});
30053 manish 1189
 
30410 amit.gupta 1190
		model.addAttribute("month", month);
1191
		model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1192
		model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1193
		model.addAttribute("modelNameMap", modelNameMap);
1194
		model.addAttribute("modelTotalIncomeMap", modelTotalIncomeMap);
30414 amit.gupta 1195
		model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1196
		model.addAttribute("totalModel", totalModel);
30053 manish 1197
 
1198
		return "montly-brand-wise-income";
1199
 
1200
	}
1201
 
1202
	@RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1203
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1204
			throws ProfitMandiBusinessException {
1205
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1206
 
1207
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1208
		LocalDateTime currentMonthEnd = lastMonthStart.plusMonths(1).withDayOfMonth(1).toLocalDate().atStartOfDay();
1209
 
1210
		YearMonth monthYear = YearMonth.now();
1211
 
1212
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
1213
 
1214
		LOGGER.info("partnerType" + partnerType);
1215
 
1216
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
1217
 
1218
		if (partnerType) {
1219
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1220
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), lastMonthStart,
1221
							currentMonthEnd)
1222
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1223
		}
1224
 
1225
		String status = "CREDITED";
1226
		LOGGER.info("lastMonthStart" + lastMonthStart);
1227
		LOGGER.info("currentMonthEnd" + currentMonthEnd);
1228
 
1229
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1230
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1231
 
1232
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1233
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1234
 
1235
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1236
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), lastMonthStart, currentMonthEnd);
1237
 
1238
		LOGGER.info("lastMonthCreditedIncomeModels" + lastMonthCreditedIncomeModels);
1239
		LOGGER.info("lastMonthFrontEndIncomes" + lastMonthFrontEndIncomes);
1240
		LOGGER.info("lastMonthPurchaseInMargins" + lastMonthPurchaseInMargins);
1241
 
1242
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
1243
 
1244
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1245
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1246
 
1247
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1248
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1249
 
1250
		lastMonthFrontEndIncomes.stream().forEach(x -> {
1251
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1252
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1253
 
1254
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1255
			} else {
1256
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1257
			}
1258
 
1259
		});
1260
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1261
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1262
		Set<String> keySet = new HashSet<String>();
1263
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1264
		keySet.addAll(lastMonthSaleMarginMap.keySet());
1265
 
1266
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1267
			String brand = x.getKey();
1268
			float amount = x.getValue().getAmount();
1269
			if (!totalAmountMap.containsKey(brand)) {
1270
				totalAmountMap.put(brand, 0f);
1271
			}
1272
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
1273
 
1274
		});
1275
 
1276
		Map<Integer, String> monthValueMap = new HashMap<>();
1277
		for (int i = 0; i <= 5; i++) {
1278
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1279
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1280
		}
1281
		model.addAttribute("monthValueMap", monthValueMap);
1282
 
1283
		model.addAttribute("keySet", keySet);
1284
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1285
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1286
 
1287
		model.addAttribute("totalAmountMap", totalAmountMap);
1288
		model.addAttribute("status", status);
1289
		model.addAttribute("month", yearMonth);
1290
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1291
		LOGGER.info("totalAmountMap {}", totalAmountMap);
1292
		LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
1293
 
1294
		return "last-month-credited-income";
1295
	}
1296
 
23020 ashik.ali 1297
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 1298
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 1299
		return "schemes-download";
1300
	}
23786 amit.gupta 1301
 
23020 ashik.ali 1302
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 1303
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
31170 amit.gupta 1304
																  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
23786 amit.gupta 1305
			throws ProfitMandiBusinessException {
23914 govind 1306
 
23020 ashik.ali 1307
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 1308
 
23020 ashik.ali 1309
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1310
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 1311
 
1312
		final HttpHeaders headers = new HttpHeaders();
1313
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 1314
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 1315
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1316
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1317
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1318
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 1319
	}
23786 amit.gupta 1320
 
22860 ashik.ali 1321
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 1322
	public String getSchemeById(HttpServletRequest request,
31170 amit.gupta 1323
								@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
23786 amit.gupta 1324
			throws ProfitMandiBusinessException {
23343 ashik.ali 1325
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29899 tejbeer 1326
 
1327
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
22860 ashik.ali 1328
		Scheme scheme = schemeService.getSchemeById(schemeId);
29899 tejbeer 1329
		model.addAttribute("fullAccess", fullAccess);
22860 ashik.ali 1330
		model.addAttribute("scheme", scheme);
24445 amit.gupta 1331
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 1332
		return "scheme-details";
1333
	}
23786 amit.gupta 1334
 
22860 ashik.ali 1335
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
31170 amit.gupta 1336
	public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1337
								   @RequestParam(name = "offset", defaultValue = "0") int offset,
1338
								   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1339
			throws ProfitMandiBusinessException {
22860 ashik.ali 1340
		schemeService.activeSchemeById(schemeId);
1341
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
30064 amit.gupta 1342
		for (Scheme scheme : schemes) {
1343
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1344
				scheme.setAmountModel(scheme.getAmount() + "%");
1345
			} else {
1346
				scheme.setAmountModel(scheme.getAmount() + "");
1347
			}
1348
		}
30122 amit.gupta 1349
		return "schemes";
22860 ashik.ali 1350
	}
23786 amit.gupta 1351
 
22860 ashik.ali 1352
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1353
	public String expireSchemeById(HttpServletRequest request,
31170 amit.gupta 1354
								   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1355
								   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
23786 amit.gupta 1356
			throws ProfitMandiBusinessException {
25069 amit.gupta 1357
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
30122 amit.gupta 1358
		return getDefaultSchemes(request, model);
22860 ashik.ali 1359
	}
23786 amit.gupta 1360
 
23784 ashik.ali 1361
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 1362
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
31170 amit.gupta 1363
											@RequestParam(name = "offset", defaultValue = "0") int offset,
1364
											@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1365
			throws ProfitMandiBusinessException {
23784 ashik.ali 1366
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1367
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1368
	}
26802 tejbeer 1369
 
29707 tejbeer 1370
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
31147 tejbeer 1371
	public String getCustomerOffer(HttpServletRequest request,
1372
			@RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel, Model model)
1373
			throws ProfitMandiBusinessException {
31170 amit.gupta 1374
		List<CustomerOffer> customerOffers = null;
31147 tejbeer 1375
		if (searchModel > 0) {
29707 tejbeer 1376
 
31147 tejbeer 1377
			Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1378
			customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1379
			model.addAttribute("modelName", item.getItemDescriptionNoColor());
1380
		} else {
1381
			customerOffers = customerOfferRepository.selectAll();
1382
		}
29707 tejbeer 1383
 
31147 tejbeer 1384
		LOGGER.info("customerOffers" + customerOffers);
1385
 
1386
		for (CustomerOffer customerOffer : customerOffers) {
1387
 
1388
			LOGGER.info("ss" + searchModel);
1389
 
1390
			if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
1391
				String partnerCriteria = retailerService.getPartnerCriteriaString(
1392
						gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
1393
				customerOffer.setPartnerCriteriaString(partnerCriteria);
1394
			}
1395
 
1396
		}
1397
 
1398
		List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1399
				.collect(Collectors.toList());
1400
 
1401
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1402
 
1403
		Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1404
				.filter(x -> x != null).collect(Collectors.toList()).stream()
1405
				.collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1406
 
1407
		model.addAttribute("customRetailersMap", customRetailersMap);
1408
		model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1409
		model.addAttribute("searchModel", searchModel);
1410
 
29707 tejbeer 1411
		model.addAttribute("customerOffers", customerOffers);
1412
		return "customer-offer";
1413
 
1414
	}
1415
 
1416
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
31147 tejbeer 1417
	public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
31170 amit.gupta 1418
									  Model model) throws Exception {
29707 tejbeer 1419
 
1420
		CustomerOffer co = new CustomerOffer();
31147 tejbeer 1421
		co.setOfferName(customerOfferModel.getOfferName());
1422
		co.setStartDate(customerOfferModel.getStartDate());
1423
		co.setEndDate(customerOfferModel.getEndDate());
1424
		co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
29707 tejbeer 1425
		co.setCreatedTimestamp(LocalDateTime.now());
1426
		co.setUpdatedTimestamp(LocalDateTime.now());
1427
		customerOfferRepository.persist(co);
1428
 
31238 amit.gupta 1429
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29707 tejbeer 1430
 
1431
		return "response";
1432
 
1433
	}
1434
 
1435
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1436
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1437
		List<List<?>> rows = new ArrayList<>();
1438
 
31147 tejbeer 1439
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
1440
				"Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)"),
1441
				rows);
29707 tejbeer 1442
 
1443
		final HttpHeaders headers = new HttpHeaders();
1444
		headers.set("Content-Type", "text/csv");
1445
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1446
		headers.setContentLength(baos.toByteArray().length);
1447
 
1448
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1449
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1450
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1451
 
1452
	}
1453
 
1454
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1455
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
31170 amit.gupta 1456
										  HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
29707 tejbeer 1457
 
1458
		List<CSVRecord> records = FileUtil.readFile(file);
31147 tejbeer 1459
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
29707 tejbeer 1460
 
31147 tejbeer 1461
		CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1462
		List<Integer> catalogIds = new ArrayList<>();
29707 tejbeer 1463
		for (CSVRecord record : records) {
31147 tejbeer 1464
 
1465
			CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1466
 
1467
			if (coi == null) {
1468
				coi = new CustomerOfferItem();
29707 tejbeer 1469
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1470
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1471
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1472
				coi.setCustomerOfferId(offerId);
1473
				coi.setCreatedTimestamp(LocalDateTime.now());
31147 tejbeer 1474
 
29707 tejbeer 1475
				customerOfferItemRepository.persist(coi);
1476
 
31147 tejbeer 1477
			}
1478
			coi.setSchemePayout(Integer.parseInt(record.get(2)));
1479
			coi.setDealerPayout(Integer.parseInt(record.get(3)));
1480
			coi.setCustomerOfferId(offerId);
1481
			coi.setUpdatedTimestamp(LocalDateTime.now());
1482
 
1483
			LOGGER.info(record.get(4));
1484
 
1485
			LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1486
			LocalDate endDate = LocalDate.parse(record.get(5), formatter);
1487
 
1488
			if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1489
					|| startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1490
					&& (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1491
							|| startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1492
				coi.setStartDate(startDate);
1493
 
29707 tejbeer 1494
			} else {
31147 tejbeer 1495
 
1496
				catalogIds.add(coi.getCatalogId());
29707 tejbeer 1497
			}
1498
 
31147 tejbeer 1499
			if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1500
					|| endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1501
					&& (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1502
							|| endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1503
 
1504
				coi.setEndDate(endDate);
1505
 
1506
			} else {
1507
				catalogIds.add(coi.getCatalogId());
1508
			}
1509
 
29707 tejbeer 1510
		}
1511
 
31147 tejbeer 1512
		if (!catalogIds.isEmpty()) {
1513
			throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1514
					"Please set accurate start and end date");
1515
		}
31238 amit.gupta 1516
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29707 tejbeer 1517
 
1518
		return "response";
1519
 
1520
	}
1521
 
31147 tejbeer 1522
	@RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1523
	public String addCustomerOfferItem(HttpServletRequest request,
1524
			@RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
1525
 
1526
		CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
1527
 
1528
		if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1529
				&& customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1530
			throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
1531
 
1532
		}
1533
 
1534
		List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1535
				.selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
1536
 
1537
		if (!customerOfferItems.isEmpty()) {
1538
 
1539
			for (CustomerOfferItem coi : customerOfferItems) {
1540
				if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1541
					throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1542
				}
1543
			}
1544
 
1545
		}
1546
 
1547
		LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1548
		LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1549
		CustomerOfferItem coi = new CustomerOfferItem();
1550
		coi.setCatalogId(customerOfferItemModel.getCatalogId());
1551
		coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
1552
		coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
1553
		coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1554
		coi.setUpdatedTimestamp(LocalDateTime.now());
1555
		coi.setCreatedTimestamp(LocalDateTime.now());
1556
 
1557
		if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1558
				|| startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1559
				&& (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1560
						|| startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1561
 
1562
			coi.setStartDate(startDate);
1563
 
1564
		} else {
1565
 
1566
			throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1567
					"Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1568
							+ customerOffer.getEndDate());
1569
 
1570
		}
1571
 
1572
		if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1573
				|| endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1574
				&& (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1575
						|| endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1576
 
1577
			coi.setEndDate(endDate);
1578
 
1579
		} else {
1580
			throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1581
					"Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1582
							+ customerOffer.getEndDate());
1583
		}
1584
 
1585
		customerOfferItemRepository.persist(coi);
1586
 
31238 amit.gupta 1587
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1588
 
1589
		return "response";
1590
 
1591
	}
1592
 
29707 tejbeer 1593
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1594
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1595
 
1596
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1597
		List<List<?>> rows = new ArrayList<>();
31147 tejbeer 1598
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
29707 tejbeer 1599
 
1600
		for (CustomerOfferItem coi : cois) {
31147 tejbeer 1601
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
1602
					coi.getStartDate().format(formatter), coi.getEndDate().format(formatter)));
29707 tejbeer 1603
 
1604
		}
1605
 
31147 tejbeer 1606
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1607
				Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date"), rows);
29707 tejbeer 1608
 
1609
		final HttpHeaders headers = new HttpHeaders();
1610
		headers.set("Content-Type", "text/csv");
1611
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1612
		headers.setContentLength(baos.toByteArray().length);
1613
 
1614
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1615
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1616
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1617
 
1618
	}
1619
 
31147 tejbeer 1620
	@RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1621
	public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1622
			throws Exception {
1623
 
1624
		List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1625
		List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1626
 
1627
		Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1628
				.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1629
 
1630
		model.addAttribute("catalogItemMap", catalogItemMap);
1631
 
1632
		model.addAttribute("offerId", offerId);
1633
 
1634
		model.addAttribute("customerOfferItems", customerOfferItems);
1635
		return "customer-offer-item";
1636
 
1637
	}
1638
 
1639
	@RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1640
	public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1641
			@RequestParam LocalDateTime endDate, Model model) throws Exception {
1642
 
1643
		CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
1644
 
1645
		CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
1646
 
1647
		if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1648
				|| endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1649
				&& (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1650
						|| endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
1651
 
1652
			customerOfferItem.setEndDate(endDate.toLocalDate());
1653
 
1654
		} else {
1655
			throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1656
					"customer offer expired on " + customerOffer.getEndDate());
1657
		}
1658
		Map<Integer, List<Item>> catalogItemMap = itemRepository
1659
				.selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1660
				.collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1661
		model.addAttribute("catalogItemMap", catalogItemMap);
1662
 
1663
		model.addAttribute("coi", customerOfferItem);
1664
 
1665
		return "customer-offer-item-index";
1666
 
1667
	}
1668
 
29707 tejbeer 1669
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1670
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
31170 amit.gupta 1671
									  @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
29707 tejbeer 1672
 
1673
		CustomerOffer co = customerOfferRepository.selectById(id);
1674
		co.setEndDate(endDate);
1675
		co.setUpdatedTimestamp(LocalDateTime.now());
1676
 
1677
		model.addAttribute("co", co);
1678
 
1679
		return "customer-index-offer";
1680
 
1681
	}
1682
 
1683
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1684
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1685
 
1686
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1687
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1688
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1689
 
1690
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1691
		return "samsung-upgrade-offer";
1692
 
1693
	}
1694
 
1695
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1696
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1697
			throws ProfitMandiBusinessException {
1698
 
1699
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1700
		suo.setStatus(UpgradeOfferStatus.approved);
1701
		suo.setApprovedTimestamp(LocalDateTime.now());
1702
		model.addAttribute("suo", suo);
1703
		return "samsung-upgrade-offer-index";
1704
 
1705
	}
1706
 
1707
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1708
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1709
			throws ProfitMandiBusinessException {
1710
 
1711
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1712
		suo.setStatus(UpgradeOfferStatus.rejected);
1713
 
1714
		model.addAttribute("suo", suo);
1715
		return "samsung-upgrade-offer-index";
1716
 
1717
	}
30410 amit.gupta 1718
 
22860 ashik.ali 1719
}