Subversion Repositories SmartDukaan

Rev

Rev 32204 | Rev 32510 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 32204 Rev 32505
Line 70... Line 70...
70
import java.util.stream.Collectors;
70
import java.util.stream.Collectors;
71
 
71
 
72
@Controller
72
@Controller
73
@Transactional(rollbackOn = Throwable.class)
73
@Transactional(rollbackOn = Throwable.class)
74
public class OfferController {
74
public class OfferController {
75
	private static final Logger LOGGER = LogManager.getLogger(OfferController.class);
75
    private static final Logger LOGGER = LogManager.getLogger(OfferController.class);
76
	@Autowired
76
    private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
77
	private OfferRepository offerRepository;
77
    private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
78
 
78
    @Autowired
79
	@Autowired
79
    UserAccountRepository userAccountRepository;
80
	private OfferMarginRepository offerMarginRepository;
80
    @Autowired
81
 
81
    RoleManager roleManager;
82
	@Autowired
82
    @Autowired
83
	private FofoStoreRepository fofoStoreRepository;
83
    private OfferRepository offerRepository;
84
 
84
    @Autowired
85
	@Autowired
85
    private OfferMarginRepository offerMarginRepository;
86
	private ResponseSender responseSender;
86
    @Autowired
87
 
87
    private FofoStoreRepository fofoStoreRepository;
88
	@Autowired
88
    @Autowired
89
	private ViewResolver viewResolver;
89
    private ResponseSender responseSender;
90
 
90
    @Autowired
91
	@Autowired
91
    private ViewResolver viewResolver;
92
	private OfferPartnerRepository offerPartnerRepository;
92
    @Autowired
93
 
93
    private OfferPartnerRepository offerPartnerRepository;
94
	private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
94
    @Autowired
95
	private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
95
    private ItemRepository itemRepository;
96
 
96
    @Autowired
97
	@Autowired
97
    private MVCResponseSender mvcResponseSender;
98
	private ItemRepository itemRepository;
98
    @Autowired
99
 
99
    private Gson gson;
100
	@Autowired
100
    @Autowired
101
	private MVCResponseSender mvcResponseSender;
101
    private RetailerService retailerService;
102
 
102
    @Autowired
103
	@Autowired
103
    private Mongo mongoClient;
104
	private Gson gson;
104
    @Autowired
105
 
105
    private NotificationService notificationService;
106
	@Autowired
106
    @Autowired
107
	private RetailerService retailerService;
107
    private CookiesProcessor cookiesProcessor;
108
 
108
    @Autowired
109
	@Autowired
109
    private OfferService offerService;
110
	private Mongo mongoClient;
110
    @Autowired
111
 
111
    private CacheManager thirtyMinsTimeOutCacheManager;
112
	@Autowired
112
    @Autowired
113
	private NotificationService notificationService;
113
    private CacheManager oneDayCacheManager;
114
 
114
    @Autowired
115
	@Autowired
115
    private PartnerTypeChangeService partnerTypeChangeService;
116
	private CookiesProcessor cookiesProcessor;
116
    @Autowired
117
 
117
    private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
118
	@Autowired
118
    @Autowired
119
	private OfferService offerService;
119
    private VelocityEngine velocityEngine;
120
 
120
 
121
	@Autowired
121
    @RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
122
	private CacheManager thirtyMinsTimeOutCacheManager;
122
    public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
123
 
123
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
124
	@Autowired
124
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
125
	private CacheManager oneDayCacheManager;
125
                .collect(Collectors.toList());
126
 
126
 
127
	@Autowired
127
        Set<String> brands = mongoClient.getMongoBrands(loginDetails.getFofoId(), null, 3).stream()
128
	private PartnerTypeChangeService partnerTypeChangeService;
128
                .map(x -> (String) x.get("name")).collect(Collectors.toSet());
129
 
129
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
130
	@RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
130
        //Lets allow demo
131
	public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
131
        brands.add("Live Demo");
132
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
132
 
133
		List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
133
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
134
				.collect(Collectors.toList());
134
 
135
 
135
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
136
		Set<String> brands = mongoClient.getMongoBrands(loginDetails.getFofoId(), null, 3).stream()
136
                .filter(x -> x != null).collect(Collectors.toList()).stream()
137
				.map(x -> (String) x.get("name")).collect(Collectors.toSet());
137
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
138
		brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
138
 
139
		//Lets allow demo
139
        model.addAttribute("customRetailersMap", customRetailersMap);
140
		brands.add("Live Demo");
140
        model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
141
 
141
        model.addAttribute("brands", brands);
142
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
142
        model.addAttribute("partnerCategories", PartnerType.values());
143
 
143
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
144
		Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
144
        return "scheme_offer";
145
				.filter(x -> x != null).collect(Collectors.toList()).stream()
145
 
146
				.collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
146
    }
147
 
147
 
148
		model.addAttribute("customRetailersMap", customRetailersMap);
148
    @RequestMapping(value = "/createOffer", method = RequestMethod.POST)
149
		model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
149
    public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
150
		model.addAttribute("brands", brands);
150
                              Model model) throws Exception {
151
		model.addAttribute("partnerCategories", PartnerType.values());
151
        LOGGER.info("createOfferRequest [{}]", createOfferRequest);
152
		model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
152
        offerService.addOfferService(createOfferRequest);
153
		return "scheme_offer";
153
        thirtyMinsTimeOutCacheManager.getCache("allOffers").evict(YearMonth.now());
154
 
154
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
155
	}
