Subversion Repositories SmartDukaan

Rev

Rev 29651 | Rev 29658 | 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-> {
29652 amit.gupta 603
				return (x.getId()!=411 && x.getId()!=612) || date1.isBefore(LocalDate.of(2021, 12, 1));
29648 amit.gupta 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);
29650 amit.gupta 669
		LOGGER.info("schemes" + schemes);
29651 amit.gupta 670
		model.addAttribute("schemes", schemes !=null ? schemes.stream().filter(x-> {
29652 amit.gupta 671
			return (x.getId()!=411 && x.getId()!=612) || date1.isBefore(LocalDate.of(2021, 12, 1));
29651 amit.gupta 672
		}).collect(Collectors.toList()) : null);
27876 amit.gupta 673
		LOGGER.info("schemes" + schemes);
23786 amit.gupta 674
		// model.addAttribute("roleTypes", loginDetails.getRoleTypes());
27876 amit.gupta 675
		if (isAdmin)
676
			return "schemes";
677
		else {
27897 amit.gupta 678
			List<CreateOfferRequest> offers = new ArrayList<>();
28795 tejbeer 679
			List<PriceDropIMEI> priceDropImeis = new ArrayList<>();
28134 tejbeer 680
			if (searchItem > 0) {
27897 amit.gupta 681
				offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(), searchItem);
682
			}
28795 tejbeer 683
			if (!(searchImei.equals(""))) {
684
				InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
685
						loginDetails.getFofoId());
686
 
687
				priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
688
				for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
689
					int priceDropId = priceDropIMEI.getPriceDropId();
690
					PriceDrop pd = priceDropRepository.selectById(priceDropId);
691
 
692
					priceDropIMEI.setPriceDrop(pd);
693
				}
694
			}
28136 tejbeer 695
			FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
696
 
27876 amit.gupta 697
			model.addAttribute("offers", offers);
28136 tejbeer 698
			model.addAttribute("partnerCode", fs.getCode());
28795 tejbeer 699
			model.addAttribute("fofoId", fs.getId());
700
			model.addAttribute("priceDropImeis", priceDropImeis);
27876 amit.gupta 701
			return "schemes-partner";
702
		}
22860 ashik.ali 703
	}
23786 amit.gupta 704
 
28795 tejbeer 705
	private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing, int itemId)
706
			throws ProfitMandiBusinessException {
707
 
708
		if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
709
				.filter(x -> x.getId() == fofoId).count() > 0) {
710
			schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
711
					.collect(Collectors.toList());
712
		}
713
		float nlc = tagListing.getSellingPrice();
714
		for (Scheme scheme : schemes) {
715
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
716
				if (tagListing != null) {
717
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
718
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
719
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
720
					scheme.setAmountModel(
721
							FormattingUtils.formatDecimalTwoDigits(amount) + " (" + scheme.getAmount() + "%)");
722
					nlc -= amount;
723
				}
724
 
725
				else {
726
					scheme.setAmountModel(scheme.getAmount() + "%");
727
				}
728
			} else {
729
				scheme.setAmountModel(scheme.getAmount() + "");
730
				nlc -= scheme.getAmount();
731
			}
732
		}
733
 
734
		return Math.round(nlc);
735
 
736
	}
737
 
22860 ashik.ali 738
	@RequestMapping(value = "/getPaginatedSchemes", method = RequestMethod.GET)
