Subversion Repositories SmartDukaan

Rev

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