Subversion Repositories SmartDukaan

Rev

Rev 29663 | Rev 29883 | 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
 
23020 ashik.ali 3
import java.io.ByteArrayInputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.InputStream;
26674 tejbeer 6
import java.time.LocalDate;
23020 ashik.ali 7
import java.time.LocalDateTime;
28916 amit.gupta 8
import java.time.LocalTime;
29585 manish 9
import java.time.Month;
29608 amit.gupta 10
import java.time.YearMonth;
27897 amit.gupta 11
import java.util.ArrayList;
23556 amit.gupta 12
import java.util.Arrays;
23914 govind 13
import java.util.HashMap;
23556 amit.gupta 14
import java.util.HashSet;
22860 ashik.ali 15
import java.util.List;
23020 ashik.ali 16
import java.util.Map;
25368 amit.gupta 17
import java.util.Set;
28491 amit.gupta 18
import java.util.stream.Collectors;
22860 ashik.ali 19
 
20
import javax.servlet.http.HttpServletRequest;
29707 tejbeer 21
import javax.servlet.http.HttpServletResponse;
25368 amit.gupta 22
import javax.transaction.Transactional;
22860 ashik.ali 23
 
29707 tejbeer 24
import org.apache.commons.csv.CSVRecord;
23784 ashik.ali 25
import org.apache.logging.log4j.LogManager;
23568 govind 26
import org.apache.logging.log4j.Logger;
22860 ashik.ali 27
import org.springframework.beans.factory.annotation.Autowired;
23784 ashik.ali 28
import org.springframework.beans.factory.annotation.Qualifier;
23020 ashik.ali 29
import org.springframework.core.io.InputStreamResource;
30
import org.springframework.http.HttpHeaders;
31
import org.springframework.http.HttpStatus;
32
import org.springframework.http.ResponseEntity;
22860 ashik.ali 33
import org.springframework.stereotype.Controller;
34
import org.springframework.ui.Model;
35
import org.springframework.web.bind.annotation.RequestBody;
36
import org.springframework.web.bind.annotation.RequestMapping;
37
import org.springframework.web.bind.annotation.RequestMethod;
38
import org.springframework.web.bind.annotation.RequestParam;
29707 tejbeer 39
import org.springframework.web.bind.annotation.RequestPart;
40
import org.springframework.web.multipart.MultipartFile;
22860 ashik.ali 41
 
23020 ashik.ali 42
import com.spice.profitmandi.common.enumuration.DateTimePattern;
29585 manish 43
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22860 ashik.ali 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
29585 manish 45
import com.spice.profitmandi.common.model.CustomRetailer;
23914 govind 46
import com.spice.profitmandi.common.model.MapWrapper;
22860 ashik.ali 47
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23557 amit.gupta 48
import com.spice.profitmandi.common.model.SchemeItems;
23020 ashik.ali 49
import com.spice.profitmandi.common.model.SchemeModel;
29585 manish 50
import com.spice.profitmandi.common.services.ReporticoService;
23020 ashik.ali 51
import com.spice.profitmandi.common.util.ExcelUtils;
29585 manish 52
import com.spice.profitmandi.common.util.FileUtil;
27394 amit.gupta 53
import com.spice.profitmandi.common.util.FormattingUtils;
23020 ashik.ali 54
import com.spice.profitmandi.common.util.StringUtils;
28924 amit.gupta 55
import com.spice.profitmandi.common.util.Utils;
23784 ashik.ali 56
import com.spice.profitmandi.common.web.util.ResponseSender;
29707 tejbeer 57
import com.spice.profitmandi.dao.entity.catalog.CustomerOffer;
58
import com.spice.profitmandi.dao.entity.catalog.CustomerOfferItem;
29585 manish 59
import com.spice.profitmandi.dao.entity.catalog.EvaluateSchemeInvestmentPayoutModel;
28492 amit.gupta 60
import com.spice.profitmandi.dao.entity.catalog.Item;
29707 tejbeer 61
import com.spice.profitmandi.dao.entity.catalog.SamsungUpgradeOffer;
22860 ashik.ali 62
import com.spice.profitmandi.dao.entity.catalog.Scheme;
27389 amit.gupta 63
import com.spice.profitmandi.dao.entity.catalog.TagListing;
29707 tejbeer 64
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
65
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
66
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
28136 tejbeer 67
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
28795 tejbeer 68
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
29585 manish 69
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
25505 amit.gupta 70
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
28795 tejbeer 71
import com.spice.profitmandi.dao.entity.fofo.SchemeInOut;
23556 amit.gupta 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;
29585 manish 78
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
27876 amit.gupta 79
import com.spice.profitmandi.dao.model.CreateOfferRequest;
25505 amit.gupta 80
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
29707 tejbeer 81
import com.spice.profitmandi.dao.repository.catalog.CustomerOfferItemRepository;
82
import com.spice.profitmandi.dao.repository.catalog.CustomerOfferRepository;
26674 tejbeer 83
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
29707 tejbeer 84
import com.spice.profitmandi.dao.repository.catalog.SamsungUpgradeOfferRepository;
22860 ashik.ali 85
import com.spice.profitmandi.dao.repository.catalog.SchemeRepository;
27389 amit.gupta 86
import com.spice.profitmandi.dao.repository.catalog.StateGstRateRepository;
23556 amit.gupta 87
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
26588 tejbeer 88
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
89
import com.spice.profitmandi.dao.repository.dtr.Mongo;
29707 tejbeer 90
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
91
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
92
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
28795 tejbeer 93
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
29585 manish 94
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
26674 tejbeer 95
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
28795 tejbeer 96
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
23556 amit.gupta 97
import com.spice.profitmandi.dao.repository.fofo.SchemeItemRepository;
28795 tejbeer 98
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
99
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
23798 amit.gupta 100
import com.spice.profitmandi.service.authentication.RoleManager;
23020 ashik.ali 101
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 102
import com.spice.profitmandi.service.offers.OfferService;
22860 ashik.ali 103
import com.spice.profitmandi.service.scheme.SchemeService;
26588 tejbeer 104
import com.spice.profitmandi.service.user.RetailerService;
29585 manish 105
import com.spice.profitmandi.service.wallet.WalletService;
22860 ashik.ali 106
import com.spice.profitmandi.web.model.LoginDetails;
107
import com.spice.profitmandi.web.util.CookiesProcessor;
23570 amit.gupta 108
import com.spice.profitmandi.web.util.MVCResponseSender;
22860 ashik.ali 109
 