155
        return "response";
156
 
156
 
157
	@RequestMapping(value = "/createOffer", method = RequestMethod.POST)
157
    }
158
	public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
158
 
159
							  Model model) throws Exception {
159
    @RequestMapping(value = "/offers/published", method = RequestMethod.GET)
160
		LOGGER.info("createOfferRequest [{}]", createOfferRequest);
160
    public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
161
		offerService.addOfferService(createOfferRequest);
161
            throws Exception {
162
		thirtyMinsTimeOutCacheManager.getCache("allOffers").evict(YearMonth.now());
162
        LOGGER.info("Published");
163
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
163
        offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
164
		return "response";
164
        return "scheme_offer/published";
165
 
165
 
166
	}
166
    }
167
 
167
 
168
	@RequestMapping(value = "/offers/published", method = RequestMethod.GET)
168
    @RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
169
	public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
169
    public String activateOffer(HttpServletRequest request, @PathVariable(name = "offerId") String offerIdsString,
170
			throws Exception {
170
                                Model model, @RequestParam(defaultValue = "true") boolean active)
171
		LOGGER.info("Published");
171
            throws ProfitMandiBusinessException, Exception {
172
		offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
172
        List<Integer> offerIds = Arrays.stream(offerIdsString.split(",")).map(x -> Integer.parseInt(x))
173
		return "scheme_offer/published";
173
                .collect(Collectors.toList());
174
 
174
        List<Offer> offers = offerRepository.selectAllByIds(offerIds);
175
	}
175
        boolean shouldEvict = false;
176
 
176
        for (Offer offer : offers) {
177
	@RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
177
            offer.setAlreadyActive(offer.isActive());
178
	public String activateOffer(HttpServletRequest request, @PathVariable(name = "offerId") String offerIdsString,
178
            if (offer.isActive() != active) {
179
								Model model, @RequestParam(defaultValue = "true") boolean active)
179
                offer.setActive(active);
180
			throws ProfitMandiBusinessException, Exception {
180
                shouldEvict = true;
181
		List<Integer> offerIds = Arrays.stream(offerIdsString.split(",")).map(x -> Integer.parseInt(x))
181
            }
182
				.collect(Collectors.toList());
182
        }
183
		List<Offer> offers = offerRepository.selectAllByIds(offerIds);
183
        if (shouldEvict) {
184
		boolean shouldEvict = false;
184
            oneDayCacheManager.getCache("catalog.published_yearmonth").evict(YearMonth.now());
185
		for (Offer offer : offers) {
185
        }
186
			offer.setAlreadyActive(offer.isActive());
186
        for (Offer offer : offers) {
187
			if (offer.isActive() != active) {
187
            if (active && !offer.isAlreadyActive()) {
188
				offer.setActive(active);
188
                this.sendNotification(offer);
189
				shouldEvict = true;
189
            }
190
			}
190
        }
191
		}
191
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
192
		if (shouldEvict) {
192
        return "response";
193
			oneDayCacheManager.getCache("catalog.published_yearmonth").evict(YearMonth.now());
193
        // CreateOfferRequest createOfferRequest =
194
		}
194
        // offerService.getCreateOfferRequest(offer);
195
		for (Offer offer : offers) {
195
        // model.addAttribute("offer", createOfferRequest);
196
			if (active && !offer.isAlreadyActive()) {
196
        // return "offer_margin_detail_partner2";
197
				this.sendNotification(offer);
197
    }
198
			}
198
 
199
		}
199
    @RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
200
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
200
    public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
201
		return "response";
201
                            @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
202
		// CreateOfferRequest createOfferRequest =
202
        Offer offer = offerRepository.selectById(offerId);
203
		// offerService.getCreateOfferRequest(offer);
203
        // model.addAttribute("response1", mvcResponseSender.createResponseString(true));
204
		// model.addAttribute("offer", createOfferRequest);
204
        // return "response";
205
		// return "offer_margin_detail_partner2";
205
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
206
	}
