Subversion Repositories SmartDukaan

Rev

Rev 29585 | Rev 29648 | 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;
26802 tejbeer 556
		if (partnerType == null) {
29608 amit.gupta 557
			// TODO - SCHEME
558
 
559
			partnerType = partnerTypeChangeService.getTypeOnMonth(loginDetails.getFofoId(), YearMonth.from(date));
560
 
561
			// partnerType =
562
			// partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), date);
23343 ashik.ali 563
		}
27394 amit.gupta 564
		if (!(searchTerm.equals(""))) {
26802 tejbeer 565
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
27612 tejbeer 566
			for (Scheme scheme : schemes) {
567
				if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
27394 amit.gupta 568
					scheme.setAmountModel(scheme.getAmount() + "%");
569
				} else {
570
					scheme.setAmountModel(scheme.getAmount() + "");
571
				}
572
			}
27876 amit.gupta 573
			if (schemes.size() > 0) {
26802 tejbeer 574
				size = schemeRepository.selectAllCount();
575
				LOGGER.info("schemes" + schemes);
576
				model.addAttribute("schemes", schemes);
577
				model.addAttribute("start", offset + 1);
578
				model.addAttribute("size", size);
579
				if (schemes.size() < limit) {
580
					model.addAttribute("end", offset + schemes.size());
27876 amit.gupta 581
				} else {
26802 tejbeer 582
					model.addAttribute("end", offset + limit);
583
				}
27612 tejbeer 584
			}
585
 
586
			else {
26802 tejbeer 587
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
588
			}
27612 tejbeer 589
		}
590
 
27897 amit.gupta 591
		else if (searchItem > 0) {
27394 amit.gupta 592
			TagListing tagListing = null;
28134 tejbeer 593
			tagListing = tagListingRepository.selectByItemId(searchItem);
28492 amit.gupta 594
			Item item = itemRepository.selectById(searchItem);
28134 tejbeer 595
			if (tagListing != null) {
596
				model.addAttribute("dp", tagListing.getSellingPrice());
597
				model.addAttribute("mop", tagListing.getMop());
26802 tejbeer 598
			}
27897 amit.gupta 599
			schemes = schemeService.selectSchemeByPartnerType(partnerType, date, searchItem, isAdmin, offset, limit);
27424 tejbeer 600
			model.addAttribute("schemes", schemes);
27612 tejbeer 601
			if (schemes.size() == 0) {
28795 tejbeer 602
				if (isAdmin)
603
					return "schemes";
604
				else {
27612 tejbeer 605
 
28795 tejbeer 606
					return "schemes-partner";
27389 amit.gupta 607
				}
608
			}
28795 tejbeer 609
			// For 7720(HR) remove investment
610
			int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing, searchItem);
27897 amit.gupta 611
			size = schemeService.selectSchemeCount(partnerType, date, searchItem, isAdmin);
26802 tejbeer 612
			model.addAttribute("start", offset + 1);
613
			model.addAttribute("size", size);
614
			if (schemes.size() < limit) {
615
				model.addAttribute("end", offset + schemes.size());
616
			} else {
617
				model.addAttribute("end", offset + limit);
618
			}
28547 amit.gupta 619
			model.addAttribute("nlc", Math.round(nlc));
28795 tejbeer 620
		} else if (!(searchImei.equals(""))) {
621
 
622
			LOGGER.info("searchImei" + searchImei);
623
 
624
			InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
625
					loginDetails.getFofoId());
28802 tejbeer 626
			Item item = itemRepository.selectById(inventoryItem.getItemId());
28795 tejbeer 627
			Map<Integer, Scheme> schemeMap = new HashMap<>();
628
			if (inventoryItem != null) {
629
 
630
				LOGGER.info("inventoryItem" + inventoryItem);
631
 
632
				schemeInOut = schemeInOutRepository
633
						.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
634
 
635
				LOGGER.info("schemeInOut" + schemeInOut);
636
 
637
				if (!schemeInOut.isEmpty()) {
638
 
639
					List<Integer> schemeIds = schemeInOut.stream().map(x -> x.getSchemeId())
640
							.collect(Collectors.toList());
641
 
642
					schemes = schemeRepository.selectBySchemeIds(schemeIds);
643
					for (Scheme scheme : schemes) {
644
						if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
645
							scheme.setAmountModel(scheme.getAmount() + "%");
646
						} else {
647
							scheme.setAmountModel(scheme.getAmount() + "");
648
						}
649
					}
650
 
651
					schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
652
				}
653
			}
654
 
655
			model.addAttribute("schemeMap", schemeMap);
28802 tejbeer 656
			model.addAttribute("item", item);
