Subversion Repositories SmartDukaan

Rev

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