Subversion Repositories SmartDukaan

Rev

Rev 31283 | Rev 31286 | 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
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
856
 
857
		lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
858
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
859
 
860
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
861
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
862
 
863
		lastMonthFrontEndIncomes.stream().forEach(x -> {
864
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
865
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
866
				lastMonthSaleMarginMap.put(x.getBrand(), x);
867
			} else {
868
				lastMonthSaleMarginMap.put(x.getBrand(), x);
869
			}
870
 
871
		});
872
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
873
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
874
 
31281 amit.gupta 875
		Set<String> keySet = new HashSet<>();
30053 manish 876
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
877
		keySet.addAll(lastMonthSaleMarginMap.keySet());
30235 tejbeer 878
		keySet.addAll(lastMonthPendingIncomeMap.keySet());
30053 manish 879
 
880
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
881
			String brand = x.getKey();
882
			float amount = x.getValue().getAmount();
883
			if (!totalAmountMap.containsKey(brand)) {
884
				totalAmountMap.put(brand, 0f);
885
			}
886
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
887
 
888
		});
30253 amit.gupta 889
 
30235 tejbeer 890
		lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
891
			String brand = x.getKey();
892
			float amount = x.getValue().getAmount();
893
			if (!totalAmountMap.containsKey(brand)) {
894
				totalAmountMap.put(brand, 0f);
895
			}
896
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30053 manish 897
 
30235 tejbeer 898
		});
899
 
31283 amit.gupta 900
 
30053 manish 901
		Map<Integer, String> monthValueMap = new HashMap<>();
902
		for (int i = 0; i <= 5; i++) {
903
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
904
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
905
		}
906
		model.addAttribute("month", 0);
907
		model.addAttribute("monthValueMap", monthValueMap);
908
		model.addAttribute("keySet", keySet);
30235 tejbeer 909
		model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
30053 manish 910
 
911
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
912
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
913
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
914
		model.addAttribute("status", status);
915
		model.addAttribute("totalAmountMap", totalAmountMap);
916
 
917
		return "last-month-credited-income";
918
	}
919
 
920
	@RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
921
	public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
922
 
923
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
924
 
925
		LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
926
		LocalDateTime currentDate = LocalDate.now().atStartOfDay();
927
		String status = "PENDING";
928
 
929
		LOGGER.info("currentStartMonth" + currentStartMonth);
930
		LOGGER.info("currentDate" + currentDate);
931
 
932
		List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
933
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
934
 
935
		Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
936
 
937
		for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
938
 
939
			lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
940
		}
941
		LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
942
		LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
943
		model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
944
		model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
945
		model.addAttribute("status", status);
946
 
947
		return "last-month-credited-income";
948
	}
949
 
950
	@RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
951
	public String getLastMonthImeiWiseIncome(HttpServletRequest request,
31170 amit.gupta 952
											 @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
953
											 @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 954
			throws Exception {
955
 
956
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
957
 
958
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
30410 amit.gupta 959
		LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 960
 
961
		HashSet<String> allImeiSet = new LinkedHashSet<>();
962
		HashSet<String> purchaseSet = new LinkedHashSet<>();
963
		HashSet<String> saleSet = new LinkedHashSet<>();
964
 
965
		List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
30410 amit.gupta 966
				.selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 967
		List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
30410 amit.gupta 968
				catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 969
		List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
30410 amit.gupta 970
				catalogItemId, lastMonthStart, lastMonthEnd);
30253 amit.gupta 971
 
30235 tejbeer 972
		LOGGER.info("lmci {}", lmci);
30053 manish 973
 
974
		Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
975
				.selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
30410 amit.gupta 976
						lastMonthEnd)
30053 manish 977
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
978
 
979
		allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
980
		allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
981
		allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
982
 
983
		List<String> allImeiList = new ArrayList<>(allImeiSet);
984
 
985
		LOGGER.info("allImeiList" + allImeiList);
986
		LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 987
 
30053 manish 988
		List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
989
				.selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
990
		List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
991
				.selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
992
		List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
993
				.selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
30253 amit.gupta 994
 
30053 manish 995
		LOGGER.info("lastMonthFrontEndImei {}", lastMonthFrontEndImeis);
996
		LOGGER.info("lastMonthPurchaseInImei {}", lastMonthPurchaseInImeis);
997
		LOGGER.info("lastMonthCreditedImei {}", lastMonthCreditedImeis);
