Subversion Repositories SmartDukaan

Rev

Rev 31699 | Rev 31778 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
27391 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.google.gson.Gson;
29943 amit.gupta 4
import com.jcraft.jsch.*;
29900 amit.gupta 5
import com.spice.profitmandi.common.enumuration.MessageType;
27391 tejbeer 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
7
import com.spice.profitmandi.common.model.CustomRetailer;
27876 amit.gupta 8
import com.spice.profitmandi.common.model.ProfitMandiConstants;
29900 amit.gupta 9
import com.spice.profitmandi.common.model.SendNotificationModel;
27876 amit.gupta 10
import com.spice.profitmandi.common.util.FileUtil;
29904 amit.gupta 11
import com.spice.profitmandi.common.util.FormattingUtils;
27876 amit.gupta 12
import com.spice.profitmandi.common.web.util.ResponseSender;
27391 tejbeer 13
import com.spice.profitmandi.dao.entity.catalog.Offer;
14
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
15
import com.spice.profitmandi.dao.enumuration.catalog.ItemCriteriaType;
30651 amit.gupta 16
import com.spice.profitmandi.dao.enumuration.catalog.OfferSchemeType;
27391 tejbeer 17
import com.spice.profitmandi.dao.model.CreateOfferRequest;
27876 amit.gupta 18
import com.spice.profitmandi.dao.model.OfferRowModel;
27391 tejbeer 19
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
20
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
21
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
22
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24
import com.spice.profitmandi.dao.repository.dtr.Mongo;
29926 amit.gupta 25
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
27391 tejbeer 26
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
29900 amit.gupta 27
import com.spice.profitmandi.service.NotificationService;
29785 amit.gupta 28
import com.spice.profitmandi.service.authentication.RoleManager;
27876 amit.gupta 29
import com.spice.profitmandi.service.offers.OfferService;
27391 tejbeer 30
import com.spice.profitmandi.service.user.RetailerService;
31
import com.spice.profitmandi.web.model.LoginDetails;
32
import com.spice.profitmandi.web.util.CookiesProcessor;
33
import com.spice.profitmandi.web.util.MVCResponseSender;
29943 amit.gupta 34
import org.apache.commons.io.FileUtils;
35
import org.apache.commons.io.output.ByteArrayOutputStream;
36
import org.apache.logging.log4j.LogManager;
37
import org.apache.logging.log4j.Logger;
38
import org.apache.velocity.app.VelocityEngine;
39
import org.springframework.beans.factory.annotation.Autowired;
30470 amit.gupta 40
import org.springframework.beans.factory.annotation.Qualifier;
29943 amit.gupta 41
import org.springframework.cache.CacheManager;
42
import org.springframework.core.io.InputStreamResource;
43
import org.springframework.http.HttpHeaders;
44
import org.springframework.http.HttpStatus;
45
import org.springframework.http.ResponseEntity;
46
import org.springframework.stereotype.Controller;
47
import org.springframework.ui.Model;
48
import org.springframework.ui.velocity.VelocityEngineUtils;
49
import org.springframework.web.bind.annotation.*;
50
import org.springframework.web.multipart.MultipartFile;
51
import org.xhtmlrenderer.swing.Java2DRenderer;
27391 tejbeer 52
 
29943 amit.gupta 53
import javax.imageio.ImageIO;
54
import javax.servlet.http.HttpServletRequest;
55
import javax.transaction.Transactional;
56
import java.awt.*;
57
import java.awt.image.BufferedImage;
58
import java.io.ByteArrayInputStream;
59
import java.io.File;
60
import java.io.FileNotFoundException;
61
import java.io.InputStream;
62
import java.time.Instant;
63
import java.time.LocalDate;
64
import java.time.LocalDateTime;
65
import java.time.YearMonth;
66
import java.util.List;
67
import java.util.*;
68
import java.util.stream.Collectors;
69
 