29585 manish 110
import in.shop2020.model.v1.order.WalletReferenceType;
111
 
22860 ashik.ali 112
@Controller
25369 amit.gupta 113
@Transactional(rollbackOn = Throwable.class)
22860 ashik.ali 114
public class SchemeController {
115
 
23568 govind 116
	private static final Logger LOGGER = LogManager.getLogger(SchemeController.class);
22860 ashik.ali 117
 
118
	@Autowired
22927 ashik.ali 119
	private SchemeService schemeService;
27897 amit.gupta 120
 
27876 amit.gupta 121
	@Autowired
122
	private OfferService offerService;
23786 amit.gupta 123
 
22860 ashik.ali 124
	@Autowired
27389 amit.gupta 125
	private StateGstRateRepository stateGstRateRepository;
27612 tejbeer 126
 
27389 amit.gupta 127
	@Autowired
27416 amit.gupta 128
	private ItemRepository itemRepository;
29608 amit.gupta 129
 
29585 manish 130
	@Autowired
131
	private ReporticoService reporticoService;
27612 tejbeer 132
 
27416 amit.gupta 133
	@Autowired
22927 ashik.ali 134
	private SchemeRepository schemeRepository;
22860 ashik.ali 135
 
136
	@Autowired
23556 amit.gupta 137
	private SchemeItemRepository schemeItemRepository;
23786 amit.gupta 138
 
23556 amit.gupta 139
	@Autowired
23570 amit.gupta 140
	private MVCResponseSender mvcResponseSender;
23786 amit.gupta 141
 
23570 amit.gupta 142
	@Autowired
22927 ashik.ali 143
	private CookiesProcessor cookiesProcessor;
23786 amit.gupta 144
 
23020 ashik.ali 145
	@Autowired
23784 ashik.ali 146
	@Qualifier("fofoInventoryService")
23020 ashik.ali 147
	private InventoryService inventoryService;
23556 amit.gupta 148
 
149
	@Autowired
150
	private TagListingRepository tagListingRepository;
23914 govind 151
 
23798 amit.gupta 152
	@Autowired
153
	private RoleManager roleManager;
23786 amit.gupta 154
 
23506 amit.gupta 155
	@Autowired
27394 amit.gupta 156
	private ResponseSender<?> responseSender;
23786 amit.gupta 157
 
23784 ashik.ali 158
	@Autowired
27394 amit.gupta 159
	private FofoStoreRepository fofoStoreRepository;
23786 amit.gupta 160
 
23784 ashik.ali 161
	@Autowired
27394 amit.gupta 162
	private RetailerService retailerService;
22860 ashik.ali 163
 
27394 amit.gupta 164
	@Autowired
165
	private Mongo mongoClient;
29608 amit.gupta 166
 
29585 manish 167
	@Autowired
168
	WalletService walletService;
26588 tejbeer 169
 
170
	@Autowired
29585 manish 171
	PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
172
 
173
	@Autowired
26674 tejbeer 174
	private PartnerTypeChangeService partnerTypeChangeService;
175
 
28795 tejbeer 176
	@Autowired
177
	InventoryItemRepository inventoryItemRepository;
178
 
179
	@Autowired
180
	PriceDropIMEIRepository priceDropIMEIRepository;
181
 
182
	@Autowired
183
	PriceDropRepository priceDropRepository;
184
 
185
	@Autowired
186
	SchemeInOutRepository schemeInOutRepository;
187
 
29707 tejbeer 188
	@Autowired
189
	private CustomerOfferRepository customerOfferRepository;
190
 
191
	@Autowired
192
	private CustomerOfferItemRepository customerOfferItemRepository;
193
 
194
	@Autowired
195
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
196
 
22860 ashik.ali 197
	@RequestMapping(value = "/createScheme", method = RequestMethod.GET)
23786 amit.gupta 198
	public String createScheme(HttpServletRequest request, Model model) {
29608 amit.gupta 199
 
29585 manish 200
		LocalDate currentdate = LocalDate.now();
201
		Month month = currentdate.getMonth().minus(1);
202
		model.addAttribute("month", month);
29608 amit.gupta 203
 
23786 amit.gupta 204
		// Map<Integer, String> itemIdItemDescriptionMap =
205
		// inventoryService.getAllItemIdItemDescriptionMap();
206
		// model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
25368 amit.gupta 207
		Set<String> brands = inventoryService.getAllTagListingBrands(ProfitMandiConstants.MOBILE_CATEGORY_ID);
208
		brands.addAll(inventoryService.getAllTagListingBrands(14206));
209
		model.addAttribute("brands", brands);
25505 amit.gupta 210
		model.addAttribute("retailerTypes", PartnerType.values());
22860 ashik.ali 211
		return "create-scheme";
212
	}
23786 amit.gupta 213
 
23914 govind 214
	@RequestMapping(value = "/getTagListingItemsByBrand", method = RequestMethod.POST)
215
	public String getTagListingItemsByBrand(HttpServletRequest request, @RequestBody List<String> brands, Model model) {
216
		Map<Integer, String> itemIdItemDescriptionMap = new HashMap<>();
217
		LOGGER.info("brands" + brands);
218
 
219
		List<MapWrapper<Integer, String>> itemIdItemDescriptionMaplist = inventoryService
220
				.getAllTagListingItemIdItemDescriptionMap(new HashSet<>(brands));
221
		for (MapWrapper<Integer, String> mapWrapper : itemIdItemDescriptionMaplist) {
222
			itemIdItemDescriptionMap.put(mapWrapper.getKey(), mapWrapper.getValue());
223
		}
23020 ashik.ali 224
		model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
23786 amit.gupta 225
		// model.addAttribute("brands", inventoryService.getAllBrands());
23914 govind 226
 
23419 ashik.ali 227
		return "tag-listing-items-description";
23020 ashik.ali 228
	}
23556 amit.gupta 229
 
230
	@RequestMapping(value = "/schemes/update-schemes-page", method = RequestMethod.GET)
231
	public String updateShcemes(HttpServletRequest request) throws ProfitMandiBusinessException {
232
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23799 amit.gupta 233
		if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
23556 amit.gupta 234
			throw new ProfitMandiBusinessException("User", loginDetails.getEmailId(), "Unauthorised access");
235
		}
236
		return "update-schemes-page";
237
	}
29608 amit.gupta 238
 
29585 manish 239
	@RequestMapping(value = "/payMonthlyInvestment", method = RequestMethod.POST)