30253 amit.gupta 998
 
30580 amit.gupta 999
		Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
30831 tejbeer 1000
				.filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
1001
						.groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30253 amit.gupta 1002
 
30053 manish 1003
		Map<IncomeImeiDate, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
1004
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
1005
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1006
 
1007
		Map<IncomeImeiDate, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
1008
				.collect(Collectors.groupingBy(x -> new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp()),
1009
						Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1010
		// descriptionSet.add("")
1011
		purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
1012
		saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
1013
 
1014
		List<String> purchaseList = new ArrayList<>(purchaseSet);
1015
		List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 1016
 
30053 manish 1017
		Map<IncomeImeiDate, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30253 amit.gupta 1018
 
30053 manish 1019
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
1020
 
1021
			IncomeImeiDate imeiDate = entry.getKey();
1022
			Map<String, Double> descriptionAmountMap = entry.getValue();
1023
 
1024
			ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(),
1025
					imeiDate.getLocalDateTime(), null, descriptionAmountMap);
1026
			imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1027
			double totalAmount = imeiWiseIncomeMapOfMap.get(imeiDate).getDescriptionAmountMap().entrySet().stream()
1028
					.collect(Collectors.summingDouble(x -> x.getValue()));
1029
			imeiWiseIncomeMapOfMap.get(imeiDate).setTotalIncome(totalAmount);
1030
		}
1031
 
1032
		for (Map.Entry<IncomeImeiDate, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1033
			IncomeImeiDate imeiDate = entry.getKey();
1034
			Map<String, Double> descriptionAmountMap = entry.getValue();
1035
			if (!imeiWiseIncomeMapOfMap.containsKey(imeiDate)) {
1036
				ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imeiDate.getImei(), null,
1037
						imeiDate.getLocalDateTime(), descriptionAmountMap);
1038
				imeiWiseIncomeMapOfMap.put(imeiDate, modelImeiMap);
1039
 
1040
			} else {
1041
				ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(imeiDate);
1042
				modelImeiMap.setSaleDate(imeiDate.getLocalDateTime());
1043
				modelImeiMap.getDescriptionAmountMap().putAll(descriptionAmountMap);
1044
 
1045
			}
1046
			double totalAmount = descriptionAmountMap.entrySet().stream()
1047
					.collect(Collectors.summingDouble(x -> x.getValue()));
1048
			imeiWiseIncomeMapOfMap.get(imeiDate)
1049
					.setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(imeiDate).getTotalIncome());
1050
		}
1051
 
1052
		lastMonthFrontEndImeis.stream().forEach(x -> {
1053
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), null);
1054
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1055
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1056
						.get(incomeImeiDate);
1057
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount();
1058
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1059
				imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
1060
			}
1061
		});
1062
 
30235 tejbeer 1063
		lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1064
			IncomeImeiDate incomeImeiDate = new IncomeImeiDate(x.getImei(), x.getCreateTimeStamp());
1065
			if (imeiWiseIncomeMapOfMap.containsKey(incomeImeiDate)) {
1066
				ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1067
						.get(incomeImeiDate);
1068
 
1069
				double totalAmount = imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getPendingSaleAmount();
1070
				imeiWiseIncomePairAndMapModel.setTotalIncome(totalAmount);
1071
 
1072
			} else {
1073
 
1074
				ImeiWiseIncomePairAndMapModel newObjectImeiWiseIncomePairAndMapModel = new ImeiWiseIncomePairAndMapModel();
1075
 
1076
				newObjectImeiWiseIncomePairAndMapModel.setSerialNumber(x.getImei());
1077
				newObjectImeiWiseIncomePairAndMapModel.setPurchseDate(x.getCreateTimeStamp());
1078
				newObjectImeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount());
1079
			}
1080
 
1081
		});
1082
 
1083
		model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
30053 manish 1084
		model.addAttribute("month", month);
1085
		model.addAttribute("purchaseList", purchaseList);
1086
		model.addAttribute("saleList", saleList);
1087
		model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1088
		model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1089
		model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1090
		model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
1091
 
1092
		LOGGER.info("lastMonthPurchaseInMapPairMap {}", lastMonthPurchaseInMapPairMap);
1093
		LOGGER.info("lastMonthCreditedMapPairMap {}", lastMonthCreditedMapPairMap);
1094
		LOGGER.info("imeiWiseIncomeMapOfMap {}", imeiWiseIncomeMapOfMap);
