Subversion Repositories SmartDukaan

Rev

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