27876 amit.gupta 739
	public String getPaginatedSchemes(HttpServletRequest request, @RequestParam(required = false) LocalDate date,
23786 amit.gupta 740
			@RequestParam(name = "offset", defaultValue = "0") int offset,
26802 tejbeer 741
			@RequestParam(name = "limit", defaultValue = "10") int limit,
27876 amit.gupta 742
			@RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
26802 tejbeer 743
			Model model) throws ProfitMandiBusinessException {
744
 
23343 ashik.ali 745
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26802 tejbeer 746
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
27876 amit.gupta 747
		if (date == null) {
748
			date = LocalDate.now();
749
		}
23271 ashik.ali 750
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
27876 amit.gupta 751
		List<Scheme> schemes = schemeRepository.selectAll();
26802 tejbeer 752
		int itemId = 0;
27394 amit.gupta 753
		TagListing tagListing = null;
27897 amit.gupta 754
 
27612 tejbeer 755
		for (Scheme scheme : schemes) {
756
			if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
757
				if (itemId > 0) {
27394 amit.gupta 758
					float taxRate = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId)).get(itemId);
759
					float taxableSellingPrice = tagListing.getSellingPrice() / (1 + taxRate / 100);
760
					float amount = taxableSellingPrice * scheme.getAmount() / 100;
27612 tejbeer 761
					scheme.setAmountModel(
762
							FormattingUtils.formatDecimalTwoDigits(amount) + " (" + scheme.getAmount() + "%)");
27394 amit.gupta 763
				} else {
764
					scheme.setAmountModel(scheme.getAmount() + "%");
765
				}
766
			} else {
27876 amit.gupta 767
				scheme.setAmountModel("" + scheme.getAmount());
27394 amit.gupta 768
			}
769
		}
26802 tejbeer 770
 
22860 ashik.ali 771
		model.addAttribute("schemes", schemes);
26912 tejbeer 772
		model.addAttribute("partnerType", partnerType);
23914 govind 773
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 774
		return "schemes-paginated";
775
	}
23786 amit.gupta 776
 
23020 ashik.ali 777
	@RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
23786 amit.gupta 778
	public String downloadPage(HttpServletRequest request, Model model) {
23020 ashik.ali 779
		return "schemes-download";
780
	}
23786 amit.gupta 781
 
23020 ashik.ali 782
	@RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
23786 amit.gupta 783
	public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
23914 govind 784
			@RequestParam(name = ProfitMandiConstants.START_DATE_TIME) String startDateTimeString,
785
			@RequestParam(name = ProfitMandiConstants.END_DATE_TIME) String endDateTimeString, Model model)