1095
 
1096
		return "last-month-imei-wise-income";
1097
	}
1098
 
1099
	@RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1100
	public String getBrandWiseIncome(HttpServletRequest request,
31170 amit.gupta 1101
									 @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1102
									 @RequestParam(name = "status", required = false, defaultValue = "") String status,
1103
									 @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
30053 manish 1104
			throws ProfitMandiBusinessException {
1105
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1106
		LOGGER.info("loginDetails {}", loginDetails);
1107
		LOGGER.info("brand" + brand);
1108
		LOGGER.info("month {}", month);
1109
 
30410 amit.gupta 1110
		LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1111
		LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1112
 
30564 tejbeer 1113
		boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1114
				YearMonth.now());
30053 manish 1115
 
30410 amit.gupta 1116
		LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1117
 
30414 amit.gupta 1118
		Map<String, Double> categoryUpgradeBrandModelMap = null;
30410 amit.gupta 1119
		if (partnerTypeUpgraded) {
30414 amit.gupta 1120
			categoryUpgradeBrandModelMap = schemeInOutRepository
30410 amit.gupta 1121
					.selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1122
							monthEnd)
30053 manish 1123
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1124
		}
1125
 
30564 tejbeer 1126
		List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1127
				.selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
30053 manish 1128
 
30564 tejbeer 1129
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1130
				.selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1131
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1132
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1133
 
30564 tejbeer 1134
		List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1135
				.selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1136
		Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1137
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30253 amit.gupta 1138
 
30410 amit.gupta 1139
		Map<Integer, Double> modelTotalIncomeMap = new HashMap<>();
1140
		Map<Integer, String> modelNameMap = new HashMap<>();
30253 amit.gupta 1141
 
30410 amit.gupta 1142
		modelWiseSchemeOutMargins.stream().forEach(x -> {
30414 amit.gupta 1143
			modelTotalIncomeMap.put(x.getCatalogItemId(), x.getAmount() + x.getPendingSaleAmount());
1144
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + " " + x.getModelName()).trim());
30253 amit.gupta 1145
 
30410 amit.gupta 1146
		});
30414 amit.gupta 1147
		LastMonthBrandWiseIncomeModel totalModel = new LastMonthBrandWiseIncomeModel();
30410 amit.gupta 1148
		modelWiseSalesMargins.stream().forEach(x -> {
30413 amit.gupta 1149
			if (!modelWiseSchemeOutMarginsMap.containsKey(x.getCatalogItemId())) {
30235 tejbeer 1150
				LastMonthBrandWiseIncomeModel lmbwIncomeModel = new LastMonthBrandWiseIncomeModel();
1151
				lmbwIncomeModel.setModelName(x.getModelName());
1152
				lmbwIncomeModel.setModelNumber(x.getModelNumber());
1153
				lmbwIncomeModel.setBrand(x.getBrand());
1154
				lmbwIncomeModel.setCatalogItemId(x.getCatalogItemId());
1155
				lmbwIncomeModel.setStatus(SchemePayoutStatus.CREDITED);
30410 amit.gupta 1156
				modelWiseSchemeOutMarginsMap.put(x.getCatalogItemId(), lmbwIncomeModel);
30235 tejbeer 1157
			}
30410 amit.gupta 1158
			LastMonthBrandWiseIncomeModel lmbwIncomeModel = modelWiseSchemeOutMarginsMap.get(x.getCatalogItemId());
31283 amit.gupta 1159
			lmbwIncomeModel.setQty(lmbwIncomeModel.getQty() + x.getQty());
30410 amit.gupta 1160
			lmbwIncomeModel.setAmount(lmbwIncomeModel.getAmount() + x.getAmount());
30564 tejbeer 1161
			modelTotalIncomeMap.put(x.getCatalogItemId(),
31284 amit.gupta 1162
					modelTotalIncomeMap.get(x.getCatalogItemId()) == null ? x.getAmount() : x.getAmount() + modelTotalIncomeMap.get(x.getCatalogItemId()));
30410 amit.gupta 1163
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1164
			totalModel.setQty(totalModel.getQty() + x.getQty());
1165
			totalModel.setAmount(totalModel.getAmount() + lmbwIncomeModel.getAmount());
1166
			totalModel.setPendingSaleAmount(totalModel.getPendingSaleAmount());
30253 amit.gupta 1167
 
1168
		});