206
        Map<String, Object> model1 = new HashMap<>();
207
 
207
        model1.put("offer", createOfferRequest);
208
	@RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
208
        model1.put("lessThan", "<");
209
	public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
209
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
210
							@RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
210
        model.addAttribute("response1", htmlContent);
211
		Offer offer = offerRepository.selectById(offerId);
211
        return "response";
212
		// model.addAttribute("response1", mvcResponseSender.createResponseString(true));
212
    }
213
		// return "response";
213
 
214
		CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
214
    @RequestMapping(value = "/offer/active/fofo/{fofoId}", method = RequestMethod.GET)
215
		Map<String, Object> model1 = new HashMap<>();
215
    public String sendOfferNotification(HttpServletRequest request, @PathVariable int fofoId, Model model,
216
		model1.put("offer", createOfferRequest);
216
                                        @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
217
		model1.put("lessThan", "<");
217
        List<Offer> offers = offerRepository.selectAllPublishedMapByPartner(YearMonth.now()).get(fofoId);
218
		String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
218
        for (Offer offer : offers) {
219
		model.addAttribute("response1", htmlContent);
219
            this.sendNotification(offer);
220
		return "response";
220
        }
221
	}
221
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
222
 
222
        return "response";
223
	@Autowired
223
    }
224
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
224
 
225
 
225
    private void sendNotification(Offer offer) throws Exception {
226
	@RequestMapping(value = "/offer/active/fofo/{fofoId}", method = RequestMethod.GET)
226
        if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
227
	public String sendOfferNotification(HttpServletRequest request, @PathVariable int fofoId, Model model,
227
            return;
228
										@RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
228
        }
229
		List<Offer> offers = offerRepository.selectAllPublishedMapByPartner(YearMonth.now()).get(fofoId);
229
        String fileName = "offer-" + offer.getId() + ".png";
230
		for (Offer offer : offers) {
230
        String htmlFileName = fileName.replace("png", "html");
231
			this.sendNotification(offer);
231
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
232
		}
232
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
233
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
233
        sendNotificationModel.setCampaignName("SchemeOffer");
234
		return "response";
234
        sendNotificationModel.setTitle(offer.getName());
235
	}
235
        sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
236
 
236
                + FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
237
	@Autowired
237
                + FormattingUtils.formatDateMonth(offer.getEndDate()));
238
	UserAccountRepository userAccountRepository;
238
        sendNotificationModel.setType("url");
239
 
239
        String imageUrl = IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName;
240
	private void sendNotification(Offer offer) throws Exception {
240
        sendNotificationModel.setImageUrl(imageUrl);
241
		if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
241
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
242
			return;
242
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
243
		}
243
        sendNotificationModel.setMessageType(MessageType.scheme);
244
		String fileName = "offer-" + offer.getId() + ".png";
244
        Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
245
		String htmlFileName = fileName.replace("png", "html");
245
 
246
		CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
246
        Map<String, InputStream> fileStreamsMap = new HashMap<>();
247
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
247
        Map<String, Object> model = new HashMap<>();
248
		sendNotificationModel.setCampaignName("SchemeOffer");
248
        model.put("offer", createOfferRequest);
249
		sendNotificationModel.setTitle(offer.getName());
249
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
250
		sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
250
        LOGGER.info("this.getContentFromTemplate {}", htmlContent);
251
				+ FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
251
        fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
252
				+ FormattingUtils.formatDateMonth(offer.getEndDate()));
252
        // fileStreamsMap.put(htmlFileName, new
253
		sendNotificationModel.setType("url");
253
        // ByteArrayInputStream(htmlContent.getBytes()));
254
		sendNotificationModel.setImageUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