27391 tejbeer 70
@Controller
71
@Transactional(rollbackOn = Throwable.class)
72
public class OfferController {
73
	private static final Logger LOGGER = LogManager.getLogger(OfferController.class);
74
	@Autowired
75
	private OfferRepository offerRepository;
76
 
77
	@Autowired
78
	private OfferMarginRepository offerMarginRepository;
79
 
80
	@Autowired
81
	private FofoStoreRepository fofoStoreRepository;
82
 
83
	@Autowired
27876 amit.gupta 84
	private ResponseSender responseSender;
85
 
86
	@Autowired
27391 tejbeer 87
	private OfferPartnerRepository offerPartnerRepository;
88
 
29900 amit.gupta 89
	private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
90
	private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
29926 amit.gupta 91
 
27391 tejbeer 92
	@Autowired
93
	private ItemRepository itemRepository;
94
 
95
	@Autowired
96
	private MVCResponseSender mvcResponseSender;
97
 
98
	@Autowired
99
	private Gson gson;
100
 
101
	@Autowired
102
	private RetailerService retailerService;
103
 
104
	@Autowired
105
	private Mongo mongoClient;
106
 
107
	@Autowired
29900 amit.gupta 108
	private NotificationService notificationService;
109
 
110
	@Autowired
27391 tejbeer 111
	private CookiesProcessor cookiesProcessor;
112
 
113
	@Autowired
27876 amit.gupta 114
	private OfferService offerService;
29900 amit.gupta 115
 
29809 amit.gupta 116
	@Autowired
117
	private CacheManager thirtyMinsTimeOutCacheManager;
29900 amit.gupta 118
 
29855 amit.gupta 119
	@Autowired
120
	private CacheManager oneDayCacheManager;
27876 amit.gupta 121
 
122
	@Autowired
27391 tejbeer 123
	private PartnerTypeChangeService partnerTypeChangeService;
124
 
125
	@RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
126
	public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
127
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
128
		List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
129
				.collect(Collectors.toList());
130
 
27876 amit.gupta 131
		Set<String> brands = mongoClient.getMongoBrands(loginDetails.getFofoId(), null, 3).stream()
132
				.map(x -> (String) x.get("name")).collect(Collectors.toSet());
30753 amit.gupta 133
		brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
31699 amit.gupta 134
		//Lets allow demo
31700 amit.gupta 135
		brands.add("Live Demo");
27391 tejbeer 136
 
30426 tejbeer 137
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
27391 tejbeer 138
 
30426 tejbeer 139
		Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
140
				.filter(x -> x != null).collect(Collectors.toList()).stream()
141
				.collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
142
 
27391 tejbeer 143
		model.addAttribute("customRetailersMap", customRetailersMap);
144
		model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
145
		model.addAttribute("brands", brands);
146
		model.addAttribute("partnerCategories", PartnerType.values());
27876 amit.gupta 147
		model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
27391 tejbeer 148
		return "scheme_offer";
149
 
150
	}
151
 
152
	@RequestMapping(value = "/createOffer", method = RequestMethod.POST)
153
	public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
30651 amit.gupta 154
							  Model model) throws Exception {
27876 amit.gupta 155
		LOGGER.info("createOfferRequest [{}]", createOfferRequest);
156
		offerService.addOfferService(createOfferRequest);
29809 amit.gupta 157
		thirtyMinsTimeOutCacheManager.getCache("allOffers").evict(YearMonth.now());
31238 amit.gupta 158
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
27391 tejbeer 159
		return "response";
160
 
161
	}
162
 
27876 amit.gupta 163
	@RequestMapping(value = "/offers/published", method = RequestMethod.GET)
164
	public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
27391 tejbeer 165
			throws Exception {
27876 amit.gupta 166
		LOGGER.info("Published");
167
		offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
168
		return "scheme_offer/published";
27391 tejbeer 169
 
27876 amit.gupta 170
	}
27391 tejbeer 171
 
27876 amit.gupta 172
	@RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
30426 tejbeer 173
	public String activateOffer(HttpServletRequest request, @PathVariable(name = "offerId") String offerIdsString,
30651 amit.gupta 174
								Model model, @RequestParam(defaultValue = "true") boolean active)
30426 tejbeer 175
			throws ProfitMandiBusinessException, Exception {
176
		List<Integer> offerIds = Arrays.stream(offerIdsString.split(",")).map(x -> Integer.parseInt(x))
177
				.collect(Collectors.toList());
29943 amit.gupta 178
		List<Offer> offers = offerRepository.selectAllByIds(offerIds);
179
		boolean shouldEvict = false;
180
		for (Offer offer : offers) {
29949 amit.gupta 181
			offer.setAlreadyActive(offer.isActive());
182
			if (offer.isActive() != active) {
29943 amit.gupta 183
				offer.setActive(active);
184
				shouldEvict = true;
185
			}
186
		}
187
		if (shouldEvict) {
29900 amit.gupta 188
			oneDayCacheManager.getCache("catalog.published_yearmonth").evict(YearMonth.now());
189
		}
29949 amit.gupta 190
		for (Offer offer : offers) {
191
			if (active && !offer.isAlreadyActive()) {
192
				this.sendNotification(offer);
193
			}
194
		}
31238 amit.gupta 195
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
27876 amit.gupta 196
		return "response";
29926 amit.gupta 197
		// CreateOfferRequest createOfferRequest =
198
		// offerService.getCreateOfferRequest(offer);
199
		// model.addAttribute("offer", createOfferRequest);
200
		// return "offer_margin_detail_partner2";
27876 amit.gupta 201
	}