30410 amit.gupta 1169
		modelWiseSchemeInMargins.stream().forEach(x -> {
1170
			if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1171
				modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
30235 tejbeer 1172
			}
30564 tejbeer 1173
			modelTotalIncomeMap.put(x.getCatalogItemId(),
1174
					modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
30410 amit.gupta 1175
			modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
30414 amit.gupta 1176
			totalModel.setQty(totalModel.getQty() + x.getQty());
1177
			totalModel.setAmount(totalModel.getAmount() + x.getAmount());
30053 manish 1178
 
30235 tejbeer 1179
		});
30053 manish 1180
 
30410 amit.gupta 1181
		model.addAttribute("month", month);
1182
		model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1183
		model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1184
		model.addAttribute("modelNameMap", modelNameMap);
1185
		model.addAttribute("modelTotalIncomeMap", modelTotalIncomeMap);
30414 amit.gupta 1186
		model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1187
		model.addAttribute("totalModel", totalModel);
30053 manish 1188
 
1189
		return "montly-brand-wise-income";
1190
 
1191
	}
1192
 
1193
	@RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1194
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1195
			throws ProfitMandiBusinessException {
1196
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1197
 
1198
		LocalDateTime lastMonthStart = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
31281 amit.gupta 1199
		LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 1200
 
1201
		YearMonth monthYear = YearMonth.now();
1202
 
1203
		boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
1204
 
1205
		LOGGER.info("partnerType" + partnerType);
1206
 
1207
		Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
1208
 
1209
		if (partnerType) {
1210
			lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1211
					.selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), lastMonthStart,
31281 amit.gupta 1212
							lastMonthEnd)
30053 manish 1213
					.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1214
		}
1215
 
1216
		String status = "CREDITED";
1217
 
31281 amit.gupta 1218
		List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1219
				.selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), lastMonthStart, lastMonthEnd);
1220
 
30053 manish 1221
		List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
31281 amit.gupta 1222
				.selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), lastMonthStart, lastMonthEnd);
30053 manish 1223
 
1224
		List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
31281 amit.gupta 1225
				.selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), lastMonthStart, lastMonthEnd);
30053 manish 1226
 
1227
		List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
31281 amit.gupta 1228
				.selectFrontIncomeByBrand(loginDetails.getFofoId(), lastMonthStart, lastMonthEnd);
30053 manish 1229
 
1230
 
31281 amit.gupta 1231
		Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
30053 manish 1232
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1233
 
1234
		Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1235
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1236
 
31281 amit.gupta 1237
 
1238
		Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1239
				.collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1240
 
30053 manish 1241
		lastMonthFrontEndIncomes.stream().forEach(x -> {
1242
			if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1243
				x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1244
 
1245
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1246
			} else {
1247
				lastMonthSaleMarginMap.put(x.getBrand(), x);
1248
			}
1249
 
1250
		});
1251
		Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1252
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1253
		Set<String> keySet = new HashSet<String>();
1254
		keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1255
		keySet.addAll(lastMonthSaleMarginMap.keySet());
1256
 
1257
		lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1258
			String brand = x.getKey();
1259
			float amount = x.getValue().getAmount();
1260
			if (!totalAmountMap.containsKey(brand)) {
1261
				totalAmountMap.put(brand, 0f);
1262
			}
1263
			totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
1264
 
1265
		});
1266
 
1267
		Map<Integer, String> monthValueMap = new HashMap<>();
1268
		for (int i = 0; i <= 5; i++) {
1269
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1270
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1271
		}
1272
		model.addAttribute("monthValueMap", monthValueMap);
1273
 
1274
		model.addAttribute("keySet", keySet);
1275
		model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1276
		model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
31281 amit.gupta 1277
		model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
30053 manish 1278
 
1279
		model.addAttribute("totalAmountMap", totalAmountMap);
1280
		model.addAttribute("status", status);
1281
		model.addAttribute("month", yearMonth);
1282
		model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1283
		LOGGER.info("totalAmountMap {}", totalAmountMap);
1284
		LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
1285
 
1286
		return "last-month-credited-income";
1287
	}
1288
 
23020 ashik.ali 1289
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 1290
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 1291
		return "schemes-download";
1292
	}
23786 amit.gupta 1293
 
23020 ashik.ali 1294
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 1295
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
31170 amit.gupta 1296
																  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
