Subversion Repositories SmartDukaan

Rev

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