Subversion Repositories SmartDukaan

Rev

Rev 30651 | Rev 30753 | 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
30723 amit.gupta 257
				|| createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0 ||
258
				createOfferRequest.getPartnerCriteria().getExcludeFofoIds().size() > 0) {
30017 amit.gupta 259
			List<Integer> fofoIds = offersMap.entrySet().stream().filter(x -> x.getValue().contains(offer))
260
					.map(x -> x.getKey()).collect(Collectors.toList());
261
			List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
262
			sendNotificationModel.setUserIds(userIds);
263
			notificationService.sendNotification(sendNotificationModel);
264
		} else {
30723 amit.gupta 265
 
30017 amit.gupta 266
			notificationService.sendNotificationToAll(sendNotificationModel);
267
		}
29900 amit.gupta 268
 
269
	}
29926 amit.gupta 270
 
271
	private InputStream asInputStream(BufferedImage bi) throws Exception {
29900 amit.gupta 272
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
273
		ImageIO.write(bi, "png", baos);
274
		return new ByteArrayInputStream(baos.toByteArray());
29926 amit.gupta 275
 
29900 amit.gupta 276
	}
277
 
278
	private ChannelSftp setupJsch() throws JSchException {
279
		JSch jsch = new JSch();
280
		Session jschSession = jsch.getSession("root", "192.168.179.131");
29926 amit.gupta 281
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
282
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
283
				getClass().getClassLoader().getResource("id_rsa").getPath());
29900 amit.gupta 284
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
29926 amit.gupta 285
		// jschSession.setPassword("spic@2015static0");
29900 amit.gupta 286
		jschSession.setConfig("StrictHostKeyChecking", "no");
287
		jschSession.connect();
288
		return (ChannelSftp) jschSession.openChannel("sftp");
289
	}
290
 
291
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
292
			throws SftpException, FileNotFoundException {
293
 
294
		channelSftp.cd(destinationPath);
295
		String folderName = "image" + LocalDate.now();
296
 
297
		channelSftp.cd(destinationPath);
298
		SftpATTRS attrs = null;
299
 
300
		// check if the directory is already existing
301
		try {
302
			attrs = channelSftp.stat(folderName);
303
		} catch (Exception e) {
304
			System.out.println(destinationPath + "/" + folderName + " not found");
305
		}
306
 
307
		// else create a directory
308
		if (attrs == null) {
309
			channelSftp.mkdir(folderName);
310
			channelSftp.chmod(0755, ".");
311
		}
312
		channelSftp.cd(folderName);
313
 
314
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
315
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
316
		}
317
 
318
	}
29926 amit.gupta 319
 
29900 amit.gupta 320
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
321
		ChannelSftp channelSftp = setupJsch();
322
		channelSftp.connect();
323
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
324
		channelSftp.exit();
325
	}
29926 amit.gupta 326
 
327
	private InputStream getImageBuffer(String html) throws Exception {
328
 
29900 amit.gupta 329
		String fileName = "/tmp/" + Instant.now().toEpochMilli();
330
		FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
29920 amit.gupta 331
		String address = "file:" + fileName;
29921 amit.gupta 332
		Java2DRenderer renderer = new Java2DRenderer(address, 400);
29926 amit.gupta 333
		RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
334
				RenderingHints.VALUE_COLOR_RENDER_QUALITY);
29920 amit.gupta 335
		hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
336
		hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
337
		hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
338
		renderer.setRenderingHints(hints);
339
		BufferedImage img = renderer.getImage();
340
		ByteArrayOutputStream os = new ByteArrayOutputStream();
341
		ImageIO.write(img, "png", os);
342
		return new ByteArrayInputStream(os.toByteArray());
29900 amit.gupta 343
	}
344
 
345
	@Autowired
30470 amit.gupta 346
	private VelocityEngine velocityEngine;
29900 amit.gupta 347
 
30470 amit.gupta 348
 
349
	@Autowired
350
	@Qualifier("velocityAttributesMap")
351
	private Map<String, Object> velocityAttributesMap;
352
 
29900 amit.gupta 353
	private String getContentFromTemplate(String template, Map<String, Object> model) {
354
		StringBuffer content = new StringBuffer();
355
		try {
30470 amit.gupta 356
			((HashMap<String, Object>) (velocityAttributesMap.entrySet().stream().findAny().get()).getValue()).entrySet().stream().forEach(x -> {
357
				model.put(x.getKey(), x.getValue());
358
			});
29900 amit.gupta 359
			content.append(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model));
360
		} catch (Exception e) {
361
			e.printStackTrace();
362
		}
363
		return content.toString();
364
	}
365
 
27876 amit.gupta 366
	@RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
367
	public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
368
			throws ProfitMandiBusinessException {
27391 tejbeer 369
 
29900 amit.gupta 370
		List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
371
				.sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
27876 amit.gupta 372
		model.addAttribute("offers", publishedOffers);
373
		model.addAttribute("yearMonth", yearMonth);
30651 amit.gupta 374
		model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
27391 tejbeer 375
 
376
		return "offer_history";
377
	}
378
 
27876 amit.gupta 379
	@RequestMapping(value = "/offer-details", method = RequestMethod.GET)
