Subversion Repositories SmartDukaan

Rev

Rev 30957 | Rev 30969 | 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());
27391 tejbeer 156
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
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
		}
27876 amit.gupta 193
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
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);
29926 amit.gupta 205
		// model.addAttribute("response", mvcResponseSender.createResponseString(true));
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
		}
222
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
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 {
230
		String fileName = "offer-" + offer.getId() + ".png";
29948 amit.gupta 231
		String htmlFileName = fileName.replace("png", "html");
29900 amit.gupta 232
		CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
233
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
234
		sendNotificationModel.setCampaignName("SchemeOffer");
235
		sendNotificationModel.setTitle(offer.getName());
29926 amit.gupta 236
		sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
237
				+ FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
238
				+ FormattingUtils.formatDateMonth(offer.getEndDate()));
29900 amit.gupta 239
		sendNotificationModel.setType("url");
240
		sendNotificationModel.setImageUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
241
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
242
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
243
		sendNotificationModel.setMessageType(MessageType.scheme);
244
		Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
30017 amit.gupta 245
 
29900 amit.gupta 246
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
29926 amit.gupta 247
		Map<String, Object> model = new HashMap<>();
248
		model.put("offer", createOfferRequest);
249
		String htmlContent = this.getContentFromTemplate("offer_margin_detail_partner.vm", model);
250
		LOGGER.info("this.getContentFromTemplate {}", htmlContent);
251
		fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
30426 tejbeer 252
		// fileStreamsMap.put(htmlFileName, new
253
		// ByteArrayInputStream(htmlContent.getBytes()));
29926 amit.gupta 254
 
255
		this.uploadFile(fileStreamsMap);
30017 amit.gupta 256
		if (createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0
257
				|| createOfferRequest.getPartnerCriteria().getFofoIds().size() > 0
30723 amit.gupta 258
				|| createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0 ||
259
				createOfferRequest.getPartnerCriteria().getExcludeFofoIds().size() > 0) {
30017 amit.gupta 260
			List<Integer> fofoIds = offersMap.entrySet().stream().filter(x -> x.getValue().contains(offer))
261
					.map(x -> x.getKey()).collect(Collectors.toList());
262
			List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
263
			sendNotificationModel.setUserIds(userIds);
264
			notificationService.sendNotification(sendNotificationModel);
265
		} else {
30723 amit.gupta 266
 
30017 amit.gupta 267
			notificationService.sendNotificationToAll(sendNotificationModel);
268
		}
29900 amit.gupta 269
 
270
	}
29926 amit.gupta 271
 
272
	private InputStream asInputStream(BufferedImage bi) throws Exception {
29900 amit.gupta 273
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
274
		ImageIO.write(bi, "png", baos);
275
		return new ByteArrayInputStream(baos.toByteArray());
29926 amit.gupta 276
 
29900 amit.gupta 277
	}
278
 
279
	private ChannelSftp setupJsch() throws JSchException {
280
		JSch jsch = new JSch();
281
		Session jschSession = jsch.getSession("root", "192.168.179.131");
29926 amit.gupta 282
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
283
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
284
				getClass().getClassLoader().getResource("id_rsa").getPath());
29900 amit.gupta 285
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
29926 amit.gupta 286
		// jschSession.setPassword("spic@2015static0");
29900 amit.gupta 287
		jschSession.setConfig("StrictHostKeyChecking", "no");
288
		jschSession.connect();
289
		return (ChannelSftp) jschSession.openChannel("sftp");
290
	}
291
 
292
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
293
			throws SftpException, FileNotFoundException {
294
 
295
		channelSftp.cd(destinationPath);
296
		String folderName = "image" + LocalDate.now();
297
 
298
		channelSftp.cd(destinationPath);
299
		SftpATTRS attrs = null;
300
 
301
		// check if the directory is already existing
302
		try {
303
			attrs = channelSftp.stat(folderName);
304
		} catch (Exception e) {
305
			System.out.println(destinationPath + "/" + folderName + " not found");
306
		}
307
 
308
		// else create a directory
309
		if (attrs == null) {
310
			channelSftp.mkdir(folderName);
311
			channelSftp.chmod(0755, ".");
312
		}
313
		channelSftp.cd(folderName);
314
 
315
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
316
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
317
		}
318
 
319
	}
29926 amit.gupta 320
 
29900 amit.gupta 321
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
322
		ChannelSftp channelSftp = setupJsch();
323
		channelSftp.connect();
324
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
325
		channelSftp.exit();
326
	}
29926 amit.gupta 327
 
328
	private InputStream getImageBuffer(String html) throws Exception {
329
 
29900 amit.gupta 330
		String fileName = "/tmp/" + Instant.now().toEpochMilli();
331
		FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
29920 amit.gupta 332
		String address = "file:" + fileName;
29921 amit.gupta 333
		Java2DRenderer renderer = new Java2DRenderer(address, 400);
29926 amit.gupta 334
		RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
335
				RenderingHints.VALUE_COLOR_RENDER_QUALITY);
29920 amit.gupta 336
		hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
337
		hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