29926 amit.gupta 202
 
29920 amit.gupta 203
	@RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
29926 amit.gupta 204
	public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
30651 amit.gupta 205
							@RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
29920 amit.gupta 206
		Offer offer = offerRepository.selectById(offerId);
31238 amit.gupta 207
		// model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29926 amit.gupta 208
		// return "response";
29920 amit.gupta 209
		CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
210
		model.addAttribute("offer", createOfferRequest);
211
		return "offer_margin_detail_partner2";
212
	}
27391 tejbeer 213
 
29900 amit.gupta 214
	@Autowired
215
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
216
 
29917 amit.gupta 217
	@RequestMapping(value = "/offer/active/fofo/{fofoId}", method = RequestMethod.GET)
29926 amit.gupta 218
	public String sendOfferNotification(HttpServletRequest request, @PathVariable int fofoId, Model model,
30651 amit.gupta 219
										@RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
29917 amit.gupta 220
		List<Offer> offers = offerRepository.selectAllPublishedMapByPartner(YearMonth.now()).get(fofoId);
29926 amit.gupta 221
		for (Offer offer : offers) {
29917 amit.gupta 222
			this.sendNotification(offer);
223
		}
31238 amit.gupta 224
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29917 amit.gupta 225
		return "response";
226
	}
29926 amit.gupta 227
 
228
	@Autowired
229
	UserAccountRepository userAccountRepository;
230
 
29900 amit.gupta 231
	private void sendNotification(Offer offer) throws Exception {
31280 amit.gupta 232
		if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
31279 amit.gupta 233
			return;
234
		}
29900 amit.gupta 235
		String fileName = "offer-" + offer.getId() + ".png";
29948 amit.gupta 236
		String htmlFileName = fileName.replace("png", "html");
29900 amit.gupta 237
		CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
238
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
239
		sendNotificationModel.setCampaignName("SchemeOffer");
240
		sendNotificationModel.setTitle(offer.getName());
29926 amit.gupta 241
		sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
242
				+ FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
243
				+ FormattingUtils.formatDateMonth(offer.getEndDate()));
29900 amit.gupta 244
		sendNotificationModel.setType("url");
245
		sendNotificationModel.setImageUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
246
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
247
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
248
		sendNotificationModel.setMessageType(MessageType.scheme);
249
		Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
30017 amit.gupta 250
 
29900 amit.gupta 251
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
29926 amit.gupta 252
		Map<String, Object> model = new HashMap<>();
253
		model.put("offer", createOfferRequest);
254
		String htmlContent = this.getContentFromTemplate("offer_margin_detail_partner.vm", model);
255
		LOGGER.info("this.getContentFromTemplate {}", htmlContent);
256
		fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
30426 tejbeer 257
		// fileStreamsMap.put(htmlFileName, new
258
		// ByteArrayInputStream(htmlContent.getBytes()));
29926 amit.gupta 259
 
260
		this.uploadFile(fileStreamsMap);
30017 amit.gupta 261
		if (createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0
262
				|| createOfferRequest.getPartnerCriteria().getFofoIds().size() > 0
30723 amit.gupta 263
				|| createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0 ||
264
				createOfferRequest.getPartnerCriteria().getExcludeFofoIds().size() > 0) {
30017 amit.gupta 265
			List<Integer> fofoIds = offersMap.entrySet().stream().filter(x -> x.getValue().contains(offer))
266
					.map(x -> x.getKey()).collect(Collectors.toList());
267
			List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
268
			sendNotificationModel.setUserIds(userIds);
269
			notificationService.sendNotification(sendNotificationModel);
270
		} else {
30723 amit.gupta 271
 
30017 amit.gupta 272
			notificationService.sendNotificationToAll(sendNotificationModel);
273
		}
29900 amit.gupta 274
 
275
	}
29926 amit.gupta 276
 
277
	private InputStream asInputStream(BufferedImage bi) throws Exception {
29900 amit.gupta 278
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
279
		ImageIO.write(bi, "png", baos);
280
		return new ByteArrayInputStream(baos.toByteArray());
29926 amit.gupta 281
 
29900 amit.gupta 282
	}
283
 