254
        List<Integer> fofoIds = null;
255
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
255
        this.uploadFile(fileStreamsMap);
256
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
256
        if (createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0
257
		sendNotificationModel.setMessageType(MessageType.scheme);
257
                || createOfferRequest.getPartnerCriteria().getFofoIds().size() > 0
258
		Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
258
                || createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0 ||
259
 
259
                createOfferRequest.getPartnerCriteria().getExcludeFofoIds().size() > 0) {
260
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
260
            fofoIds = offersMap.entrySet().stream().filter(x -> x.getValue().contains(offer))
261
		Map<String, Object> model = new HashMap<>();
261
                    .map(x -> x.getKey()).collect(Collectors.toList());
262
		model.put("offer", createOfferRequest);
262
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
263
		String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
263
            sendNotificationModel.setUserIds(userIds);
264
		LOGGER.info("this.getContentFromTemplate {}", htmlContent);
264
            notificationService.sendNotification(sendNotificationModel);
265
		fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
265
        } else {
266
		// fileStreamsMap.put(htmlFileName, new
266
            notificationService.sendNotificationToAll(sendNotificationModel);
267
		// ByteArrayInputStream(htmlContent.getBytes()));
267
        }
268
 
268
        this.sendWhatsapp(offer, fofoIds, imageUrl);
269
		this.uploadFile(fileStreamsMap);
269
 
270
		if (createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0
270
    }
271
				|| createOfferRequest.getPartnerCriteria().getFofoIds().size() > 0
271
 
272
				|| createOfferRequest.getPartnerCriteria().getRegionIds().size() > 0 ||
272
    private void sendWhatsapp(Offer offer, List<Integer> fofoIds, String imageUrl) throws Exception {
273
				createOfferRequest.getPartnerCriteria().getExcludeFofoIds().size() > 0) {
273
        if (fofoIds == null) {
274
			List<Integer> fofoIds = offersMap.entrySet().stream().filter(x -> x.getValue().contains(offer))
274
            fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toList());
275
					.map(x -> x.getKey()).collect(Collectors.toList());
275
        }
276
			List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
276
        final List<Integer> finalFofoIds = fofoIds;
277
			sendNotificationModel.setUserIds(userIds);
277
        List<String> mobileNumbers = retailerService.getAllFofoRetailers().entrySet().stream().filter(x -> finalFofoIds.contains(x.getKey())).map(x -> x.getValue().getMobileNumber()).collect(Collectors.toList());
278
			notificationService.sendNotification(sendNotificationModel);
278
        String message = "%s\n" +
279
		} else {
279
                "On %s of select models\n" +
280
 
280
                "From %s to %s\n" +
281
			notificationService.sendNotificationToAll(sendNotificationModel);
281
                "\n" +
282
		}
282
                "Happy Selling\n" +
283
 
283
                "Team Smartdukaan";
284
	}
284
 
285
 
285
        for (String mobileNumber : mobileNumbers) {
286
	private InputStream asInputStream(BufferedImage bi) throws Exception {
286
            notificationService.sendWhatsappMediaMessage(String.format(message, offer.getName(), offer.getSchemeType().toString(), FormattingUtils.formatDate(offer.getStartDate()), FormattingUtils.formatDate(offer.getEndDate())), mobileNumber, imageUrl, "offer-" + offer.getId() + ".png");
287
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
287
        }
288
		ImageIO.write(bi, "png", baos);
288
    }
289
		return new ByteArrayInputStream(baos.toByteArray());
289
 
290
 
290
    private InputStream asInputStream(BufferedImage bi) throws Exception {
291
	}
291
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
292
 
292
        ImageIO.write(bi, "png", baos);
293
	private ChannelSftp setupJsch() throws JSchException {
293
        return new ByteArrayInputStream(baos.toByteArray());
294
		JSch jsch = new JSch();
294
 
295
		Session jschSession = jsch.getSession("root", "192.168.179.131");
295
    }
296
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
296
 
297
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
297
    private ChannelSftp setupJsch() throws JSchException {
298
				getClass().getClassLoader().getResource("id_rsa").getPath());
298
        JSch jsch = new JSch();
299
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
299
        Session jschSession = jsch.getSession("root", "192.168.179.131");
300
		// jschSession.setPassword("spic@2015static0");
300
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
301
		jschSession.setConfig("StrictHostKeyChecking", "no");
