Subversion Repositories SmartDukaan

Rev

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