240
	public void payMonthlyInvestment(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
29608 amit.gupta 241
 
29585 manish 242
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
243
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
244
		int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
245
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
246
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
247
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
248
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
249
				.filter(x -> x.getShortPercentage() <= 10)
250
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
251
		LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
252
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
253
				startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
29608 amit.gupta 254
 
255
		if (schemeInOuts.isEmpty()) {
256
			throw new ProfitMandiBusinessException("Investment Payout", "", "No data Found");
29585 manish 257
		}
29608 amit.gupta 258
 
29585 manish 259
		Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
260
				.collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
261
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
262
		Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
263
				Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
264
		System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
265
		for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
266
			int fofoId = retailerEntry.getKey();
267
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
268
					: investmentMaintainedDaysMap.get(fofoId);
25256 amit.gupta 269
 
29585 manish 270
			List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
271
					.flatMap(List::stream).filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList());
272
			float totalAmount = 0;
29608 amit.gupta 273
			for (SchemeInOut sio : schemeInouts) {
274
 
29585 manish 275
				if (investmentMaintainedDays < 8) {
276
					sio.setStatus(SchemePayoutStatus.REJECTED);
29608 amit.gupta 277
					// sio.setRolledBackTimestamp(LocalDateTime.now());
29585 manish 278
					sio.setStatusDescription("Investment maintained for " + investmentMaintainedDays + "(< 8) days");
279
				} else if (investmentMaintainedDays < 12) {
280
					sio.setStatus(SchemePayoutStatus.CREDITED);
29608 amit.gupta 281
					sio.setAmount(sio.getAmount() / 2);
29585 manish 282
					sio.setCreditTimestamp(LocalDateTime.now());
283
					sio.setStatusDescription("Investment maintained for " + investmentMaintainedDays + "(< 12) days");
284
					totalAmount += sio.getAmount();
285
				} else {
286
					sio.setStatus(SchemePayoutStatus.CREDITED);
287
					sio.setCreditTimestamp(LocalDateTime.now());
288
					totalAmount += sio.getAmount();
289
				}
290
			}
29608 amit.gupta 291
			if (totalAmount > 0) {
292
				String description = "Investment margin paid for "
293
						+ FormattingUtils.formatYearMonth(startOfPreviousMonth.atStartOfDay());
294
				if (investmentMaintainedDays < 12) {
295
					description += ", as maintained for " + investmentMaintainedDays + "(< 12) days";
29585 manish 296
				}
29608 amit.gupta 297
				walletService.addAmountToWallet(fofoId, referenceId, WalletReferenceType.INVESTMENT_PAYOUT, description,
298
						totalAmount, lastOfPreviousMonth.atTime(LocalTime.MAX));
29585 manish 299
			}
300
			System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
301
		}
29608 amit.gupta 302
 
29585 manish 303
	}
29608 amit.gupta 304
 
29585 manish 305
	@RequestMapping(value = "/evaluateActualInvestmentPayout", method = RequestMethod.GET)
29663 manish 306
	public ResponseEntity<?> evaluateActualInvestmentPayout(HttpServletRequest request, Model model) throws Exception {
307
 
308
		List<List<?>> rows = new ArrayList<>();
309
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
310
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
311
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
312
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
313
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
314
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
315
				.filter(x -> x.getShortPercentage() <= 10)
316
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
317
		LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
318
		List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
319
				startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
320
		Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
321
				.collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
322
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
323
		Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
324
				Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
325
		System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
326
		for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
327
			int fofoId = retailerEntry.getKey();
328
			List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
329
					.flatMap(List::stream).collect(Collectors.toList());
330
			double totalAmount = schemeInouts.stream().filter(x -> x.getRolledBackTimestamp() == null)
331
					.collect(Collectors.summingDouble(x -> x.getAmount()));
332
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
333
					: investmentMaintainedDaysMap.get(fofoId);
334
			if (investmentMaintainedDays < 8) {
335
				totalAmount = 0;
336
			} else if (investmentMaintainedDays < 12) {
337
				totalAmount = totalAmount / 2;
29585 manish 338
			}
29663 manish 339
			System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
340
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
29608 amit.gupta 341
 
29663 manish 342
			rows.add(Arrays.asList(fofoId, customRetailer.getBusinessName(), customRetailer.getCode(),
343
					investmentMaintainedDays, totalAmount));
29585 manish 344
		}
345
 
29663 manish 346
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
347
				Arrays.asList("fofoId", "Name", "Code", "investmentMaintainedDays", "totalAmount"), rows);
348
 
349
		final HttpHeaders headers = new HttpHeaders();
350
		headers.set("Content-Type", "text/csv");
351
		headers.set("Content-disposition", "inline; filename=investmentMaintainedDays.csv");
352
		headers.setContentLength(baos.toByteArray().length);
353
 
354
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
355
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
356
 
357
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
358
 
359
	}
360
 
29585 manish 361
	@RequestMapping(value = "/processInvestmentDryRun", method = RequestMethod.GET)