301
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
302
		jschSession.connect();
302
                getClass().getClassLoader().getResource("id_rsa").getPath());
303
		return (ChannelSftp) jschSession.openChannel("sftp");
303
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
304
	}
304
        // jschSession.setPassword("spic@2015static0");
305
 
305
        jschSession.setConfig("StrictHostKeyChecking", "no");
306
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
306
        jschSession.connect();
307
			throws SftpException, FileNotFoundException {
307
        return (ChannelSftp) jschSession.openChannel("sftp");
308
 
308
    }
309
		channelSftp.cd(destinationPath);
309
 
310
		String folderName = "image" + LocalDate.now();
310
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
311
 
311
            throws SftpException, FileNotFoundException {
312
		channelSftp.cd(destinationPath);
312
 
313
		SftpATTRS attrs = null;
313
        channelSftp.cd(destinationPath);
314
 
314
        String folderName = "image" + LocalDate.now();
315
		// check if the directory is already existing
315
 
316
		try {
316
        channelSftp.cd(destinationPath);
317
			attrs = channelSftp.stat(folderName);
317
        SftpATTRS attrs = null;
318
		} catch (Exception e) {
318
 
319
			System.out.println(destinationPath + "/" + folderName + " not found");
319
        // check if the directory is already existing
320
		}
320
        try {
321
 
321
            attrs = channelSftp.stat(folderName);
322
		// else create a directory
322
        } catch (Exception e) {
323
		if (attrs == null) {
323
            System.out.println(destinationPath + "/" + folderName + " not found");
324
			channelSftp.mkdir(folderName);
324
        }
325
			channelSftp.chmod(0755, ".");
325
 
326
		}
326
        // else create a directory
327
		channelSftp.cd(folderName);
327
        if (attrs == null) {
328
 
328
            channelSftp.mkdir(folderName);
329
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
329
            channelSftp.chmod(0755, ".");
330
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
330
        }
331
		}
331
        channelSftp.cd(folderName);
332
 
332
 
333
	}
333
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
334
 
334
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
335
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
335
        }
336
		ChannelSftp channelSftp = setupJsch();
336
 
337
		channelSftp.connect();
337
    }
338
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
338
 
339
		channelSftp.exit();
339
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
340
	}
340
        ChannelSftp channelSftp = setupJsch();
341
 
341
        channelSftp.connect();
342
	private InputStream getImageBuffer(String html) throws Exception {
342
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
343
 
343
        channelSftp.exit();
344
		String fileName = "/tmp/" + Instant.now().toEpochMilli();
344
    }
345
		FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
345
 
346
		String address = "file:" + fileName;
346
    private InputStream getImageBuffer(String html) throws Exception {
347
		Java2DRenderer renderer = new Java2DRenderer(address, 400);
347
 
348
		RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
348
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
349
				RenderingHints.VALUE_COLOR_RENDER_QUALITY);
349
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
350
		hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
350
        String address = "file:" + fileName;
351
		hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
351
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
352
		hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
352
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
353
		renderer.setRenderingHints(hints);
353
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
354
		BufferedImage img = renderer.getImage();
354
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
355
		ByteArrayOutputStream os = new ByteArrayOutputStream();
355
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
356
		ImageIO.write(img, "png", os);
356
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
357
		return new ByteArrayInputStream(os.toByteArray());
357
        renderer.setRenderingHints(hints);
358
	}
358
        BufferedImage img = renderer.getImage();
359
 
359
        ByteArrayOutputStream os = new ByteArrayOutputStream();
360
	@Autowired
360
        ImageIO.write(img, "png", os);
361
	private VelocityEngine velocityEngine;
361
        return new ByteArrayInputStream(os.toByteArray());
362
 
362
    }
363
 
363
 
364
	private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
364
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
365
		View resolvedView = viewResolver.resolveViewName(template, Locale.US);
365
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
366
		MockHttpServletResponse mockResp = new MockHttpServletResponse();
366
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
367
		MockHttpServletRequest req = new MockHttpServletRequest();
367
        MockHttpServletRequest req = new MockHttpServletRequest();
368
		LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
368
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
369
		resolvedView.render(model, req, mockResp);
369
        resolvedView.render(model, req, mockResp);
370
		return mockResp.getContentAsString();
370
        return mockResp.getContentAsString();
371
	}
371
    }
372
 
372
 
373
	@RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
373
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
374
	public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