380
	public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
27391 tejbeer 381
			throws ProfitMandiBusinessException {
29839 amit.gupta 382
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
27391 tejbeer 383
 
27876 amit.gupta 384
		model.addAttribute("offer", createOfferRequest);
385
		return "offer-details";
27391 tejbeer 386
	}
387
 
30651 amit.gupta 388
	@RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
389
	public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
390
			throws Exception {
391
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
392
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
393
			offerRepository.processSellin(createOfferRequest);
394
		}
395
		return responseSender.ok(true);
396
	}
397
 
27876 amit.gupta 398
	@RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
399
	public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
400
			throws Exception {
401
		List<List<?>> listOfRows = new ArrayList<>();
402
		final HttpHeaders headers = new HttpHeaders();
403
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
404
		headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
29785 amit.gupta 405
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
27876 amit.gupta 406
		Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);
30651 amit.gupta 407
		ByteArrayOutputStream baos = null;
408
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
409
			for (OfferRowModel offerRowModel : offerRowModels) {
410
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
411
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
412
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
413
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
414
						"--", createOfferRequest.getItemCriteriaString(),
415
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
416
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
417
						customRetailer.getCode(), offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getAchievedTarget(),
418
						offerRowModel.getPayoutPurchaseValue(), offerRowModel.getPayout(), offerRowModel.getPayoutType(), offerRowModel.getFinalPayout(), String.join(", ", offerRowModel.getEligibleImeis())));
419
			}
420
			baos = FileUtil.getCSVByteStream(
421
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
422
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
423
							"Base Purchase", "Achieved Target", "Eligible Purchase", "Slab Amount", "Slab Amount Type", "Payout Value(Rs.)",
424
							"Eligible IMEIs"
425
					), listOfRows);
426
		} else {
27391 tejbeer 427
 
30651 amit.gupta 428
			for (OfferRowModel offerRowModel : offerRowModels) {
429
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
430
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
431
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
432
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
433
						createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
434
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
435
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
436
						customRetailer.getCode(), offerRowModel.getTotalSale(), offerRowModel.getEligibleSale(),
437
						offerRowModel.getAchievedTarget(), offerRowModel.getNextTarget(), offerRowModel.getEligibleSaleDp(),
438
						offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getCurrentPayoutTarget(),
439
						offerRowModel.getPayoutTargetAchieved(), offerRowModel.getPayoutType(),
440
						offerRowModel.getPayoutValue(), offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
441
						String.join(", ", offerRowModel.getPendingImeis())));
442
			}
443
			baos = FileUtil.getCSVByteStream(
444
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
445
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
446
							"Total Value", "Eligible Value", "Achieved Target", "Next Target", "Eligible Sale DP",
447
							"Total Purchase DP", "Current Payout Target", "Payout Target Achieved", "Payout Amount Type",
448
							"Payout Value", "Payout Value DP", "Amount to be credited", "IMEIs pending for Activation"
449
							// "Payout Sale Qty", "Activated Value", "Activated Qty",
450
					), listOfRows);
27391 tejbeer 451
		}
27876 amit.gupta 452
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
453
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
454
		return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
27391 tejbeer 455
	}
29900 amit.gupta 456
 
27876 amit.gupta 457
	@RequestMapping(value = "/offerById", method = RequestMethod.GET)
458
	public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
27391 tejbeer 459
		Offer offer = offerRepository.selectById(offerId);
460
 
461
		model.addAttribute("offer", offer);
462
 
27876 amit.gupta 463
		return "offer-edit";
27391 tejbeer 464
 
465
	}
29900 amit.gupta 466
 
29675 amit.gupta 467
	@RequestMapping(value = "/published-offers/{yearMonth}", method = RequestMethod.GET)
29900 amit.gupta 468
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
469
			throws ProfitMandiBusinessException {
29675 amit.gupta 470
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
471
		int fofoId = loginDetails.getFofoId();
29900 amit.gupta 472
		List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
473
				YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
474
 
29675 amit.gupta 475
		model.addAttribute("publishedOffers", createOffers);
29900 amit.gupta 476
 
29675 amit.gupta 477
		return "published-offers";
478
	}
29900 amit.gupta 479
 
29682 amit.gupta 480
	@PostMapping(value = "/offers/upload")
481
	public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
482
			throws Exception {
483
		offerService.createOffers(targetFile.getInputStream());
484
		model.addAttribute("response", true);
485
		return "response";
486
	}
29900 amit.gupta 487
 
29785 amit.gupta 488
	@Autowired
489
	RoleManager roleManager;
27391 tejbeer 490
 
27876 amit.gupta 491
	@RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
492
	public String getOfferMargins(HttpServletRequest request,
30651 amit.gupta 493
								  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
27876 amit.gupta 494
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29785 amit.gupta 495
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
29900 amit.gupta 496
		CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
497
 
27876 amit.gupta 498
		model.addAttribute("offer", createOfferRequest);
27391 tejbeer 499
 
27876 amit.gupta 500
		return "offer_margin_detail_partner";
27391 tejbeer 501
 
502
	}
503
 
27895 amit.gupta 504
}