338
		hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
339
		renderer.setRenderingHints(hints);
340
		BufferedImage img = renderer.getImage();
341
		ByteArrayOutputStream os = new ByteArrayOutputStream();
342
		ImageIO.write(img, "png", os);
343
		return new ByteArrayInputStream(os.toByteArray());
29900 amit.gupta 344
	}
345
 
346
	@Autowired
30470 amit.gupta 347
	private VelocityEngine velocityEngine;
29900 amit.gupta 348
 
30470 amit.gupta 349
 
350
	@Autowired
351
	@Qualifier("velocityAttributesMap")
352
	private Map<String, Object> velocityAttributesMap;
353
 
29900 amit.gupta 354
	private String getContentFromTemplate(String template, Map<String, Object> model) {
355
		StringBuffer content = new StringBuffer();
356
		try {
30470 amit.gupta 357
			((HashMap<String, Object>) (velocityAttributesMap.entrySet().stream().findAny().get()).getValue()).entrySet().stream().forEach(x -> {
358
				model.put(x.getKey(), x.getValue());
359
			});
29900 amit.gupta 360
			content.append(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model));
361
		} catch (Exception e) {
362
			e.printStackTrace();
363
		}
364
		return content.toString();
365
	}
366
 
27876 amit.gupta 367
	@RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
368
	public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
369
			throws ProfitMandiBusinessException {
27391 tejbeer 370
 
29900 amit.gupta 371
		List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
372
				.sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
27876 amit.gupta 373
		model.addAttribute("offers", publishedOffers);
374
		model.addAttribute("yearMonth", yearMonth);
30651 amit.gupta 375
		model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
27391 tejbeer 376
 
377
		return "offer_history";
378
	}
379
 
27876 amit.gupta 380
	@RequestMapping(value = "/offer-details", method = RequestMethod.GET)
381
	public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
27391 tejbeer 382
			throws ProfitMandiBusinessException {
29839 amit.gupta 383
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
27391 tejbeer 384
 
27876 amit.gupta 385
		model.addAttribute("offer", createOfferRequest);
386
		return "offer-details";
27391 tejbeer 387
	}
388
 
30651 amit.gupta 389
	@RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
390
	public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
391
			throws Exception {
392
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
393
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
394
			offerRepository.processSellin(createOfferRequest);
30957 amit.gupta 395
		} else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
396
			offerRepository.processActivationtOffer(createOfferRequest);
30651 amit.gupta 397
		}
398
		return responseSender.ok(true);
399
	}
400
 
27876 amit.gupta 401
	@RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
402
	public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
403
			throws Exception {
404
		List<List<?>> listOfRows = new ArrayList<>();
405
		final HttpHeaders headers = new HttpHeaders();
406
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
407
		headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
29785 amit.gupta 408
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
27876 amit.gupta 409
		Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);
30651 amit.gupta 410
		ByteArrayOutputStream baos = null;
411
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
412
			for (OfferRowModel offerRowModel : offerRowModels) {
413
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
414
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
415
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
416
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
417
						"--", createOfferRequest.getItemCriteriaString(),
418
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
419
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
420
						customRetailer.getCode(), offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getAchievedTarget(),
421
						offerRowModel.getPayoutPurchaseValue(), offerRowModel.getPayout(), offerRowModel.getPayoutType(), offerRowModel.getFinalPayout(), String.join(", ", offerRowModel.getEligibleImeis())));
422
			}
423
			baos = FileUtil.getCSVByteStream(
424
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
425
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
426
							"Base Purchase", "Achieved Target", "Eligible Purchase", "Slab Amount", "Slab Amount Type", "Payout Value(Rs.)",
427
							"Eligible IMEIs"
428
					), listOfRows);
429
		} else {
430
			for (OfferRowModel offerRowModel : offerRowModels) {
431
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
432
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
433
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
434
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
435
						createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
436
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
437
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
30960 amit.gupta 438
						customRetailer.getCode(),
439
 
440
						offerRowModel.getTotalSale(),
441
						offerRowModel.getEligibleSale(),
442
						offerRowModel.getTotalBasePurchaseValue(),
443
						offerRowModel.getCurrentPayoutTarget(),
444
						offerRowModel.getPayoutTargetAchieved(),
445
						offerRowModel.getPayoutValue(),
446
						offerRowModel.getPayoutType(),
447
						offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
30651 amit.gupta 448
						String.join(", ", offerRowModel.getPendingImeis())));
449
			}
450
			baos = FileUtil.getCSVByteStream(
451
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
452
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
30960 amit.gupta 453
 
454
							"Total Value",
455
							"Eligible Value",
456
							//"Achieved Target",
457
							//"Next Target",
458
							//"Eligible Sale DP",
459
							"Total Purchase", "Current Payout Target", "Payout Target Achieved", "Payout Amount", "Payout Amount Type",
460
							"Payout Value DP", "Amount to be credited", "IMEIs pending for Activation"
30651 amit.gupta 461
							// "Payout Sale Qty", "Activated Value", "Activated Qty",
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());
496
		model.addAttribute("response", true);
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
}