Subversion Repositories SmartDukaan

Rev

Rev 31284 | Rev 31334 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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