23786 amit.gupta 1297
			throws ProfitMandiBusinessException {
23914 govind 1298
 
23020 ashik.ali 1299
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 1300
 
23020 ashik.ali 1301
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1302
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 1303
 
1304
		final HttpHeaders headers = new HttpHeaders();
1305
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 1306
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 1307
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1308
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1309
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1310
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 1311
	}
23786 amit.gupta 1312
 
22860 ashik.ali 1313
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 1314
	public String getSchemeById(HttpServletRequest request,
31170 amit.gupta 1315
								@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
23786 amit.gupta 1316
			throws ProfitMandiBusinessException {
23343 ashik.ali 1317
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29899 tejbeer 1318
 
1319
		boolean fullAccess = this.getAccess(loginDetails.getEmailId());
22860 ashik.ali 1320
		Scheme scheme = schemeService.getSchemeById(schemeId);
29899 tejbeer 1321
		model.addAttribute("fullAccess", fullAccess);
22860 ashik.ali 1322
		model.addAttribute("scheme", scheme);
24445 amit.gupta 1323
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 1324
		return "scheme-details";
1325
	}
23786 amit.gupta 1326
 
22860 ashik.ali 1327
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
31170 amit.gupta 1328
	public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1329
								   @RequestParam(name = "offset", defaultValue = "0") int offset,
1330
								   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1331
			throws ProfitMandiBusinessException {
22860 ashik.ali 1332
		schemeService.activeSchemeById(schemeId);
1333
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
30064 amit.gupta 1334
		for (Scheme scheme : schemes) {
1335
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1336
				scheme.setAmountModel(scheme.getAmount() + "%");
1337
			} else {
1338
				scheme.setAmountModel(scheme.getAmount() + "");
1339
			}
1340
		}
30122 amit.gupta 1341
		return "schemes";
22860 ashik.ali 1342
	}
23786 amit.gupta 1343
 
22860 ashik.ali 1344
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 1345
	public String expireSchemeById(HttpServletRequest request,
31170 amit.gupta 1346
								   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1347
								   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
23786 amit.gupta 1348
			throws ProfitMandiBusinessException {
25069 amit.gupta 1349
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
30122 amit.gupta 1350
		return getDefaultSchemes(request, model);
22860 ashik.ali 1351
	}
23786 amit.gupta 1352
 
23784 ashik.ali 1353
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 1354
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
31170 amit.gupta 1355
											@RequestParam(name = "offset", defaultValue = "0") int offset,
1356
											@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
23786 amit.gupta 1357
			throws ProfitMandiBusinessException {
23784 ashik.ali 1358
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1359
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1360
	}
26802 tejbeer 1361
 
29707 tejbeer 1362
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
31147 tejbeer 1363
	public String getCustomerOffer(HttpServletRequest request,
1364
			@RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel, Model model)
1365
			throws ProfitMandiBusinessException {
31170 amit.gupta 1366
		List<CustomerOffer> customerOffers = null;
31147 tejbeer 1367
		if (searchModel > 0) {
29707 tejbeer 1368
 
31147 tejbeer 1369
			Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1370
			customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1371
			model.addAttribute("modelName", item.getItemDescriptionNoColor());
1372
		} else {
1373
			customerOffers = customerOfferRepository.selectAll();
1374
		}
29707 tejbeer 1375
 
31147 tejbeer 1376
		LOGGER.info("customerOffers" + customerOffers);
1377
 
1378
		for (CustomerOffer customerOffer : customerOffers) {
1379
 
1380
			LOGGER.info("ss" + searchModel);
1381
 
1382
			if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
1383
				String partnerCriteria = retailerService.getPartnerCriteriaString(
1384
						gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
1385
				customerOffer.setPartnerCriteriaString(partnerCriteria);
1386
			}
1387
 
1388
		}
1389
 
1390
		List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1391
				.collect(Collectors.toList());
1392
 
1393
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1394
 
1395
		Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1396
				.filter(x -> x != null).collect(Collectors.toList()).stream()
1397
				.collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1398
 
1399
		model.addAttribute("customRetailersMap", customRetailersMap);
1400
		model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1401
		model.addAttribute("searchModel", searchModel);
1402
 
29707 tejbeer 1403
		model.addAttribute("customerOffers", customerOffers);
1404
		return "customer-offer";
1405
 
1406
	}
1407
 
1408
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
31147 tejbeer 1409
	public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
31170 amit.gupta 1410
									  Model model) throws Exception {
29707 tejbeer 1411
 
1412
		CustomerOffer co = new CustomerOffer();
31147 tejbeer 1413
		co.setOfferName(customerOfferModel.getOfferName());
1414
		co.setStartDate(customerOfferModel.getStartDate());
1415
		co.setEndDate(customerOfferModel.getEndDate());
1416
		co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
29707 tejbeer 1417
		co.setCreatedTimestamp(LocalDateTime.now());
1418
		co.setUpdatedTimestamp(LocalDateTime.now());
1419
		customerOfferRepository.persist(co);
1420
 
31238 amit.gupta 1421
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29707 tejbeer 1422
 
1423
		return "response";
1424
 
1425
	}