374
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
375
			throws ProfitMandiBusinessException {
375
            throws ProfitMandiBusinessException {
376
 
376
 
377
		List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
377
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
378
				.sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
378
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
379
		model.addAttribute("offers", publishedOffers);
379
        model.addAttribute("offers", publishedOffers);
380
		model.addAttribute("yearMonth", yearMonth);
380
        model.addAttribute("yearMonth", yearMonth);
381
		model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
381
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
382
 
382
 
383
		return "offer_history";
383
        return "offer_history";
384
	}
384
    }
385
 
385
 
386
	@RequestMapping(value = "/offer-details", method = RequestMethod.GET)
386
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
387
	public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
387
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
388
			throws ProfitMandiBusinessException {
388
            throws ProfitMandiBusinessException {
389
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
389
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
390
 
390
 
391
		model.addAttribute("offer", createOfferRequest);
391
        model.addAttribute("offer", createOfferRequest);
392
		return "offer-details";
392
        return "offer-details";
393
	}
393
    }
394
 
394
 
395
	@RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
395
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
396
	public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
396
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
397
			throws Exception {
397
            throws Exception {
398
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
398
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
399
		if (!createOfferRequest.isActive()) {
399
        if (!createOfferRequest.isActive()) {
400
			throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
400
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
401
		}
401
        }
402
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
402
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
403
			offerService.processSellin(createOfferRequest);
403
            offerService.processSellin(createOfferRequest);
404
		} else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
404
        } else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
405
			offerService.processActivationtOffer(createOfferRequest);
405
            offerService.processActivationtOffer(createOfferRequest);
406
		}
406
        }
407
		return responseSender.ok(true);
407
        return responseSender.ok(true);
408
	}
408
    }
409
 
409
 
410
	@RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
410
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
411
	public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
411
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
412
			throws Exception {
412
            throws Exception {
413
		List<List<?>> listOfRows = new ArrayList<>();
413
        List<List<?>> listOfRows = new ArrayList<>();
414
		final HttpHeaders headers = new HttpHeaders();
414
        final HttpHeaders headers = new HttpHeaders();
415
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
415
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
416
		headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
416
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
417
		CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
417
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
418
		Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);
418
        Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);
419
		ByteArrayOutputStream baos = null;
419
        ByteArrayOutputStream baos = null;
420
		if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
420
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
421
			for (OfferRowModel offerRowModel : offerRowModels) {
421
            for (OfferRowModel offerRowModel : offerRowModels) {
422
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
422
                CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
423
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
423
                listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
424
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
424
                        createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
425
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
425
                        createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
426
						"--", createOfferRequest.getItemCriteriaString(),
426
                        "--", createOfferRequest.getItemCriteriaString(),
427
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
427
                        createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
428
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
428
                        createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
429
						customRetailer.getCode(), offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getAchievedTarget(),
429
                        customRetailer.getCode(), offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getAchievedTarget(),
430
						offerRowModel.getPayoutPurchaseValue(), offerRowModel.getPayout(), offerRowModel.getPayoutType(), offerRowModel.getFinalPayout(), String.join(", ", offerRowModel.getEligibleImeis())));
430
                        offerRowModel.getPayoutPurchaseValue(), offerRowModel.getPayout(), offerRowModel.getPayoutType(), offerRowModel.getFinalPayout(), String.join(", ", offerRowModel.getEligibleImeis())));
431
			}
431
            }
432
			baos = FileUtil.getCSVByteStream(
432
            baos = FileUtil.getCSVByteStream(
433
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
433
                    Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
434
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
434
                            "Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
435
							"Base Purchase", "Achieved Target", "Eligible Purchase", "Slab Amount", "Slab Amount Type", "Payout Value(Rs.)",
435
                            "Base Purchase", "Achieved Target", "Eligible Purchase", "Slab Amount", "Slab Amount Type", "Payout Value(Rs.)",
436
							"Eligible IMEIs", "Billing Pending Imeis"
436
                            "Eligible IMEIs", "Billing Pending Imeis"
437
					), listOfRows);
437
                    ), listOfRows);