28795 tejbeer 657
 
28796 tejbeer 658
		}
659
		model.addAttribute("schemeInOut", schemeInOut);
28795 tejbeer 660
 
27876 amit.gupta 661
		model.addAttribute("searchItem", searchItem);
662
		model.addAttribute("searchTerm", searchTerm);
663
		model.addAttribute("partnerType", partnerType);
664
		model.addAttribute("isAdmin", isAdmin);
27612 tejbeer 665
		model.addAttribute("schemes", schemes);
27876 amit.gupta 666
		LOGGER.info("schemes" + schemes);
23786 amit.gupta 667
		// model.addAttribute("roleTypes", loginDetails.getRoleTypes());
27876 amit.gupta 668
		if (isAdmin)
669
			return "schemes";
670
		else {
27897 amit.gupta 671
			List<CreateOfferRequest> offers = new ArrayList<>();
28795 tejbeer 672
			List<PriceDropIMEI> priceDropImeis = new ArrayList<>();
28134 tejbeer 673
			if (searchItem > 0) {
27897 amit.gupta 674
				offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(), searchItem);
675
			}
28795 tejbeer 676
			if (!(searchImei.equals(""))) {
677
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
678
						loginDetails.getFofoId());
679
 
680
				priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
681
				for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
682
					int priceDropId = priceDropIMEI.getPriceDropId();
683
					PriceDrop pd = priceDropRepository.selectById(priceDropId);
684
 
685
					priceDropIMEI.setPriceDrop(pd);
686
				}
687
			}
28136 tejbeer 688
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
689
 
27876 amit.gupta 690
			model.addAttribute("offers", offers);
28136 tejbeer 691
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 692
			model.addAttribute("fofoId", fs.getId());
693
			model.addAttribute("priceDropImeis", priceDropImeis);
27876 amit.gupta 694
			return "schemes-partner";
695
		}
22860 ashik.ali 696
	}
23786 amit.gupta 697
 
28795 tejbeer 698
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing, int itemId)
699
			throws ProfitMandiBusinessException {
700
 
701
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
702
				.filter(x -> x.getId() == fofoId).count() > 0) {
703
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
704
					.collect(Collectors.toList());
705
		}
706
		float nlc = tagListing.getSellingPrice();
707
		for (Scheme scheme : schemes) {
708
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
709
				if (tagListing != null) {
710
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
711
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
712
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
713
					scheme.setAmountModel(
714
							FormattingUtils.formatDecimalTwoDigits(amount) + " (" + scheme.getAmount() + "%)");
715
					nlc -= amount;
716
				}
717
 
718
				else {
719
					scheme.setAmountModel(scheme.getAmount() + "%");
720
				}
721
			} else {
722
				scheme.setAmountModel(scheme.getAmount() + "");
723
				nlc -= scheme.getAmount();
724
			}
725
		}
726
 
727
		return Math.round(nlc);
728
 
729
	}
730
 
22860 ashik.ali 731
	@RequestMapping(value = "/getPaginatedSchemes", method = RequestMethod.GET)
27876 amit.gupta 732
	public String getPaginatedSchemes(HttpServletRequest request, @RequestParam(required = false) LocalDate date,
23786 amit.gupta 733
			@RequestParam(name = "offset", defaultValue = "0") int offset,
26802 tejbeer 734
			@RequestParam(name = "limit", defaultValue = "10") int limit,
27876 amit.gupta 735
			@RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
26802 tejbeer 736
			Model model) throws ProfitMandiBusinessException {
737
 
23343 ashik.ali 738
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 739
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 740
		if (date == null) {
741
			date = LocalDate.now();
742
		}
23271 ashik.ali 743
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
27876 amit.gupta 744
		List<Scheme> schemes = schemeRepository.selectAll();
26802 tejbeer 745
		int itemId = 0;
27394 amit.gupta 746
		TagListing tagListing = null;
27897 amit.gupta 747
 
27612 tejbeer 748
		for (Scheme scheme : schemes) {
749
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
750
				if (itemId > 0) {
27394 amit.gupta 751
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
752
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
753
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
27612 tejbeer 754
					scheme.setAmountModel(
755
							FormattingUtils.formatDecimalTwoDigits(amount) + " (" + scheme.getAmount() + "%)");
27394 amit.gupta 756
				} else {
757
					scheme.setAmountModel(scheme.getAmount() + "%");
758
				}
759
			} else {
27876 amit.gupta 760
				scheme.setAmountModel("" + scheme.getAmount());
27394 amit.gupta 761
			}
762
		}
26802 tejbeer 763
 
22860 ashik.ali 764
		model.addAttribute("schemes", schemes);
