Subversion Repositories SmartDukaan

Rev

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