29608 amit.gupta 362
	public ResponseEntity<?> processInvestmentDryRun(HttpServletRequest request, Model model) throws Exception {
363
 
29585 manish 364
		LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
365
		LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
366
		LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
367
		List<List<?>> rows = new ArrayList<>();
368
 
29608 amit.gupta 369
		Map<String, String> params = new HashMap<>();
29585 manish 370
 
29608 amit.gupta 371
		params.put("MANUAL_datesBetween_FROMDATE", firstDateOfCurrentMonth.toString());
372
		params.put("MANUAL_datesBetween_TODATE", firstDateOfCurrentMonth.plusDays(9).toString());
29585 manish 373
 
29608 amit.gupta 374
		params.put("type", "INVESTMENT");
29585 manish 375
 
29608 amit.gupta 376
		List<EvaluateSchemeInvestmentPayoutModel> evaluateSchemeInvestmentPayouts = reporticoService.getReports(
377
				EvaluateSchemeInvestmentPayoutModel.class, ReporticoProject.FOCO, "schemepayout.xml", params);
378
		LOGGER.info("reportResponse {}", evaluateSchemeInvestmentPayouts);
379
 
380
		int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
381
		List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
382
				.selectAll(startOfPreviousMonth, lastOfPreviousMonth);
383
		Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
384
				.filter(x -> x.getShortPercentage() <= 10)
385
				.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
386
 
387
		for (EvaluateSchemeInvestmentPayoutModel esip : evaluateSchemeInvestmentPayouts) {
388
 
389
			long investmentMaintainedDays = investmentMaintainedDaysMap.get(esip.getFofoId()) == null ? 0
390
					: investmentMaintainedDaysMap.get(esip.getFofoId());
391
 
392
			esip.setInvestmentDays(investmentMaintainedDays);
393
 
394
			float processAmount = esip.getPaidAmount() / 2;
395
 
396
			esip.setProcessAmount(processAmount);
397
 
398
			rows.add(Arrays.asList(esip.getCode(), esip.getStoreName(), esip.getFofoId(), esip.getItemId(),
399
					esip.getBrand(), esip.getModelName(), esip.getModelNumber(), esip.getColor(), esip.getSchemeInDp(),
400
					esip.getSchemeOutDp(), esip.getSchemeId(), esip.getName(), esip.getType(), esip.getPartnerType(),
401
					esip.getAmountType(), esip.getAmount(), esip.getPurchaseInvoice(), esip.getSaleInovoice(),
402
					esip.getPaidAmount(), esip.getCreateTimestamp(), esip.getRolledBackTimestamp(),
403
					esip.getSerialNumber(), esip.getInRef(), esip.getOutRef(), esip.getBusinessDate(), esip.getStatus(),
404
					esip.getDescription(), esip.getProcessAmount(), esip.getInvestmentDays()));
29585 manish 405
		}
406
 
29608 amit.gupta 407
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
408
				.getCSVByteStream(Arrays.asList("Code", "Store Name", "Fofo Id", "Item Id", "Brand", "Model Name",
409
						"Model Number", "Color", "Scheme In Dp", "Scheme Out Dp", "Scheme Id", "Name", "Type",
410
						"Partner Type", "Amount Type", "Amount", "Purchase Invoice", "Sale Inovoice", "Paid Amount",
411
						"Create Timestamp", "Rolled Back Timestamp", "Serial Number", "In Ref", "Out Ref",
412
						"Business Date", "Status", "Description", "Process Amount", "Investment Days"), rows);
413
 
414
		final HttpHeaders headers = new HttpHeaders();
415
		headers.set("Content-Type", "text/csv");
416
		headers.set("Content-disposition", "inline; filename=schemePayout.csv");
417
		headers.setContentLength(baos.toByteArray().length);
418
 
419
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
420
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
421
 
422
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
423
 
424
	}
425
 
23556 amit.gupta 426
	@RequestMapping(value = "/schemes/update", method = RequestMethod.POST)
23786 amit.gupta 427
	public String updateShcemes(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
428
			throws Exception {
429
		for (int schemeId : schemeItems.getSchemeIds()) {
23928 govind 430
			if (schemeRepository.selectById(schemeId) != null)
431
				for (int itemId : schemeItems.getItemIds()) {
432
					if (tagListingRepository.selectByItemIdsAndTagIds(new HashSet<>(Arrays.asList(itemId)),
433
							new HashSet<>(Arrays.asList(4, 7))).size() > 0) {
434
						SchemeItem si = new SchemeItem();
435
						si.setItemId(itemId);
436
						si.setSchemeId(schemeId);
29608 amit.gupta 437
						si.setCreateTimestamp(LocalDateTime.now());
23928 govind 438
						try {
439
							schemeItemRepository.persist(si);
440
						} catch (Exception e) {
441
							LOGGER.info("Scheme aleady exist");
442
						}
443
						model.addAttribute("response", mvcResponseSender.createResponseString(true));
444
					} else {
445
						model.addAttribute("response", mvcResponseSender.createResponseString(false));
446
						throw new ProfitMandiBusinessException("ItemId", itemId, "Invalid Item Id");
447
					}
448
				}
449
		}
450
		return "response";
451
	}
25256 amit.gupta 452
 
23928 govind 453
	@RequestMapping(value = "/addItemToScheme", method = RequestMethod.POST)
454
	public String updateScheme(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
455
			throws Exception {
456
		for (int schemeId : schemeItems.getSchemeIds()) {
23914 govind 457
			List<Integer> itemIds = schemeItemRepository.selectItemIdsBySchemeId(schemeId);
23786 amit.gupta 458
			if (schemeRepository.selectById(schemeId) != null)
459
				for (int itemId : schemeItems.getItemIds()) {
460
					if (tagListingRepository.selectByItemIdsAndTagIds(new HashSet<>(Arrays.asList(itemId)),
23914 govind 461
							new HashSet<>(Arrays.asList(4, 7))).size() > 0 && (!(itemIds.contains(itemId)))) {
23786 amit.gupta 462
						SchemeItem si = new SchemeItem();
463
						si.setItemId(itemId);
464
						si.setSchemeId(schemeId);
29608 amit.gupta 465
						si.setCreateTimestamp(LocalDateTime.now());
23786 amit.gupta 466
						try {
467
							schemeItemRepository.persist(si);
468
						} catch (Exception e) {
23914 govind 469
							LOGGER.info("Scheme already exist");
23786 amit.gupta 470
						}
471
						model.addAttribute("response", mvcResponseSender.createResponseString(true));
472
					} else {
473
						model.addAttribute("response", mvcResponseSender.createResponseString(false));
23556 amit.gupta 474
					}
475
				}
476
		}
477
		return "response";
478
	}
23914 govind 479
 
480
	@RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
481
	public String deleteShcemes(HttpServletRequest request,
482
			@RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
483
			@RequestParam(name = "itemId", required = false, defaultValue = "0") int itemId, Model model)
23819 govind 484
			throws Exception {
23914 govind 485
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
486
		if (!(schemeId == 0 && itemId == 0) || (!(schemeId == 0 || itemId == 0))) {
487
			schemeItemRepository.deletebyItemIdsandSchemeIds(itemId, schemeId);
488
 
489
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
490
 
491
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
492
 
493
		}
494
		return "response";
495
	}
496
 
497
	@RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
498
	public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
499
			throws Exception {
28924 amit.gupta 500
		extendDatetime = LocalDateTime.of(extendDatetime.toLocalDate(), Utils.MAX_TIME);
23914 govind 501
		List<Scheme> schemes = schemeRepository.selectActiveAll();
502
		if (schemes.size() > 0) {
503
			for (Scheme scheme : schemes) {
25261 amit.gupta 504
				if (scheme.getExpireTimestamp() == null) {
23914 govind 505
					scheme.setEndDateTime(extendDatetime);
506
					schemeRepository.persist(scheme);
23819 govind 507
				}
508
			}
23914 govind 509
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
510
			return "response";
23819 govind 511
		}
23914 govind 512
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
23819 govind 513
		return "response";
514
	}
23786 amit.gupta 515
 
23914 govind 516
	@RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
517
	public String extendSchemeById(HttpServletRequest request,
23819 govind 518
 
23914 govind 519
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
520
			@RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
28924 amit.gupta 521
		extendDatetime = LocalDateTime.of(extendDatetime.toLocalDate(), Utils.MAX_TIME);
23914 govind 522
		Scheme scheme = schemeRepository.selectById(schemeId);
523
		if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
524
			scheme.setEndDateTime(extendDatetime);
525
			schemeRepository.persist(scheme);
526
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
527
			return "response";
528
		}
529
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
530
		return "response";
531
	}
532
 
22860 ashik.ali 533
	@RequestMapping(value = "/createScheme", method = RequestMethod.POST)
23715 govind 534
	public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
535
			@RequestParam(name = "offset", defaultValue = "0") int offset,
23752 govind 536
			@RequestParam(name = "limit", defaultValue = "10") int limit,
537
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
538
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm, Model model)
23715 govind 539
			throws ProfitMandiBusinessException {
22927 ashik.ali 540
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 541
		LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
22927 ashik.ali 542
		schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
543
		LOGGER.info("Scheme saved successfully");
23271 ashik.ali 544
		long size = schemeRepository.selectAllCount();
22927 ashik.ali 545
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
546
		model.addAttribute("schemes", schemes);
547
		model.addAttribute("start", offset + 1);
23271 ashik.ali 548
		model.addAttribute("size", size);
23752 govind 549
		model.addAttribute("searchItem", searchItem);
550
		model.addAttribute("searchTerm", searchTerm);
23914 govind 551
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23715 govind 552
		if (schemes.size() < limit) {
22927 ashik.ali 553
			model.addAttribute("end", offset + schemes.size());
23786 amit.gupta 554
		} else {
22927 ashik.ali 555
			model.addAttribute("end", offset + limit);
556
		}
557
		return "schemes";
23786 amit.gupta 558
 
22860 ashik.ali 559
	}