26912 tejbeer 765
		model.addAttribute("partnerType", partnerType);
23914 govind 766
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 767
		return "schemes-paginated";
768
	}
23786 amit.gupta 769
 
23020 ashik.ali 770
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 771
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 772
		return "schemes-download";
773
	}
23786 amit.gupta 774
 
23020 ashik.ali 775
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 776
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
23914 govind 777
			@RequestParam(name = ProfitMandiConstants.START_DATE_TIME) String startDateTimeString,
778
			@RequestParam(name = ProfitMandiConstants.END_DATE_TIME) String endDateTimeString, Model model)
23786 amit.gupta 779
			throws ProfitMandiBusinessException {
23914 govind 780
		LocalDateTime startDateTime = StringUtils.toDateTime(startDateTimeString,
24406 amit.gupta 781
				DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
782
		LocalDateTime endDateTime = StringUtils.toDateTime(endDateTimeString, DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
23914 govind 783
 
23020 ashik.ali 784
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 785
 
23020 ashik.ali 786
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
787
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 788
 
789
		final HttpHeaders headers = new HttpHeaders();
790
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 791
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 792
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
793
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
794
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
795
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 796
	}
23786 amit.gupta 797
 
22860 ashik.ali 798
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 799
	public String getSchemeById(HttpServletRequest request,
800
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
801
			throws ProfitMandiBusinessException {
23343 ashik.ali 802
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 803
		Scheme scheme = schemeService.getSchemeById(schemeId);
804
		model.addAttribute("scheme", scheme);
24445 amit.gupta 805
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 806
		return "scheme-details";
23914 govind 807
 
22860 ashik.ali 808
	}
23786 amit.gupta 809
 
22860 ashik.ali 810
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 811
	public String activeSchemeById(HttpServletRequest request,
812
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
813
			@RequestParam(name = "offset", defaultValue = "0") int offset,
814
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
815
			throws ProfitMandiBusinessException {
22860 ashik.ali 816
		schemeService.activeSchemeById(schemeId);
817
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
818
		model.addAttribute("schemes", schemes);
819
		return "schemes-paginated";
820
	}
23786 amit.gupta 821
 
22860 ashik.ali 822
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 823
	public String expireSchemeById(HttpServletRequest request,
824
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
25069 amit.gupta 825
			@RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp,
23786 amit.gupta 826
			@RequestParam(name = "offset", defaultValue = "0") int offset,
827
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
828
			throws ProfitMandiBusinessException {
28924 amit.gupta 829
		expiryTimestamp = LocalDateTime.of(expiryTimestamp.toLocalDate(), Utils.MAX_TIME);
25069 amit.gupta 830
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
22860 ashik.ali 831
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
832
		model.addAttribute("schemes", schemes);
833
		return "schemes-paginated";
834
	}
23786 amit.gupta 835
 
23784 ashik.ali 836
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 837
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
838
			@RequestParam(name = "offset", defaultValue = "0") int offset,
839
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
840
			throws ProfitMandiBusinessException {
23784 ashik.ali 841
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
842
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
843
	}
26802 tejbeer 844
 
26763 tejbeer 845
	@RequestMapping(value = "/searchSchemeByCategory")
846
	public String getSchemeByCategory(HttpServletRequest request,
847
			@RequestParam(name = "offset", defaultValue = "0") int offset,
848
			@RequestParam(name = "limit", defaultValue = "10") int limit,
849
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
850
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
851
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
852
			throws ProfitMandiBusinessException {
853
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
854
		List<Scheme> schemes = null;
855
		long size = 0;
26802 tejbeer 856
 
857
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
858
 
859
		if (!(schemes.size() == 0)) {
860
			size = schemeRepository.selectAllCount();
861
			LOGGER.info("schemes" + schemes);
862
			model.addAttribute("schemes", schemes);
863
			model.addAttribute("start", offset + 1);
864
			model.addAttribute("size", size);
865
			model.addAttribute("searchTerm", searchTerm);
866
			model.addAttribute("searchItem", searchItem);
867
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
868
			if (schemes.size() < limit) {
869
				model.addAttribute("end", offset + schemes.size());
870
			} else {
871
				model.addAttribute("end", offset + limit);
26763 tejbeer 872
			}
26802 tejbeer 873
		}
874
 
26763 tejbeer 875
		return "schemes";
876
	}
26802 tejbeer 877
 
26763 tejbeer 878
	@RequestMapping(value = "/getSchemeByCategoryPaginated")
879
	public String getSchemeByCategoryPaginated(HttpServletRequest request,
880
			@RequestParam(name = "offset", defaultValue = "0") int offset,
881
			@RequestParam(name = "limit", defaultValue = "10") int limit,
882
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
883
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
884
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
885
			throws ProfitMandiBusinessException {
886
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
887
		LOGGER.info("In search Item....");
888
		List<Scheme> schemes = null;
26802 tejbeer 889
 
26763 tejbeer 890
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
23506 amit.gupta 891
 
26763 tejbeer 892
		model.addAttribute("schemes", schemes);
893
		model.addAttribute("searchItem", searchItem);
894
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
895
		return "schemes-paginated";
896
	}
897
 
23752 govind 898
	@RequestMapping(value = "/searchScheme")
899
	public String getSchemeBySchemeId(HttpServletRequest request,
900
			@RequestParam(name = "offset", defaultValue = "0") int offset,
901
			@RequestParam(name = "limit", defaultValue = "10") int limit,
902
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
903
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
904
			throws ProfitMandiBusinessException {
905
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
906
		List<Scheme> schemes = null;
907
		long size = 0;
908
		if (!(searchTerm.equals("")) && searchItem.equals("")) {
909
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
23786 amit.gupta 910
			if (!(schemes.size() == 0)) {
911
				size = schemeRepository.selectAllCount();
912
				LOGGER.info("schemes" + schemes);
913
				model.addAttribute("schemes", schemes);
914
				model.addAttribute("start", offset + 1);
915
				model.addAttribute("size", size);
916
				model.addAttribute("searchTerm", searchTerm);
917
				model.addAttribute("searchItem", searchItem);
23914 govind 918
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23786 amit.gupta 919
				if (schemes.size() < limit) {
920
					model.addAttribute("end", offset + schemes.size());
921
				} else {
922
					model.addAttribute("end", offset + limit);
923
				}
23752 govind 924
			} else {
23786 amit.gupta 925
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
23752 govind 926
			}
927
		} else if (!(searchItem.equals("")) && searchTerm.equals("")) {
928
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
23786 amit.gupta 929
			if (!(schemeIds.size() == 0)) {
23752 govind 930
				LOGGER.info("schemeIds in searchItemScheme" + schemeIds);
931
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
932
				size = schemeIds.size();
933
				LOGGER.info("Size" + size);
934
				model.addAttribute("schemes", schemes);
935
				model.addAttribute("start", offset + 1);
936
				model.addAttribute("size", size);
937
				model.addAttribute("searchItem", searchItem);
938
				model.addAttribute("searchTerm", searchTerm);
23914 govind 939
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 940
				if (schemes.size() < limit) {
941
					model.addAttribute("end", offset + schemes.size());
942
				} else {
943
					model.addAttribute("end", offset + limit);
944
				}
945
 
946
			} else {
947
				throw new ProfitMandiBusinessException("SchemeIds", searchItem, "SchemeId Not Found");
948
			}
949
		} else {
23798 amit.gupta 950
			if (roleManager.isAdmin(loginDetails.getRoleIds())) {
23752 govind 951
				schemes = schemeRepository.selectAll(offset, limit);
952
				size = schemeRepository.selectAllCount();
953
			} else {
954
				schemes = schemeRepository.selectActiveAll(offset, limit);
955
				size = schemeRepository.selectAllActiveCount();
956
			}
957
			model.addAttribute("schemes", schemes);
958
			model.addAttribute("start", offset + 1);
959
			model.addAttribute("size", size);
960
			model.addAttribute("searchItem", searchItem);
961
			model.addAttribute("searchTerm", searchTerm);
23914 govind 962
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 963
			if (schemes.size() < limit) {
964
				model.addAttribute("end", offset + schemes.size());
965
			} else {
966
				model.addAttribute("end", offset + limit);
967
			}
968
		}
969
		return "schemes";
970
	}
971
 
972
	@RequestMapping(value = "/searchItemSchemePanigated")
973
	public String getSchemeByItemPanigated(HttpServletRequest request,
974
			@RequestParam(name = "offset", defaultValue = "0") int offset,
975
			@RequestParam(name = "limit", defaultValue = "10") int limit,
976
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
977
			throws ProfitMandiBusinessException {
23914 govind 978
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23752 govind 979
		LOGGER.info("In search Item....");
980
		List<Scheme> schemes = null;
981
		if (!searchItem.equals("")) {
982
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
983
			if (schemeIds != null) {
984
				LOGGER.info(schemeIds);
985
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
986
 
987
			}
988
		}
989
		model.addAttribute("schemes", schemes);
990
		model.addAttribute("searchItem", searchItem);
23914 govind 991
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 992
		return "schemes-paginated";
993
 
994
	}
22860 ashik.ali 995
}