1426
 
1427
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1428
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1429
		List<List<?>> rows = new ArrayList<>();
1430
 
31147 tejbeer 1431
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
1432
				"Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)"),
1433
				rows);
29707 tejbeer 1434
 
1435
		final HttpHeaders headers = new HttpHeaders();
1436
		headers.set("Content-Type", "text/csv");
1437
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1438
		headers.setContentLength(baos.toByteArray().length);
1439
 
1440
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1441
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1442
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1443
 
1444
	}
1445
 
1446
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1447
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
31170 amit.gupta 1448
										  HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
29707 tejbeer 1449
 
1450
		List<CSVRecord> records = FileUtil.readFile(file);
31147 tejbeer 1451
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
29707 tejbeer 1452
 
31147 tejbeer 1453
		CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1454
		List<Integer> catalogIds = new ArrayList<>();
29707 tejbeer 1455
		for (CSVRecord record : records) {
31147 tejbeer 1456
 
1457
			CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1458
 
1459
			if (coi == null) {
1460
				coi = new CustomerOfferItem();
29707 tejbeer 1461
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1462
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1463
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1464
				coi.setCustomerOfferId(offerId);
1465
				coi.setCreatedTimestamp(LocalDateTime.now());
31147 tejbeer 1466
 
29707 tejbeer 1467
				customerOfferItemRepository.persist(coi);
1468
 
31147 tejbeer 1469
			}
1470
			coi.setSchemePayout(Integer.parseInt(record.get(2)));
1471
			coi.setDealerPayout(Integer.parseInt(record.get(3)));
1472
			coi.setCustomerOfferId(offerId);
1473
			coi.setUpdatedTimestamp(LocalDateTime.now());
1474
 
1475
			LOGGER.info(record.get(4));
1476
 
1477
			LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1478
			LocalDate endDate = LocalDate.parse(record.get(5), formatter);
1479
 
1480
			if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1481
					|| startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1482
					&& (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1483
							|| startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1484
				coi.setStartDate(startDate);
1485
 
29707 tejbeer 1486
			} else {
31147 tejbeer 1487
 
1488
				catalogIds.add(coi.getCatalogId());
29707 tejbeer 1489
			}
1490
 
31147 tejbeer 1491
			if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1492
					|| endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1493
					&& (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1494
							|| endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1495
 
1496
				coi.setEndDate(endDate);
1497
 
1498
			} else {
1499
				catalogIds.add(coi.getCatalogId());
1500
			}
1501
 
29707 tejbeer 1502
		}
1503
 
31147 tejbeer 1504
		if (!catalogIds.isEmpty()) {
1505
			throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1506
					"Please set accurate start and end date");
1507
		}
31238 amit.gupta 1508
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29707 tejbeer 1509
 
1510
		return "response";
1511
 
1512
	}
1513
 
31147 tejbeer 1514
	@RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1515
	public String addCustomerOfferItem(HttpServletRequest request,
1516
			@RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
1517
 
1518
		CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
1519
 
1520
		if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1521
				&& customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1522
			throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
1523
 
1524
		}
1525
 
1526
		List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1527
				.selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
1528
 
1529
		if (!customerOfferItems.isEmpty()) {
1530
 
1531
			for (CustomerOfferItem coi : customerOfferItems) {
1532
				if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1533
					throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1534
				}
1535
			}
1536
 
1537
		}
1538
 
1539
		LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1540
		LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1541
		CustomerOfferItem coi = new CustomerOfferItem();
1542
		coi.setCatalogId(customerOfferItemModel.getCatalogId());
1543
		coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
1544
		coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
1545
		coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1546
		coi.setUpdatedTimestamp(LocalDateTime.now());
