Subversion Repositories SmartDukaan

Rev

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