23786 amit.gupta 560
 
22860 ashik.ali 561
	@RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
23715 govind 562
	public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
27876 amit.gupta 563
			@RequestParam(required = false) LocalDate date,
23752 govind 564
			@RequestParam(name = "limit", defaultValue = "10") int limit,
27897 amit.gupta 565
			@RequestParam(name = "searchItem", required = false, defaultValue = "0") int searchItem,
26802 tejbeer 566
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
567
			@RequestParam(name = "partnerType", required = false, defaultValue = "") PartnerType partnerType,
28795 tejbeer 568
			@RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
569
			throws ProfitMandiBusinessException {
23343 ashik.ali 570
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 571
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 572
		if (date == null) {
573
			date = LocalDate.now();
574
		}
575
		model.addAttribute("date", date);
26802 tejbeer 576
 
23343 ashik.ali 577
		List<Scheme> schemes = null;
28796 tejbeer 578
		List<SchemeInOut> schemeInOut = null;
579
 
23343 ashik.ali 580
		long size = 0;
28980 amit.gupta 581
		date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
29649 amit.gupta 582
		final LocalDate date1 = date;
26802 tejbeer 583
		if (partnerType == null) {
29608 amit.gupta 584
			// TODO - SCHEME
585
 
586
			partnerType = partnerTypeChangeService.getTypeOnMonth(loginDetails.getFofoId(), YearMonth.from(date));
587
 
588
			// partnerType =
589
			// partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), date);
23343 ashik.ali 590
		}
27394 amit.gupta 591
		if (!(searchTerm.equals(""))) {
26802 tejbeer 592
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
27612 tejbeer 593
			for (Scheme scheme : schemes) {
594
				if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
27394 amit.gupta 595
					scheme.setAmountModel(scheme.getAmount() + "%");
596
				} else {
597
					scheme.setAmountModel(scheme.getAmount() + "");
598
				}
599
			}
27876 amit.gupta 600
			if (schemes.size() > 0) {
26802 tejbeer 601
				size = schemeRepository.selectAllCount();
602
				LOGGER.info("schemes" + schemes);
603
				model.addAttribute("schemes", schemes);
604
				model.addAttribute("start", offset + 1);
605
				model.addAttribute("size", size);
606
				if (schemes.size() < limit) {
607
					model.addAttribute("end", offset + schemes.size());
27876 amit.gupta 608
				} else {
26802 tejbeer 609
					model.addAttribute("end", offset + limit);
610
				}
27612 tejbeer 611
			}
612
 
613
			else {
26802 tejbeer 614
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
615
			}
27612 tejbeer 616
		}
617
 
27897 amit.gupta 618
		else if (searchItem > 0) {
27394 amit.gupta 619
			TagListing tagListing = null;
28134 tejbeer 620
			tagListing = tagListingRepository.selectByItemId(searchItem);
28492 amit.gupta 621
			Item item = itemRepository.selectById(searchItem);
28134 tejbeer 622
			if (tagListing != null) {
623
				model.addAttribute("dp", tagListing.getSellingPrice());
624
				model.addAttribute("mop", tagListing.getMop());
26802 tejbeer 625
			}
29707 tejbeer 626
			schemes = schemeService.selectSchemeByPartnerType(partnerType, date, searchItem, isAdmin, offset, limit)
627
					.stream().filter(x -> {
628
						return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
629
					}).collect(Collectors.toList());
630
			// Remove 411 and 612
29658 amit.gupta 631
			model.addAttribute("schemes", schemes);
27612 tejbeer 632
			if (schemes.size() == 0) {
28795 tejbeer 633
				if (isAdmin)
634
					return "schemes";
635
				else {
27612 tejbeer 636
 
28795 tejbeer 637
					return "schemes-partner";
27389 amit.gupta 638
				}
639
			}
28795 tejbeer 640
			// For 7720(HR) remove investment
641
			int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing, searchItem);
27897 amit.gupta 642
			size = schemeService.selectSchemeCount(partnerType, date, searchItem, isAdmin);
26802 tejbeer 643
			model.addAttribute("start", offset + 1);
644
			model.addAttribute("size", size);
645
			if (schemes.size() < limit) {
646
				model.addAttribute("end", offset + schemes.size());
647
			} else {
648
				model.addAttribute("end", offset + limit);
649
			}
28547 amit.gupta 650
			model.addAttribute("nlc", Math.round(nlc));
28795 tejbeer 651
		} else if (!(searchImei.equals(""))) {
652
 
653
			LOGGER.info("searchImei" + searchImei);
654
 
655
			InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
656
					loginDetails.getFofoId());
28802 tejbeer 657
			Item item = itemRepository.selectById(inventoryItem.getItemId());