1547
		coi.setCreatedTimestamp(LocalDateTime.now());
1548
 
1549
		if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1550
				|| startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1551
				&& (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1552
						|| startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1553
 
1554
			coi.setStartDate(startDate);
1555
 
1556
		} else {
1557
 
1558
			throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1559
					"Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1560
							+ customerOffer.getEndDate());
1561
 
1562
		}
1563
 
1564
		if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1565
				|| endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1566
				&& (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1567
						|| endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1568
 
1569
			coi.setEndDate(endDate);
1570
 
1571
		} else {
1572
			throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1573
					"Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1574
							+ customerOffer.getEndDate());
1575
		}
1576
 
1577
		customerOfferItemRepository.persist(coi);
1578
 
31238 amit.gupta 1579
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1580
 
1581
		return "response";
1582
 
1583
	}
1584
 
29707 tejbeer 1585
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1586
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1587
 
1588
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1589
		List<List<?>> rows = new ArrayList<>();
31147 tejbeer 1590
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
29707 tejbeer 1591
 
1592
		for (CustomerOfferItem coi : cois) {
31147 tejbeer 1593
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
1594
					coi.getStartDate().format(formatter), coi.getEndDate().format(formatter)));
29707 tejbeer 1595
 
1596
		}
1597
 
31147 tejbeer 1598
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1599
				Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date"), rows);
29707 tejbeer 1600
 
1601
		final HttpHeaders headers = new HttpHeaders();
1602
		headers.set("Content-Type", "text/csv");
1603
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1604
		headers.setContentLength(baos.toByteArray().length);
1605
 
1606
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1607
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1608
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1609
 
1610
	}
1611
 
31147 tejbeer 1612
	@RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1613
	public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1614
			throws Exception {
1615
 
1616
		List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1617
		List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
1618
 
1619
		Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1620
				.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1621
 
1622
		model.addAttribute("catalogItemMap", catalogItemMap);
1623
 
1624
		model.addAttribute("offerId", offerId);
1625
 
1626
		model.addAttribute("customerOfferItems", customerOfferItems);
1627
		return "customer-offer-item";
1628
 
1629
	}
1630
 
1631
	@RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1632
	public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1633
			@RequestParam LocalDateTime endDate, Model model) throws Exception {
1634
 
1635
		CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
1636
 
1637
		CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
1638
 
1639
		if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1640
				|| endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1641
				&& (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1642
						|| endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
1643
 
1644
			customerOfferItem.setEndDate(endDate.toLocalDate());
1645
 
1646
		} else {
1647
			throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1648
					"customer offer expired on " + customerOffer.getEndDate());
1649
		}
1650
		Map<Integer, List<Item>> catalogItemMap = itemRepository
1651
				.selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1652
				.collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1653
		model.addAttribute("catalogItemMap", catalogItemMap);
1654
 
1655
		model.addAttribute("coi", customerOfferItem);
1656
 
1657
		return "customer-offer-item-index";
1658
 
1659
	}
1660
 
29707 tejbeer 1661
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1662
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
31170 amit.gupta 1663
									  @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
29707 tejbeer 1664
 
1665
		CustomerOffer co = customerOfferRepository.selectById(id);
1666
		co.setEndDate(endDate);
1667
		co.setUpdatedTimestamp(LocalDateTime.now());
1668
 
1669
		model.addAttribute("co", co);
1670
 
1671
		return "customer-index-offer";
1672
 
1673
	}
1674
 
1675
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1676
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1677
 
1678
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1679
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1680
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1681
 
1682
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1683
		return "samsung-upgrade-offer";
1684
 
1685
	}
1686
 
1687
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1688
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1689
			throws ProfitMandiBusinessException {
1690
 
1691
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1692
		suo.setStatus(UpgradeOfferStatus.approved);
1693
		suo.setApprovedTimestamp(LocalDateTime.now());
1694
		model.addAttribute("suo", suo);
1695
		return "samsung-upgrade-offer-index";
1696
 
1697
	}
1698
 
1699
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1700
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1701
			throws ProfitMandiBusinessException {
1702
 
1703
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1704
		suo.setStatus(UpgradeOfferStatus.rejected);
1705
 
1706
		model.addAttribute("suo", suo);
1707
		return "samsung-upgrade-offer-index";
1708
 
1709
	}
30410 amit.gupta 1710
 
22860 ashik.ali 1711
}