438
		} else {
438
        } else {
439
			for (OfferRowModel offerRowModel : offerRowModels) {
439
            for (OfferRowModel offerRowModel : offerRowModels) {
440
				CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
440
                CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
441
				listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
441
                listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
442
						createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
442
                        createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
443
						createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
443
                        createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
444
						createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
444
                        createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
445
						createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
445
                        createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
446
						createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
446
                        createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
447
						customRetailer.getCode(),
447
                        customRetailer.getCode(),
448
 
448
 
449
						offerRowModel.getTotalSale(),
449
                        offerRowModel.getTotalSale(),
450
						offerRowModel.getEligibleSale(),
450
                        offerRowModel.getEligibleSale(),
451
						offerRowModel.getPayoutTargetAchieved(),
451
                        offerRowModel.getPayoutTargetAchieved(),
452
						offerRowModel.getPayoutValue(),
452
                        offerRowModel.getPayoutValue(),
453
						offerRowModel.getPayoutType(),
453
                        offerRowModel.getPayoutType(),
454
						offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
454
                        offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
455
						String.join(", ", offerRowModel.getEligibleImeis()),
455
                        String.join(", ", offerRowModel.getEligibleImeis()),
456
						String.join(", ", offerRowModel.getBaseCriteria()))
456
                        String.join(", ", offerRowModel.getBaseCriteria()))
457
				);
457
                );
458
			}
458
            }
459
			baos = FileUtil.getCSVByteStream(
459
            baos = FileUtil.getCSVByteStream(
460
					Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
460
                    Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
461
							"Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
461
                            "Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
462
 
462
 
463
							"Total Value",
463
                            "Total Value",
464
							"Eligible Value",
464
                            "Eligible Value",
465
							"Payout Target Achieved", "Payout Amount", "Payout Amount Type",
465
                            "Payout Target Achieved", "Payout Amount", "Payout Amount Type",
466
							"Payout Value DP", "Amount to be credited", "Eligible Activated Imeis"
466
                            "Payout Value DP", "Amount to be credited", "Eligible Activated Imeis"
467
					), listOfRows);
467
                    ), listOfRows);
468
		}
468
        }
469
		final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
469
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
470
		final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
470
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
471
		return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
471
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
472
	}
472
    }
473
 
473
 
474
	@RequestMapping(value = "/offerById", method = RequestMethod.GET)
474
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
475
	public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
475
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
476
		Offer offer = offerRepository.selectById(offerId);
476
        Offer offer = offerRepository.selectById(offerId);
477
 
477
 
478
		model.addAttribute("offer", offer);
478
        model.addAttribute("offer", offer);
479
 
479
 
480
		return "offer-edit";
480
        return "offer-edit";
481
 
481
 
482
	}
482
    }
483
 
483
 
484
	@RequestMapping(value = "/published-offers/{yearMonth}", method = RequestMethod.GET)
484
    @RequestMapping(value = "/published-offers/{yearMonth}", method = RequestMethod.GET)
485
	public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
485
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
486
			throws ProfitMandiBusinessException {
486
            throws ProfitMandiBusinessException {
487
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
487
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
488
		int fofoId = loginDetails.getFofoId();
488
        int fofoId = loginDetails.getFofoId();
489
		List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
489
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
490
				YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
490
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
491
 
491
 
492
		model.addAttribute("publishedOffers", createOffers);
492
        model.addAttribute("publishedOffers", createOffers);
493
 
493
 
494
		return "published-offers";
494
        return "published-offers";
495
	}
495
    }
496
 
496
 
497
	@PostMapping(value = "/offers/upload")
497
    @PostMapping(value = "/offers/upload")
498
	public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
498
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
499
			throws Exception {
499
            throws Exception {
500
		offerService.createOffers(targetFile.getInputStream());
500
        offerService.createOffers(targetFile.getInputStream());
501
		model.addAttribute("response1", true);
501
        model.addAttribute("response1", true);
502
		return "response";
502
        return "response";
503
	}
503
    }
504
 
504
 
505
	@Autowired
505
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
506
	RoleManager roleManager;
506
    public String getOfferMargins(HttpServletRequest request,
507
 
507
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
508
	@RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
508
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
509
	public String getOfferMargins(HttpServletRequest request,
509
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
510
								  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
510
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
511
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
-
 
512
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
-
 
513
		CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
-
 
514
 
511
 
515
		model.addAttribute("offer", createOfferRequest);
512
        model.addAttribute("offer", createOfferRequest);
516
 
513
 
517
		return "offer_margin_detail_partner";
514
        return "offer_margin_detail_partner";
518
 
515
 
519
	}
516
    }
520
 
517
 
521
}
518
}
522
519