28795 tejbeer 658
			Map<Integer, Scheme> schemeMap = new HashMap<>();
659
			if (inventoryItem != null) {
660
 
661
				LOGGER.info("inventoryItem" + inventoryItem);
662
 
663
				schemeInOut = schemeInOutRepository
664
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
665
 
666
				LOGGER.info("schemeInOut" + schemeInOut);
667
 
668
				if (!schemeInOut.isEmpty()) {
669
 
670
					List<Integer> schemeIds = schemeInOut.stream().map(x -> x.getSchemeId())
671
							.collect(Collectors.toList());
672
 
673
					schemes = schemeRepository.selectBySchemeIds(schemeIds);
674
					for (Scheme scheme : schemes) {
675
						if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
676
							scheme.setAmountModel(scheme.getAmount() + "%");
677
						} else {
678
							scheme.setAmountModel(scheme.getAmount() + "");
679
						}
680
					}
681
 
682
					schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
683
				}
684
			}
685
 
686
			model.addAttribute("schemeMap", schemeMap);
28802 tejbeer 687
			model.addAttribute("item", item);
28795 tejbeer 688
 
28796 tejbeer 689
		}
690
		model.addAttribute("schemeInOut", schemeInOut);
28795 tejbeer 691
 
27876 amit.gupta 692
		model.addAttribute("searchItem", searchItem);
693
		model.addAttribute("searchTerm", searchTerm);
694
		model.addAttribute("partnerType", partnerType);
695
		model.addAttribute("isAdmin", isAdmin);
29650 amit.gupta 696
		LOGGER.info("schemes" + schemes);
29707 tejbeer 697
		model.addAttribute("schemes", schemes != null ? schemes.stream().filter(x -> {
698
			return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
29651 amit.gupta 699
		}).collect(Collectors.toList()) : null);
27876 amit.gupta 700
		LOGGER.info("schemes" + schemes);
23786 amit.gupta 701
		// model.addAttribute("roleTypes", loginDetails.getRoleTypes());
27876 amit.gupta 702
		if (isAdmin)
703
			return "schemes";
704
		else {
27897 amit.gupta 705
			List<CreateOfferRequest> offers = new ArrayList<>();
28795 tejbeer 706
			List<PriceDropIMEI> priceDropImeis = new ArrayList<>();
28134 tejbeer 707
			if (searchItem > 0) {
27897 amit.gupta 708
				offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(), searchItem);
709
			}
28795 tejbeer 710
			if (!(searchImei.equals(""))) {
711
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
712
						loginDetails.getFofoId());
713
 
714
				priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
715
				for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
716
					int priceDropId = priceDropIMEI.getPriceDropId();
717
					PriceDrop pd = priceDropRepository.selectById(priceDropId);
718
 
719
					priceDropIMEI.setPriceDrop(pd);
720
				}
721
			}
28136 tejbeer 722
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
723
 
27876 amit.gupta 724
			model.addAttribute("offers", offers);
28136 tejbeer 725
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 726
			model.addAttribute("fofoId", fs.getId());
727
			model.addAttribute("priceDropImeis", priceDropImeis);
27876 amit.gupta 728
			return "schemes-partner";
729
		}
22860 ashik.ali 730
	}
23786 amit.gupta 731
 
28795 tejbeer 732
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing, int itemId)
733
			throws ProfitMandiBusinessException {
734
 
735
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
736
				.filter(x -> x.getId() == fofoId).count() > 0) {
737
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
738
					.collect(Collectors.toList());
739
		}
740
		float nlc = tagListing.getSellingPrice();
741
		for (Scheme scheme : schemes) {
742
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
743
				if (tagListing != null) {
744
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
745
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
746
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
747
					scheme.setAmountModel(
748
							FormattingUtils.formatDecimalTwoDigits(amount) + " (" + scheme.getAmount() + "%)");
749
					nlc -= amount;
750
				}
751
 
752
				else {
753
					scheme.setAmountModel(scheme.getAmount() + "%");
754
				}
755
			} else {
756
				scheme.setAmountModel(scheme.getAmount() + "");
757
				nlc -= scheme.getAmount();
758
			}
759
		}
760
 
761
		return Math.round(nlc);
762
 
763
	}
764
 
22860 ashik.ali 765
	@RequestMapping(value = "/getPaginatedSchemes", method = RequestMethod.GET)
27876 amit.gupta 766
	public String getPaginatedSchemes(HttpServletRequest request, @RequestParam(required = false) LocalDate date,
23786 amit.gupta 767
			@RequestParam(name = "offset", defaultValue = "0") int offset,
26802 tejbeer 768
			@RequestParam(name = "limit", defaultValue = "10") int limit,
27876 amit.gupta 769
			@RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
26802 tejbeer 770
			Model model) throws ProfitMandiBusinessException {
771
 
23343 ashik.ali 772
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 773
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 774
		if (date == null) {
775
			date = LocalDate.now();
776
		}
23271 ashik.ali 777
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
27876 amit.gupta 778
		List<Scheme> schemes = schemeRepository.selectAll();
26802 tejbeer 779
		int itemId = 0;
27394 amit.gupta 780
		TagListing tagListing = null;
27897 amit.gupta 781
 
27612 tejbeer 782
		for (Scheme scheme : schemes) {
783
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
784
				if (itemId > 0) {
27394 amit.gupta 785
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
786
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
787
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
27612 tejbeer 788
					scheme.setAmountModel(
789
							FormattingUtils.formatDecimalTwoDigits(amount) + " (" + scheme.getAmount() + "%)");
27394 amit.gupta 790
				} else {
791
					scheme.setAmountModel(scheme.getAmount() + "%");
792
				}
793
			} else {
27876 amit.gupta 794
				scheme.setAmountModel("" + scheme.getAmount());
27394 amit.gupta 795
			}
796
		}
26802 tejbeer 797
 
22860 ashik.ali 798
		model.addAttribute("schemes", schemes);
26912 tejbeer 799
		model.addAttribute("partnerType", partnerType);
23914 govind 800
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 801
		return "schemes-paginated";
802
	}
23786 amit.gupta 803
 
23020 ashik.ali 804
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 805
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 806
		return "schemes-download";
807
	}
23786 amit.gupta 808
 
23020 ashik.ali 809
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 810
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
23914 govind 811
			@RequestParam(name = ProfitMandiConstants.START_DATE_TIME) String startDateTimeString,
812
			@RequestParam(name = ProfitMandiConstants.END_DATE_TIME) String endDateTimeString, Model model)