23786 amit.gupta 786
			throws ProfitMandiBusinessException {
23914 govind 787
		LocalDateTime startDateTime = StringUtils.toDateTime(startDateTimeString,
24406 amit.gupta 788
				DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
789
		LocalDateTime endDateTime = StringUtils.toDateTime(endDateTimeString, DateTimePattern.DD_MM_yyyy_T_HH_MM_SS);
23914 govind 790
 
23020 ashik.ali 791
		List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
23786 amit.gupta 792
 
23020 ashik.ali 793
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
794
		ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
23786 amit.gupta 795
 
796
		final HttpHeaders headers = new HttpHeaders();
797
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23020 ashik.ali 798
		headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
23786 amit.gupta 799
		headers.setContentLength(byteArrayOutputStream.toByteArray().length);
800
		final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
801
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
802
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
23020 ashik.ali 803
	}
23786 amit.gupta 804
 
22860 ashik.ali 805
	@RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
23786 amit.gupta 806
	public String getSchemeById(HttpServletRequest request,
807
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
808
			throws ProfitMandiBusinessException {
23343 ashik.ali 809
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
22860 ashik.ali 810
		Scheme scheme = schemeService.getSchemeById(schemeId);
811
		model.addAttribute("scheme", scheme);
24445 amit.gupta 812
		model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
22860 ashik.ali 813
		return "scheme-details";
23914 govind 814
 
22860 ashik.ali 815
	}
23786 amit.gupta 816
 
22860 ashik.ali 817
	@RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 818
	public String activeSchemeById(HttpServletRequest request,
819
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
820
			@RequestParam(name = "offset", defaultValue = "0") int offset,
821
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
822
			throws ProfitMandiBusinessException {
22860 ashik.ali 823
		schemeService.activeSchemeById(schemeId);
824
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
825
		model.addAttribute("schemes", schemes);
826
		return "schemes-paginated";
827
	}
23786 amit.gupta 828
 
22860 ashik.ali 829
	@RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
23786 amit.gupta 830
	public String expireSchemeById(HttpServletRequest request,
831
			@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
25069 amit.gupta 832
			@RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp,
23786 amit.gupta 833
			@RequestParam(name = "offset", defaultValue = "0") int offset,
834
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
835
			throws ProfitMandiBusinessException {
28924 amit.gupta 836
		expiryTimestamp = LocalDateTime.of(expiryTimestamp.toLocalDate(), Utils.MAX_TIME);
25069 amit.gupta 837
		schemeService.expireSchemeById(schemeId, expiryTimestamp);
22860 ashik.ali 838
		List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
839
		model.addAttribute("schemes", schemes);
840
		return "schemes-paginated";
841
	}
23786 amit.gupta 842
 
23784 ashik.ali 843
	@RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
23786 amit.gupta 844
	public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
845
			@RequestParam(name = "offset", defaultValue = "0") int offset,
846
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
847
			throws ProfitMandiBusinessException {
23784 ashik.ali 848
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
849
		return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
850
	}
26802 tejbeer 851
 
26763 tejbeer 852
	@RequestMapping(value = "/searchSchemeByCategory")
853
	public String getSchemeByCategory(HttpServletRequest request,
854
			@RequestParam(name = "offset", defaultValue = "0") int offset,
855
			@RequestParam(name = "limit", defaultValue = "10") int limit,
856
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
857
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
858
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
859
			throws ProfitMandiBusinessException {
860
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
861
		List<Scheme> schemes = null;
862
		long size = 0;
26802 tejbeer 863
 
864
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
865
 
866
		if (!(schemes.size() == 0)) {
867
			size = schemeRepository.selectAllCount();
868
			LOGGER.info("schemes" + schemes);
869
			model.addAttribute("schemes", schemes);
870
			model.addAttribute("start", offset + 1);
871
			model.addAttribute("size", size);
872
			model.addAttribute("searchTerm", searchTerm);
873
			model.addAttribute("searchItem", searchItem);
874
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
875
			if (schemes.size() < limit) {
876
				model.addAttribute("end", offset + schemes.size());
877
			} else {
878
				model.addAttribute("end", offset + limit);
26763 tejbeer 879
			}
26802 tejbeer 880
		}
881
 
26763 tejbeer 882
		return "schemes";
883
	}
26802 tejbeer 884
 
26763 tejbeer 885
	@RequestMapping(value = "/getSchemeByCategoryPaginated")
886
	public String getSchemeByCategoryPaginated(HttpServletRequest request,
887
			@RequestParam(name = "offset", defaultValue = "0") int offset,
888
			@RequestParam(name = "limit", defaultValue = "10") int limit,
889
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem,
890
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
891
			@RequestParam(name = "category", required = true, defaultValue = "") PartnerType category, Model model)
892
			throws ProfitMandiBusinessException {
893
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
894
		LOGGER.info("In search Item....");
895
		List<Scheme> schemes = null;
26802 tejbeer 896
 
26763 tejbeer 897
		schemes = schemeRepository.selectByPartnerType(category, offset, limit);
23506 amit.gupta 898
 
26763 tejbeer 899
		model.addAttribute("schemes", schemes);
900
		model.addAttribute("searchItem", searchItem);
901
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
902
		return "schemes-paginated";
903
	}
904
 
23752 govind 905
	@RequestMapping(value = "/searchScheme")
906
	public String getSchemeBySchemeId(HttpServletRequest request,
907
			@RequestParam(name = "offset", defaultValue = "0") int offset,
908
			@RequestParam(name = "limit", defaultValue = "10") int limit,
909
			@RequestParam(name = "searchTerm", required = false, defaultValue = "") String searchTerm,
910
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
911
			throws ProfitMandiBusinessException {
912
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
913
		List<Scheme> schemes = null;
914
		long size = 0;
915
		if (!(searchTerm.equals("")) && searchItem.equals("")) {
916
			schemes = schemeRepository.selectBySearchTerm(searchTerm, offset, limit);
23786 amit.gupta 917
			if (!(schemes.size() == 0)) {
918
				size = schemeRepository.selectAllCount();
919
				LOGGER.info("schemes" + schemes);
920
				model.addAttribute("schemes", schemes);
921
				model.addAttribute("start", offset + 1);
922
				model.addAttribute("size", size);
923
				model.addAttribute("searchTerm", searchTerm);
924
				model.addAttribute("searchItem", searchItem);
23914 govind 925
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23786 amit.gupta 926
				if (schemes.size() < limit) {
927
					model.addAttribute("end", offset + schemes.size());
928
				} else {
929
					model.addAttribute("end", offset + limit);
930
				}
23752 govind 931
			} else {
23786 amit.gupta 932
				throw new ProfitMandiBusinessException("SchemeId", searchTerm, "SchemeId Not Found");
23752 govind 933
			}
934
		} else if (!(searchItem.equals("")) && searchTerm.equals("")) {
935
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
23786 amit.gupta 936
			if (!(schemeIds.size() == 0)) {
23752 govind 937
				LOGGER.info("schemeIds in searchItemScheme" + schemeIds);
938
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
939
				size = schemeIds.size();
940
				LOGGER.info("Size" + size);
941
				model.addAttribute("schemes", schemes);
942
				model.addAttribute("start", offset + 1);
943
				model.addAttribute("size", size);
944
				model.addAttribute("searchItem", searchItem);
945
				model.addAttribute("searchTerm", searchTerm);
23914 govind 946
				model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 947
				if (schemes.size() < limit) {
948
					model.addAttribute("end", offset + schemes.size());
949
				} else {
950
					model.addAttribute("end", offset + limit);
951
				}
952
 
953
			} else {
954
				throw new ProfitMandiBusinessException("SchemeIds", searchItem, "SchemeId Not Found");
955
			}
956
		} else {
23798 amit.gupta 957
			if (roleManager.isAdmin(loginDetails.getRoleIds())) {
23752 govind 958
				schemes = schemeRepository.selectAll(offset, limit);
959
				size = schemeRepository.selectAllCount();
960
			} else {
961
				schemes = schemeRepository.selectActiveAll(offset, limit);
962
				size = schemeRepository.selectAllActiveCount();
963
			}
964
			model.addAttribute("schemes", schemes);
965
			model.addAttribute("start", offset + 1);
966
			model.addAttribute("size", size);
967
			model.addAttribute("searchItem", searchItem);
968
			model.addAttribute("searchTerm", searchTerm);
23914 govind 969
			model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 970
			if (schemes.size() < limit) {
971
				model.addAttribute("end", offset + schemes.size());
972
			} else {
973
				model.addAttribute("end", offset + limit);
974
			}
975
		}
976
		return "schemes";
977
	}
978
 
979
	@RequestMapping(value = "/searchItemSchemePanigated")
980
	public String getSchemeByItemPanigated(HttpServletRequest request,
981
			@RequestParam(name = "offset", defaultValue = "0") int offset,
982
			@RequestParam(name = "limit", defaultValue = "10") int limit,
983
			@RequestParam(name = "searchItem", required = false, defaultValue = "") String searchItem, Model model)
984
			throws ProfitMandiBusinessException {
23914 govind 985
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23752 govind 986
		LOGGER.info("In search Item....");
987
		List<Scheme> schemes = null;
988
		if (!searchItem.equals("")) {
989
			List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByItemId(Integer.parseInt(searchItem));
990
			if (schemeIds != null) {
991
				LOGGER.info(schemeIds);
992
				schemes = schemeRepository.selectBySchemeIds(schemeIds, offset, limit);
993
 
994
			}
995
		}
996
		model.addAttribute("schemes", schemes);
997
		model.addAttribute("searchItem", searchItem);
23914 govind 998
		model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
23752 govind 999
		return "schemes-paginated";
1000
 
1001
	}
22860 ashik.ali 1002
}