Subversion Repositories SmartDukaan

Rev

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