23786 amit.gupta 813
			throws ProfitMandiBusinessException {
23914 govind 814
		LocalDateTime startDateTime = StringUtils.toDateTime(startDateTimeString,
24406 amit.gupta 815
				DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
816
		LocalDateTime endDateTime = StringUtils.toDateTime(endDateTimeString, DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
23914 govind 817
 
23020 ashik.ali 818
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 819
 
23020 ashik.ali 820
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
821
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 822
 
823
		final HttpHeaders headers = new HttpHeaders();
824
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 825
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 826
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
827
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
828
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
829
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 830
	}
23786 amit.gupta 831
 
22860 ashik.ali 832
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 833
	public String getSchemeById(HttpServletRequest request,
834
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
835
			throws ProfitMandiBusinessException {
23343 ashik.ali 836
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 837
		Scheme scheme = schemeService.getSchemeById(schemeId);
838
		model.addAttribute("scheme", scheme);
24445 amit.gupta 839
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 840
		return "scheme-details";
23914 govind 841
 
22860 ashik.ali 842
	}
23786 amit.gupta 843
 
22860 ashik.ali 844
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 845
	public String activeSchemeById(HttpServletRequest request,
846
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
847
			@RequestParam(name = "offset", defaultValue = "0") int offset,
848
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
849
			throws ProfitMandiBusinessException {
22860 ashik.ali 850
		schemeService.activeSchemeById(schemeId);
851
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
852
		model.addAttribute("schemes", schemes);
853
		return "schemes-paginated";
854
	}
23786 amit.gupta 855
 
22860 ashik.ali 856
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 857
	public String expireSchemeById(HttpServletRequest request,
858
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
25069 amit.gupta 859
			@RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp,
23786 amit.gupta 860
			@RequestParam(name = "offset", defaultValue = "0") int offset,
861
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
862
			throws ProfitMandiBusinessException {
28924 amit.gupta 863
		expiryTimestamp = LocalDateTime.of(expiryTimestamp.toLocalDate(), Utils.MAX_TIME);
25069 amit.gupta 864
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
22860 ashik.ali 865
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
866
		model.addAttribute("schemes", schemes);
867
		return "schemes-paginated";
868
	}
23786 amit.gupta 869
 
23784 ashik.ali 870
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 871
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
872
			@RequestParam(name = "offset", defaultValue = "0") int offset,
873
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
874
			throws ProfitMandiBusinessException {
23784 ashik.ali 875
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
876
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
877
	}
26802 tejbeer 878
 
26763 tejbeer 879
	@RequestMapping(value = "/searchSchemeByCategory")
880
	public String getSchemeByCategory(HttpServletRequest request,
881
			@RequestParam(name = "offset", defaultValue = "0") int offset,
882
			@RequestParam(name = "limit", defaultValue = "10") int limit,
883
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
884
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
885
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
886
			throws ProfitMandiBusinessException {
887
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
888
		List<Scheme> schemes = null;
889
		long size = 0;
26802 tejbeer 890
 
891
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
892
 
893
		if (!(schemes.size() == 0)) {
894
			size = schemeRepository.selectAllCount();
895
			LOGGER.info("schemes" + schemes);
896
			model.addAttribute("schemes", schemes);
897
			model.addAttribute("start", offset + 1);
898
			model.addAttribute("size", size);
899
			model.addAttribute("searchTerm", searchTerm);
900
			model.addAttribute("searchItem", searchItem);
901
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
902
			if (schemes.size() < limit) {
903
				model.addAttribute("end", offset + schemes.size());
904
			} else {
905
				model.addAttribute("end", offset + limit);
26763 tejbeer 906
			}
26802 tejbeer 907
		}
908
 
26763 tejbeer 909
		return "schemes";
910
	}
26802 tejbeer 911
 
26763 tejbeer 912
	@RequestMapping(value = "/getSchemeByCategoryPaginated")
913
	public String getSchemeByCategoryPaginated(HttpServletRequest request,
914
			@RequestParam(name = "offset", defaultValue = "0") int offset,
915
			@RequestParam(name = "limit", defaultValue = "10") int limit,
916
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
917
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
918
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
919
			throws ProfitMandiBusinessException {
920
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
921
		LOGGER.info("In search Item....");
922
		List<Scheme> schemes = null;
26802 tejbeer 923
 
26763 tejbeer 924
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
23506 amit.gupta 925
 
26763 tejbeer 926
		model.addAttribute("schemes", schemes);
927
		model.addAttribute("searchItem", searchItem);
928
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
929
		return "schemes-paginated";
930
	}
931
 
23752 govind 932
	@RequestMapping(value = "/searchScheme")
933
	public String getSchemeBySchemeId(HttpServletRequest request,
934
			@RequestParam(name = "offset", defaultValue = "0") int offset,
935
			@RequestParam(name = "limit", defaultValue = "10") int limit,
936
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
937
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
938
			throws ProfitMandiBusinessException {
939
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
940
		List<Scheme> schemes = null;
941
		long size = 0;
942
		if (!(searchTerm.equals("")) && searchItem.equals("")) {
943
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
23786 amit.gupta 944
			if (!(schemes.size() == 0)) {
945
				size = schemeRepository.selectAllCount();
946
				LOGGER.info("schemes" + schemes);
947
				model.addAttribute("schemes", schemes);
948
				model.addAttribute("start", offset + 1);
949
				model.addAttribute("size", size);
950
				model.addAttribute("searchTerm", searchTerm);
951
				model.addAttribute("searchItem", searchItem);
23914 govind 952
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23786 amit.gupta 953
				if (schemes.size() < limit) {
954
					model.addAttribute("end", offset + schemes.size());
955
				} else {
956
					model.addAttribute("end", offset + limit);
957
				}
23752 govind 958
			} else {
23786 amit.gupta 959
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
23752 govind 960
			}
961
		} else if (!(searchItem.equals("")) && searchTerm.equals("")) {
962
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
23786 amit.gupta 963
			if (!(schemeIds.size() == 0)) {
23752 govind 964
				LOGGER.info("schemeIds in searchItemScheme" + schemeIds);
965
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
966
				size = schemeIds.size();
967
				LOGGER.info("Size" + size);
968
				model.addAttribute("schemes", schemes);
969
				model.addAttribute("start", offset + 1);
970
				model.addAttribute("size", size);
971
				model.addAttribute("searchItem", searchItem);
972
				model.addAttribute("searchTerm", searchTerm);
23914 govind 973
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 974
				if (schemes.size() < limit) {
975
					model.addAttribute("end", offset + schemes.size());
976
				} else {
977
					model.addAttribute("end", offset + limit);
978
				}
979
 
980
			} else {
981
				throw new ProfitMandiBusinessException("SchemeIds", searchItem, "SchemeId Not Found");
982
			}
983
		} else {
23798 amit.gupta 984
			if (roleManager.isAdmin(loginDetails.getRoleIds())) {
23752 govind 985
				schemes = schemeRepository.selectAll(offset, limit);
986
				size = schemeRepository.selectAllCount();
987
			} else {
988
				schemes = schemeRepository.selectActiveAll(offset, limit);
989
				size = schemeRepository.selectAllActiveCount();
990
			}
991
			model.addAttribute("schemes", schemes);
992
			model.addAttribute("start", offset + 1);
993
			model.addAttribute("size", size);
994
			model.addAttribute("searchItem", searchItem);
995
			model.addAttribute("searchTerm", searchTerm);
23914 govind 996
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 997
			if (schemes.size() < limit) {
998
				model.addAttribute("end", offset + schemes.size());
999
			} else {
1000
				model.addAttribute("end", offset + limit);
1001
			}
1002
		}
1003
		return "schemes";
1004
	}
1005
 
1006
	@RequestMapping(value = "/searchItemSchemePanigated")
1007
	public String getSchemeByItemPanigated(HttpServletRequest request,
1008
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1009
			@RequestParam(name = "limit", defaultValue = "10") int limit,
1010
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
1011
			throws ProfitMandiBusinessException {
23914 govind 1012
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23752 govind 1013
		LOGGER.info("In search Item....");
1014
		List<Scheme> schemes = null;
1015
		if (!searchItem.equals("")) {
1016
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
1017
			if (schemeIds != null) {
1018
				LOGGER.info(schemeIds);
1019
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
1020
 
1021
			}
1022
		}
1023
		model.addAttribute("schemes", schemes);
1024
		model.addAttribute("searchItem", searchItem);
23914 govind 1025
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 1026
		return "schemes-paginated";
1027
 
1028
	}
29707 tejbeer 1029
 
1030
	@RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1031
	public String getCustomerOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1032
 
1033
		List<CustomerOffer> customerOffers = customerOfferRepository.selectAll();
1034
 
1035
		model.addAttribute("customerOffers", customerOffers);
1036
		return "customer-offer";
1037
 
1038
	}
1039
 
1040
	@RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1041
	public String createCustomerOffer(HttpServletRequest request, @RequestParam String offerName,
1042
			@RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model) throws Exception {
1043
 
1044
		CustomerOffer co = new CustomerOffer();
1045
		co.setOfferName(offerName);
1046
		co.setStartDate(startDate);
1047
		co.setEndDate(endDate);
1048
		co.setCreatedTimestamp(LocalDateTime.now());
1049
		co.setUpdatedTimestamp(LocalDateTime.now());
1050
		customerOfferRepository.persist(co);
1051
 
1052
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1053
 
1054
		return "response";
1055
 
1056
	}
1057
 
1058
	@RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1059
	public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1060
		List<List<?>> rows = new ArrayList<>();
1061
 
1062
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1063
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1064
 
1065
		final HttpHeaders headers = new HttpHeaders();
1066
		headers.set("Content-Type", "text/csv");
1067
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1068
		headers.setContentLength(baos.toByteArray().length);
1069
 
1070
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1071
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1072
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1073
 
1074
	}
1075
 
1076
	@RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1077
	public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1078
			HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
1079
 
1080
		List<CSVRecord> records = FileUtil.readFile(file);
1081
 
1082
		for (CSVRecord record : records) {
1083
			if (Integer.parseInt(record.get(0)) == 0) {
1084
				CustomerOfferItem coi = new CustomerOfferItem();
1085
				coi.setCatalogId(Integer.parseInt(record.get(1)));
1086
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1087
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1088
				coi.setCustomerOfferId(offerId);
1089
				coi.setUpdatedTimestamp(LocalDateTime.now());
1090
				coi.setCreatedTimestamp(LocalDateTime.now());
1091
				customerOfferItemRepository.persist(coi);
1092
 
1093
			} else {
1094
				CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
1095
				coi.setSchemePayout(Integer.parseInt(record.get(2)));
1096
				coi.setDealerPayout(Integer.parseInt(record.get(3)));
1097
				coi.setUpdatedTimestamp(LocalDateTime.now());
1098
 
1099
			}
1100
 
1101
		}
1102
 
1103
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1104
 
1105
		return "response";
1106
 
1107
	}
1108
 
1109
	@RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1110
	public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
1111
 
1112
		List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1113
		List<List<?>> rows = new ArrayList<>();
1114
 
1115
		for (CustomerOfferItem coi : cois) {
1116
			rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout()));
1117
 
1118
		}
1119
 
1120
		org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1121
				.getCSVByteStream(Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout"), rows);
1122
 
1123
		final HttpHeaders headers = new HttpHeaders();
1124
		headers.set("Content-Type", "text/csv");
1125
		headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1126
		headers.setContentLength(baos.toByteArray().length);
1127
 
1128
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1129
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1130
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1131
 
1132
	}
1133
 
1134
	@RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1135
	public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1136
			@RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
1137
 
1138
		CustomerOffer co = customerOfferRepository.selectById(id);
1139
		co.setEndDate(endDate);
1140
		co.setUpdatedTimestamp(LocalDateTime.now());
1141
 
1142
		model.addAttribute("co", co);
1143
 
1144
		return "customer-index-offer";
1145
 
1146
	}
1147
 
1148
	@RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1149
	public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
1150
 
1151
		List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1152
		List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1153
				uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
1154
 
1155
		model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1156
		return "samsung-upgrade-offer";
1157
 
1158
	}
1159
 
1160
	@RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1161
	public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1162
			throws ProfitMandiBusinessException {
1163
 
1164
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1165
		suo.setStatus(UpgradeOfferStatus.approved);
1166
		suo.setApprovedTimestamp(LocalDateTime.now());
1167
		model.addAttribute("suo", suo);
1168
		return "samsung-upgrade-offer-index";
1169
 
1170
	}
1171
 
1172
	@RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1173
	public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1174
			throws ProfitMandiBusinessException {
1175
 
1176
		SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1177
		suo.setStatus(UpgradeOfferStatus.rejected);
1178
 
1179
		model.addAttribute("suo", suo);
1180
		return "samsung-upgrade-offer-index";
1181
 
1182
	}
1183
 
22860 ashik.ali 1184
}