284
	private ChannelSftp setupJsch() throws JSchException {
285
		JSch jsch = new JSch();
286
		Session jschSession = jsch.getSession("root", "192.168.179.131");
29926 amit.gupta 287
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
288
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
289
				getClass().getClassLoader().getResource("id_rsa").getPath());
29900 amit.gupta 290
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
29926 amit.gupta 291
		// jschSession.setPassword("spic@2015static0");
29900 amit.gupta 292
		jschSession.setConfig("StrictHostKeyChecking", "no");
293
		jschSession.connect();
294
		return (ChannelSftp) jschSession.openChannel("sftp");
295
	}
296
 
297
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
298
			throws SftpException, FileNotFoundException {
299
 
300
		channelSftp.cd(destinationPath);
301
		String folderName = "image" + LocalDate.now();
302
 
303
		channelSftp.cd(destinationPath);
304
		SftpATTRS attrs = null;
305
 
306
		// check if the directory is already existing
307
		try {
308
			attrs = channelSftp.stat(folderName);
309
		} catch (Exception e) {
310
			System.out.println(destinationPath + "/" + folderName + " not found");
311
		}
312
 
313
		// else create a directory
314
		if (attrs == null) {
315
			channelSftp.mkdir(folderName);
316
			channelSftp.chmod(0755, ".");
317
		}
318
		channelSftp.cd(folderName);
319
 
320
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
321
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
322
		}
323
 
324
	}
29926 amit.gupta 325
 
29900 amit.gupta 326
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
327
		ChannelSftp channelSftp = setupJsch();
328
		channelSftp.connect();
329
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
330
		channelSftp.exit();
331
	}
29926 amit.gupta 332
 
333
	private InputStream getImageBuffer(String html) throws Exception {
334
 
29900 amit.gupta 335
		String fileName = "/tmp/" + Instant.now().toEpochMilli();
336
		FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
29920 amit.gupta 337
		String address = "file:" + fileName;
29921 amit.gupta 338
		Java2DRenderer renderer = new Java2DRenderer(address, 400);
29926 amit.gupta 339
		RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
340
				RenderingHints.VALUE_COLOR_RENDER_QUALITY);
29920 amit.gupta 341
		hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
342
		hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
343
		hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
344
		renderer.setRenderingHints(hints);
345
		BufferedImage img = renderer.getImage();
346
		ByteArrayOutputStream os = new ByteArrayOutputStream();
347
		ImageIO.write(img, "png", os);
348
		return new ByteArrayInputStream(os.toByteArray());
29900 amit.gupta 349
	}
350
 
351
	@Autowired
30470 amit.gupta 352
	private VelocityEngine velocityEngine;
29900 amit.gupta 353
 
30470 amit.gupta 354
 
355
	@Autowired
356
	@Qualifier("velocityAttributesMap")
357
	private Map<String, Object> velocityAttributesMap;
358
 
29900 amit.gupta 359
	private String getContentFromTemplate(String template, Map<String, Object> model) {
360
		StringBuffer content = new StringBuffer();
361
		try {
30470 amit.gupta 362
			((HashMap<String, Object>) (velocityAttributesMap.entrySet().stream().findAny().get()).getValue()).entrySet().stream().forEach(x -> {
363
				model.put(x.getKey(), x.getValue());
364
			});
29900 amit.gupta 365
			content.append(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model));
366
		} catch (Exception e) {
367
			e.printStackTrace();
368
		}
369
		return content.toString();
370
	}
371
 
27876 amit.gupta 372
	@RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
373
	public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
374
			throws ProfitMandiBusinessException {
27391 tejbeer 375
 
29900 amit.gupta 376
		List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
377
				.sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
27876 amit.gupta 378
		model.addAttribute("offers", publishedOffers);
379
		model.addAttribute("yearMonth", yearMonth);
30651 amit.gupta 380
		model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
27391 tejbeer 381
 
382
		return "offer_history";
383
	}
384
 
27876 amit.gupta 385
	@RequestMapping(value = "/offer-details", method = RequestMethod.GET)
386
	public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
27391 tejbeer 387
			throws ProfitMandiBusinessException {
29839 amit.gupta 388
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
27391 tejbeer 389
 
27876 amit.gupta 390
		model.addAttribute("offer", createOfferRequest);
391
		return "offer-details";
27391 tejbeer 392
	}
393
 
30651 amit.gupta 394
	@RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
395
	public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
396
			throws Exception {
397
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
30996 amit.gupta 398
		if (!createOfferRequest.isActive()) {
399
			throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
400
		}
30651 amit.gupta 401
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
402
			offerRepository.processSellin(createOfferRequest);
30957 amit.gupta 403
		} else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
