Subversion Repositories SmartDukaan

Rev

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