404
			offerRepository.processActivationtOffer(createOfferRequest);
30651 amit.gupta 405
		}
406
		return responseSender.ok(true);
407
	}
408
 
27876 amit.gupta 409
	@RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
410
	public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
411
			throws Exception {
412
		List<List<?>> listOfRows = new ArrayList<>();
413
		final HttpHeaders headers = new HttpHeaders();
414
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
415
		headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
29785 amit.gupta 416
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
27876 amit.gupta 417
		Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);
30651 amit.gupta 418
		ByteArrayOutputStream baos = null;
419
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
420
			for (OfferRowModel offerRowModel : offerRowModels) {
421
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
422
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
423
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
424
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
425
						"--", createOfferRequest.getItemCriteriaString(),
426
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
427
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
428
						customRetailer.getCode(), offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getAchievedTarget(),
429
						offerRowModel.getPayoutPurchaseValue(), offerRowModel.getPayout(), offerRowModel.getPayoutType(), offerRowModel.getFinalPayout(), String.join(", ", offerRowModel.getEligibleImeis())));
430
			}
431
			baos = FileUtil.getCSVByteStream(
432
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
433
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
434
							"Base Purchase", "Achieved Target", "Eligible Purchase", "Slab Amount", "Slab Amount Type", "Payout Value(Rs.)",
435
							"Eligible IMEIs"
436
					), listOfRows);
437
		} else {
438
			for (OfferRowModel offerRowModel : offerRowModels) {
439
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
440
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
441
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
442
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
443
						createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
444
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
445
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
30960 amit.gupta 446
						customRetailer.getCode(),
447
 
448
						offerRowModel.getTotalSale(),
449
						offerRowModel.getEligibleSale(),
450
						offerRowModel.getPayoutTargetAchieved(),
451
						offerRowModel.getPayoutValue(),
452
						offerRowModel.getPayoutType(),
453
						offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
30979 amit.gupta 454
						String.join(", ", offerRowModel.getEligibleImeis())));
30651 amit.gupta 455
			}
456
			baos = FileUtil.getCSVByteStream(
457
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
458
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
30960 amit.gupta 459
 
460
							"Total Value",
461
							"Eligible Value",
30969 amit.gupta 462
							"Payout Target Achieved", "Payout Amount", "Payout Amount Type",
30979 amit.gupta 463
							"Payout Value DP", "Amount to be credited", "Eligible Activated Imeis"
30651 amit.gupta 464
					), listOfRows);
27391 tejbeer 465
		}
27876 amit.gupta 466
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
467
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
468
		return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
27391 tejbeer 469
	}
29900 amit.gupta 470
 
27876 amit.gupta 471
	@RequestMapping(value = "/offerById", method = RequestMethod.GET)
472
	public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
27391 tejbeer 473
		Offer offer = offerRepository.selectById(offerId);
474
 
475
		model.addAttribute("offer", offer);
476
 
27876 amit.gupta 477
		return "offer-edit";
27391 tejbeer 478
 
479
	}
29900 amit.gupta 480
 
29675 amit.gupta 481
	@RequestMapping(value = "/published-offers/{yearMonth}", method = RequestMethod.GET)
29900 amit.gupta 482
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
483
			throws ProfitMandiBusinessException {
29675 amit.gupta 484
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
485
		int fofoId = loginDetails.getFofoId();
29900 amit.gupta 486
		List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
487
				YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
488
 
29675 amit.gupta 489
		model.addAttribute("publishedOffers", createOffers);
29900 amit.gupta 490
 
29675 amit.gupta 491
		return "published-offers";
492
	}
29900 amit.gupta 493
 
29682 amit.gupta 494
	@PostMapping(value = "/offers/upload")
495
	public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
496
			throws Exception {
497
		offerService.createOffers(targetFile.getInputStream());
31238 amit.gupta 498
		model.addAttribute("response1", true);
29682 amit.gupta 499
		return "response";
500
	}
29900 amit.gupta 501
 
29785 amit.gupta 502
	@Autowired
503
	RoleManager roleManager;
27391 tejbeer 504
 
27876 amit.gupta 505
	@RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
506
	public String getOfferMargins(HttpServletRequest request,
30651 amit.gupta 507
								  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
27876 amit.gupta 508
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29785 amit.gupta 509
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
29900 amit.gupta 510
		CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
511
 
27876 amit.gupta 512
		model.addAttribute("offer", createOfferRequest);
27391 tejbeer 513
 
27876 amit.gupta 514
		return "offer_margin_detail_partner";
27391 tejbeer 515
 
516
	}
517
 
27895 amit.gupta 518
}