Subversion Repositories SmartDukaan

Rev

Rev 37208 | Rev 37216 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25380 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.google.gson.Gson;
30080 amit.gupta 4
import com.jcraft.jsch.*;
25380 amit.gupta 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.solr.SolrService;
35583 ranu 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
37208 amit 8
import com.spice.profitmandi.dao.entity.catalog.Catalog;
25380 amit.gupta 9
import com.spice.profitmandi.dao.entity.catalog.Item;
36404 amit 10
import com.spice.profitmandi.dao.entity.catalog.MonitorType;
35549 ranu 11
import com.spice.profitmandi.dao.entity.cs.Bulletin;
33443 ranu 12
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
13
import com.spice.profitmandi.dao.entity.cs.Region;
28264 tejbeer 14
import com.spice.profitmandi.dao.entity.dtr.DocumentUrl;
33443 ranu 15
import com.spice.profitmandi.dao.entity.fofo.PrintResource;
16
import com.spice.profitmandi.dao.entity.fofo.PrintResourceRegion;
17
import com.spice.profitmandi.dao.entity.user.User;
35487 ranu 18
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
33443 ranu 19
import com.spice.profitmandi.dao.model.*;
20
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
37184 ranu 21
import com.spice.profitmandi.dao.repository.catalog.*;
35549 ranu 22
import com.spice.profitmandi.dao.repository.cs.BulletinRepository;
33443 ranu 23
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
24
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
28264 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.DocumentUrlRepository;
25380 amit.gupta 26
import com.spice.profitmandi.dao.repository.dtr.Mongo;
33443 ranu 27
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRegionRepository;
28
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRepository;
29
import com.spice.profitmandi.dao.repository.user.UserRepository;
37214 amit 30
import com.spice.profitmandi.service.catalog.CategorySpecUtil;
32952 amit.gupta 31
import com.spice.profitmandi.service.catalog.ItemLoaderService;
25380 amit.gupta 32
import com.spice.profitmandi.web.model.EntityMediaPojo;
33443 ranu 33
import com.spice.profitmandi.web.model.LoginDetails;
34
import com.spice.profitmandi.web.util.CookiesProcessor;
25380 amit.gupta 35
import com.spice.profitmandi.web.util.MVCResponseSender;
30080 amit.gupta 36
import org.apache.commons.csv.CSVFormat;
37
import org.apache.commons.csv.CSVParser;
38
import org.apache.commons.csv.CSVRecord;
39
import org.apache.commons.lang3.StringUtils;
40
import org.apache.logging.log4j.LogManager;
41
import org.apache.logging.log4j.Logger;
31330 tejbeer 42
import org.json.JSONArray;
43
import org.json.JSONObject;
30080 amit.gupta 44
import org.springframework.beans.factory.annotation.Autowired;
35346 ranu 45
import org.springframework.http.ResponseEntity;
30080 amit.gupta 46
import org.springframework.stereotype.Controller;
35487 ranu 47
import org.springframework.transaction.annotation.Transactional;
30080 amit.gupta 48
import org.springframework.ui.Model;
49
import org.springframework.web.bind.annotation.*;
50
import org.springframework.web.multipart.MultipartFile;
25380 amit.gupta 51
 
30080 amit.gupta 52
import javax.servlet.http.HttpServletRequest;
53
import javax.xml.bind.DatatypeConverter;
54
import java.io.*;
55
import java.sql.Timestamp;
56
import java.time.LocalDate;
57
import java.time.LocalDateTime;
58
import java.time.ZoneOffset;
59
import java.util.*;
60
import java.util.stream.Collectors;
61
 
35458 amit 62
@Transactional(rollbackFor = Throwable.class)
25380 amit.gupta 63
@Controller
64
public class ContentController {
65
	@Autowired
66
	MVCResponseSender mvcResponseSender;
67
 
68
	@Autowired
69
	Mongo mongoClient;
70
 
71
	@Autowired
72
	SolrService solrService;
73
 
74
	@Autowired
75
	ItemRepository itemRepository;
76
 
28264 tejbeer 77
	@Autowired
78
	DocumentUrlRepository documentUrlRepository;
79
 
31330 tejbeer 80
	@Autowired
81
	FocusedModelRepository focusedModelRepository;
33443 ranu 82
 
83
	@Autowired
84
	PrintResourceRepository printResourceRepository;
85
	@Autowired
86
	AuthRepository authRepository;
87
	@Autowired
88
	RegionRepository regionRepository;
89
	@Autowired
90
	PrintResourceRegionRepository printResourceRegionRepository;
91
	@Autowired
92
	PartnerRegionRepository partnerRegionRepository;
33973 tejus.loha 93
	@Autowired
94
	SuperCatalogRepository superCatalogRepository;
35487 ranu 95
	@Autowired
96
	CatalogRepository catalogRepository;
35549 ranu 97
	@Autowired
36404 amit 98
	CatalogMonitorTypeRepository catalogMonitorTypeRepository;
99
	@Autowired
37214 amit 100
	CategorySpecDefinitionRepository categorySpecDefinitionRepository;
101
	@Autowired
35549 ranu 102
	BulletinRepository bulletinRepository;
25380 amit.gupta 103
	private Gson gson = new Gson();
104
 
105
	public static final int Entity_Id = 0;
106
	public static final int Title = 1;
107
	public static final int KeySpec1 = 2;
108
	public static final int KeySpec2 = 3;
109
	public static final int KeySpec3 = 4;
110
	public static final int KeySpec4 = 5;
111
	public static final int Warranty = 6;
112
	public static final int Package_Contents = 7;
37214 amit 113
	// new-layout template only: SpecValue1..5 at 8-12, detailed specs from 13.
114
	// Legacy templates (no SpecValue header at col 8) keep detailed specs at 8.
115
	public static final int SpecValue1 = 8;
116
	public static final int SPEC_VALUE_COUNT = 5;
117
	public static final int DetailedSpecsLegacyStart = 8;
118
	public static final int DetailedSpecsSpecLayoutStart = 13;
28264 tejbeer 119
	private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
120
	private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
25380 amit.gupta 121
 
29900 amit.gupta 122
	private static final String REMOTE_DIR = "/var/www/static.saholic.com/images/media/";
31330 tejbeer 123
	// private static final String REMOTE_DIR = "/tmp";
25986 amit.gupta 124
	private static final String STATIC_SERVER_URL = "https://static%d.smartdukaan.com/images/media/";
25380 amit.gupta 125
 
126
	private static final String THUMBNAIL = "thumbnail";
127
	private static final String ICON = "icon";
128
	private static final String DEFAULT = "default";
129
	private static final String NONE = "";
25409 amit.gupta 130
 
25400 amit.gupta 131
	private static final Logger LOGGER = LogManager.getLogger(ContentController.class);
25380 amit.gupta 132
 
133
	private String getFileName(int entityId, String description, String extension) {
134
		List<Item> items = itemRepository.selectAllByCatalogItemId(entityId);
25409 amit.gupta 135
		String imageString = getMediaPrefix(items.get(0).getItemDescriptionNoColor() + " " + description) + "-"
25380 amit.gupta 136
				+ LocalDateTime.now().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30));
25413 amit.gupta 137
		return imageString + "." + extension;
25380 amit.gupta 138
	}
139
 
35529 ranu 140
	@PostMapping(value = "/content/upload")
35525 ranu 141
	public String uploadContent(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
142
			throws Exception {
143
		List<ContentPojo> contentPojos = readFile(file);
35529 ranu 144
		if (contentPojos.size() < 1) {
145
			throw new RuntimeException("please check your file first ...may be content are wrong");
146
		}
35525 ranu 147
		for (ContentPojo contentPojo : contentPojos) {
148
			mongoClient.persistEntity(contentPojo);
149
		}
150
		//List<SuperCatalog> superCatalog = superCatalogRepository.selectAll();
151
 
152
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
153
		return "response";
25380 amit.gupta 154
	}
155
 
32952 amit.gupta 156
	@Autowired
157
	ItemLoaderService itemLoaderService;
158
	@PostMapping(value = "/catalog/upload")
159
	public String uploadCatalog(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
160
			throws Exception {
161
		itemLoaderService.parse(file);
162
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
163
		return "response";
164
	}
165
 
25380 amit.gupta 166
	@PostMapping(value = "/content/media/upload")
167
	public String uploadMediaContent(HttpServletRequest request, @RequestBody EntityMediaPojo entityMediaPojo,
168
			Model model) throws Exception {
169
		ContentPojo contentPojo = mongoClient.getEntityById(entityMediaPojo.getEntityId());
170
		Map<String, InputStream> fileStreamsMap = getStreamFileMap(contentPojo, entityMediaPojo);
25400 amit.gupta 171
		LOGGER.info("fileStreamsMap {}, " + fileStreamsMap.keySet());
29900 amit.gupta 172
		uploadContentFiles(fileStreamsMap, entityMediaPojo.getEntityId());
25380 amit.gupta 173
		mongoClient.persistEntity(contentPojo);
31238 amit.gupta 174
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
25380 amit.gupta 175
		return "response";
176
	}
177
 
35346 ranu 178
	@PostMapping(value = "/content/video/upload")
179
	public String uploadVideoUrls(HttpServletRequest request,
180
								  @RequestPart("file") MultipartFile file,
181
								  Model model) throws Exception {
182
 
183
		List<VideoUrlPojo> videoRows = readVideoFile(file);
184
 
185
		LOGGER.info("Received {} video rows", videoRows.size());
186
 
187
		// group by catalogId
188
		Map<Integer, List<VideoUrlPojo>> videoCatalogMap =
189
				videoRows.stream().collect(Collectors.groupingBy(VideoUrlPojo::getCatalogId));
190
 
35348 ranu 191
		LOGGER.info("videoCatalogMap {}", videoCatalogMap);
192
 
35346 ranu 193
		for (Map.Entry<Integer, List<VideoUrlPojo>> entry : videoCatalogMap.entrySet()) {
194
 
195
			int catalogId = entry.getKey();
35348 ranu 196
 
197
			LOGGER.info("catalogId {}", catalogId);
198
 
35346 ranu 199
			List<VideoUrlPojo> rowsForCatalog = entry.getValue();
200
 
201
			ContentPojo content = mongoClient.getEntityById(catalogId);
202
 
203
			if (content == null) {
204
				LOGGER.warn("No content found for catalogId {}", catalogId);
205
				continue;
206
			}
207
 
208
			updateVideoUrls(content, rowsForCatalog);
209
 
210
			mongoClient.persistEntity(content);
211
 
212
			LOGGER.info("Updated video URLs for catalogId {}", catalogId);
213
		}
214
 
215
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
216
		return "response";
217
	}
218
 
219
 
220
	private void updateVideoUrls(ContentPojo content, List<VideoUrlPojo> rows) {
221
 
222
		if (content.getVideoUrls() == null) {
223
			content.setVideoUrls(new ArrayList<>());
224
		}
225
 
226
		List<VideoUrlsContentPojo> existing = content.getVideoUrls();
227
 
228
		for (VideoUrlPojo row : rows) {
229
			VideoUrlsContentPojo newUrl = new VideoUrlsContentPojo(row.getUrl());
230
 
231
			// add only if not duplicate
232
			if (!existing.contains(newUrl)) {
233
				existing.add(newUrl);
234
			}
235
		}
236
 
237
		content.setVideoUrls(existing);
238
 
239
		LOGGER.info("Final video list = {}", existing);
240
	}
241
 
242
 
243
 
244
 
28264 tejbeer 245
	@PostMapping(value = "/image/media/upload")
246
	public String uploadImageMediaContent(HttpServletRequest request, @RequestBody MediaPojo mediaPojo, Model model)
247
			throws Exception {
248
 
249
		LOGGER.info("mediaPojo" + mediaPojo);
250
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
251
		String extension;
252
		String base64String = mediaPojo.getImageData();
253
		String[] strings = base64String.split(",");
254
		switch (strings[0]) {// check image's extension
255
		case "data:image/jpeg;base64":
256
			extension = "jpeg";
257
			break;
258
		case "data:image/png;base64":
259
			extension = "png";
260
			break;
32304 amit.gupta 261
			case "data:image/webp;base64":
32305 amit.gupta 262
				extension = "webp";
32304 amit.gupta 263
				break;
28264 tejbeer 264
		default:// should write cases for more images types
32304 amit.gupta 265
			extension = "jpg";
28264 tejbeer 266
			break;
267
		}
268
		LOGGER.info("After switch statement = {}", extension);
269
		// convert base64 string to binary data
270
		byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
271
		Timestamp tm = new Timestamp(System.currentTimeMillis());
28320 tejbeer 272
		String urlTitle = mediaPojo.getTitle().toLowerCase();
273
		String fileName = urlTitle.replace(' ', '-') + tm.getTime() + "." + extension;
28264 tejbeer 274
		LOGGER.info("After switch statement Filename = {}", fileName);
275
		mediaPojo.setImageData(null);
276
		mediaPojo.setUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
277
		fileStreamsMap.put(fileName, new ByteArrayInputStream(data));
278
		LOGGER.info("fileStreamsMap" + fileStreamsMap);
279
 
280
		uploadFile(fileStreamsMap);
281
 
282
		DocumentUrl du = new DocumentUrl();
283
		du.setTitle(mediaPojo.getTitle());
284
		du.setUrl(mediaPojo.getUrl());
285
		du.setCreatedTimestamp(LocalDateTime.now());
286
		documentUrlRepository.persist(du);
287
 
288
		model.addAttribute("documents", du);
289
		return "image-url";
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 + "/" + "image" + LocalDate.now() + " 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
	}
320
 
321
	@GetMapping(value = "/search/image/media")
322
	public String getImage(HttpServletRequest request, Model model, @RequestParam String title) throws Exception {
323
		List<DocumentUrl> documents = documentUrlRepository.selectBySearch(title);
324
 
325
		model.addAttribute("documents", documents);
326
		return "image-url";
327
 
328
	}
329
 
25380 amit.gupta 330
	@GetMapping(value = "/content/media")
331
	public String getMediaContent(HttpServletRequest request, Model model, @RequestParam int entityId)
332
			throws Exception {
333
		ContentPojo contentPojo = mongoClient.getEntityById(entityId);
25409 amit.gupta 334
		if (contentPojo == null) {
25380 amit.gupta 335
			throw new Exception("Please add content first");
336
		}
337
		EntityMediaPojo empojo = getEntityMediaPojo(contentPojo);
31238 amit.gupta 338
		model.addAttribute("response1", mvcResponseSender.createResponseString(empojo));
25380 amit.gupta 339
		return "response";
340
	}
28264 tejbeer 341
 
27185 amit.gupta 342
	@GetMapping(value = "/catalog-item")
28264 tejbeer 343
	public String catalogItem(HttpServletRequest request, Model model) throws Exception {
27185 amit.gupta 344
		return "catalog-item";
345
	}
25380 amit.gupta 346
 
347
	private EntityMediaPojo getEntityMediaPojo(ContentPojo contentPojo) {
348
		EntityMediaPojo ep = new EntityMediaPojo();
349
		int defaultIndex = 0;
25409 amit.gupta 350
		if (contentPojo.getImages() == null) {
25380 amit.gupta 351
			ep.setMediaPojos(new ArrayList<>());
352
		} else {
353
			ep.setMediaPojos(contentPojo.getImages());
354
			for (MediaPojo mediaPojo : contentPojo.getImages()) {
25409 amit.gupta 355
				if (mediaPojo.getUrl() == null)
356
					continue;
357
 
25380 amit.gupta 358
				if (!mediaPojo.getUrl().equals(contentPojo.getDefaultImageUrl())) {
359
					defaultIndex++;
360
				}
361
			}
362
		}
363
		ep.setDefaultImageIndex(defaultIndex);
364
		return ep;
365
	}
366
 
37184 ranu 367
	/**
368
	 * Band-aid for URL '+' decode issue: when the front-end sends `brand=Ai+` the servlet
369
	 * decodes the plus as a space and we receive "Ai " with a trailing space, missing the
370
	 * real "Ai+" brand. Restore trailing whitespace back to "+" so lookups match.
371
	 * Front-end should URL-encode with %2B (encodeURIComponent) — this is a temporary
372
	 * safety net until the mobile team ships that fix.
373
	 */
374
	private List<String> normalizeBrandNames(List<String> brands) {
375
		if (brands == null || brands.isEmpty()) return brands;
376
		return brands.stream()
377
				.map(b -> (b != null && b.endsWith(" ")) ? b.replaceAll("\\s+$", "") + "+" : b)
378
				.collect(Collectors.toList());
379
	}
380
 
25380 amit.gupta 381
	@GetMapping(value = "/entity")
28264 tejbeer 382
	public String searchEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
31330 tejbeer 383
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
384
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
385
			Model model) throws Exception {
37184 ranu 386
		brands = normalizeBrandNames(brands);
31330 tejbeer 387
		model.addAttribute("response1", solrService.getContent(query, categoryId > 0 ? Arrays.asList(categoryId) : null,
31711 amit.gupta 388
				brands, limit, false));
25380 amit.gupta 389
		return "response";
390
	}
391
 
31330 tejbeer 392
	@GetMapping(value = "/focusedEntity")
393
	public String focusedEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
394
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
395
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
396
			Model model) throws Exception {
397
 
37184 ranu 398
		brands = normalizeBrandNames(brands);
31330 tejbeer 399
		List<Integer> catalogIds = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
400
				.collect(Collectors.toList());
401
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
402
				limit, activeOnly);
403
 
404
		Iterator<Object> jsonIterator = docA.iterator();
405
		while (jsonIterator.hasNext()) {
406
			JSONObject i = (JSONObject) jsonIterator.next();
407
 
408
			if (!catalogIds.contains(i.get("catalogId_i"))) {
409
				jsonIterator.remove();
410
			}
411
 
412
		}
413
 
414
		model.addAttribute("response1", docA.toString());
415
 
416
		return "response";
417
	}
418
 
35487 ranu 419
	@GetMapping(value = "/statusWiseCatalogs")
420
	public String statusWiseCatalogs(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
421
									 @RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
422
									 @RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
423
									 Model model) throws Exception {
424
 
37184 ranu 425
		brands = normalizeBrandNames(brands);
35487 ranu 426
		List<CatalogMovingEnum> catalogMovingEnums = Arrays.asList(CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING);
427
 
428
		List<Integer> catalogIds = catalogRepository.selectAllStatusAndBrandWise(brands, catalogMovingEnums);
429
 
430
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
431
				limit, activeOnly);
432
 
36404 amit 433
		Map<Integer, MonitorType> monitorTypeByCatalogId = catalogMonitorTypeRepository.selectAllAsMap();
434
 
35487 ranu 435
		Iterator<Object> jsonIterator = docA.iterator();
436
		while (jsonIterator.hasNext()) {
437
			JSONObject i = (JSONObject) jsonIterator.next();
438
 
36404 amit 439
			Object cidObj = i.get("catalogId_i");
440
			if (!catalogIds.contains(cidObj)) {
35487 ranu 441
				jsonIterator.remove();
36404 amit 442
				continue;
35487 ranu 443
			}
444
 
36404 amit 445
			if (cidObj instanceof Number) {
446
				MonitorType mt = monitorTypeByCatalogId.get(((Number) cidObj).intValue());
447
				if (mt != null) i.put("monitor_type", mt.dbValue());
448
			}
35487 ranu 449
		}
450
 
451
		model.addAttribute("response1", docA.toString());
452
 
453
		return "response";
454
	}
455
 
25380 amit.gupta 456
	@GetMapping(value = "/content/index")
457
	public String index(HttpServletRequest request, Model model) throws Exception {
33973 tejus.loha 458
 
25380 amit.gupta 459
		return "content";
460
	}
461
 
462
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
463
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
464
		List<CSVRecord> records = parser.getRecords();
465
		if (records.size() < 2) {
466
			parser.close();
467
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
468
		}
37214 amit 469
		// header decides the layout: SpecValue columns present at 8-12 or not
470
		CSVRecord header = records.get(0);
471
		boolean specLayout = header.size() > SpecValue1 && header.get(SpecValue1) != null
472
				&& header.get(SpecValue1).trim().toUpperCase().startsWith("SPECVALUE");
25380 amit.gupta 473
		// Remove header
474
		records.remove(0);
475
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
476
		for (CSVRecord record : records) {
25430 amit.gupta 477
			ContentPojo cp = null;
478
			Long entityId = Long.parseLong(record.get(Entity_Id));
25380 amit.gupta 479
			try {
25430 amit.gupta 480
				cp = mongoClient.getEntityById(entityId);
481
			} catch (Exception e) {
482
			}
483
			try {
484
				if (cp == null) {
485
					cp = new ContentPojo(entityId);
486
				}
25380 amit.gupta 487
				cp.setWarranty(record.get(Warranty));
488
				cp.setKeySpecs(Arrays
489
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
25429 amit.gupta 490
						.stream().filter(x -> x != null && !x.equals("")).collect(Collectors.toList()));
25380 amit.gupta 491
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
37214 amit 492
				cp.setDetailedSpecs(getDetailedSpecs(record,
493
						specLayout ? DetailedSpecsSpecLayoutStart : DetailedSpecsLegacyStart));
37208 amit 494
				if (cp.getCategoryId() == null) {
495
					Catalog catalog = catalogRepository.selectCatalogById(Math.toIntExact(entityId));
496
					if (catalog != null) {
497
						cp.setCategoryId(catalog.getCategoryId());
498
					}
499
				}
37214 amit 500
				if (specLayout) {
501
					List<String> specValues = new ArrayList<>();
502
					for (int col = SpecValue1; col < SpecValue1 + SPEC_VALUE_COUNT; col++) {
503
						specValues.add(record.size() > col ? record.get(col) : "");
504
					}
505
					boolean anyValue = specValues.stream().anyMatch(v -> v != null && !v.trim().isEmpty());
506
					if (anyValue) {
507
						if (cp.getCategoryId() == null) {
508
							throw new ProfitMandiBusinessException("CatalogId", String.valueOf(entityId),
509
									"Spec values supplied but catalog/category unknown");
510
						}
511
						cp.setCategorySpecs(CategorySpecUtil.pairValues(
512
								categorySpecDefinitionRepository.selectActiveByCategoryId(cp.getCategoryId()),
513
								specValues));
514
					}
515
					// all-blank spec columns: leave existing categorySpecs untouched
516
				}
25380 amit.gupta 517
				returnList.add(cp);
37214 amit 518
			} catch (ProfitMandiBusinessException e) {
519
				parser.close();
520
				throw new ProfitMandiBusinessException(e.getRejectedType(), e.getRejectedValue(),
521
						e.getCode() + " at row " + record.getRecordNumber());
25380 amit.gupta 522
			} catch (Exception e) {
523
				continue;
524
			}
525
		}
526
		parser.close();
527
		return returnList;
528
	}
529
 
35346 ranu 530
 
531
	private List<VideoUrlPojo> readVideoFile(MultipartFile file) throws Exception {
532
 
533
		CSVParser parser = new CSVParser(
534
				new InputStreamReader(file.getInputStream()),
535
				CSVFormat.DEFAULT
536
		);
537
 
538
		List<CSVRecord> records = parser.getRecords();
539
 
540
		if (records.size() < 2) {
541
			parser.close();
542
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records found");
543
		}
544
 
545
		// Remove header
546
		records.remove(0);
547
 
548
		List<VideoUrlPojo> returnList = new ArrayList<>();
549
 
550
		for (CSVRecord record : records) {
551
 
552
			try {
553
				// Must match CSV column order
35348 ranu 554
				Long catalogId = Long.parseLong(record.get(1));
555
				String url = record.get(2);
35346 ranu 556
 
557
				VideoUrlPojo row = new VideoUrlPojo();
558
				row.setCatalogId(Math.toIntExact(catalogId));
559
				row.setUrl(url);
560
 
561
				returnList.add(row);
562
 
563
			} catch (Exception e) {
564
				// skip bad rows, same as your style
565
				continue;
566
			}
567
		}
568
 
569
		parser.close();
570
		return returnList;
571
	}
572
 
573
 
37214 amit 574
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record, int startIndex) throws Exception {
25380 amit.gupta 575
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
37214 amit 576
		int currentIndex = startIndex;
25380 amit.gupta 577
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
578
			int start = currentIndex;
579
			List<Specification> specifications = new ArrayList<>();
580
			int begin = 0;
581
			while (begin < 5) {
582
				int specKeyIndex = (begin * 2) + 1;
583
				int specValueIndex = (begin * 2) + 2;
584
 
585
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
586
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
587
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
588
							Arrays.asList(record.get(currentIndex + specValueIndex)));
589
					specifications.add(specification);
590
				}
591
				begin++;
592
			}
593
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
594
			specificationGroups.add(specificationGroup);
25392 amit.gupta 595
			currentIndex += 11;
25380 amit.gupta 596
		}
597
 
598
		return specificationGroups;
599
	}
600
 
601
	private ChannelSftp setupJsch() throws JSchException {
602
		JSch jsch = new JSch();
33463 amit.gupta 603
		Session jschSession = jsch.getSession("root", "172.105.58.16");
31330 tejbeer 604
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
605
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
606
				getClass().getClassLoader().getResource("id_rsa").getPath());
29881 amit.gupta 607
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
31330 tejbeer 608
		// jschSession.setPassword("spic@2015static0");
25396 amit.gupta 609
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 610
		jschSession.connect();
611
		return (ChannelSftp) jschSession.openChannel("sftp");
612
	}
613
 
29900 amit.gupta 614
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
25380 amit.gupta 615
		ChannelSftp channelSftp = setupJsch();
616
		channelSftp.connect();
29900 amit.gupta 617
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
618
		channelSftp.exit();
619
	}
620
 
621
	private void uploadContentFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
622
		ChannelSftp channelSftp = setupJsch();
623
		channelSftp.connect();
25380 amit.gupta 624
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
625
		channelSftp.exit();
626
	}
627
 
628
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
629
			throws SftpException, FileNotFoundException {
630
 
631
		File sourceFile = new File(sourcePath);
632
		if (sourceFile.isFile()) {
633
 
634
			// copy if it is a file
635
			channelSftp.cd(destinationPath);
636
			if (!sourceFile.getName().startsWith("."))
637
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
638
 
639
		} else {
640
 
641
			System.out.println("inside else " + sourceFile.getName());
642
			File[] files = sourceFile.listFiles();
643
 
644
			if (files != null && !sourceFile.getName().startsWith(".")) {
645
 
646
				channelSftp.cd(destinationPath);
647
				SftpATTRS attrs = null;
648
 
649
				// check if the directory is already existing
650
				try {
651
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
652
				} catch (Exception e) {
653
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
654
				}
655
 
656
				// else create a directory
657
				if (attrs != null) {
658
					System.out.println("Directory exists IsDir=" + attrs.isDir());
659
				} else {
660
					System.out.println("Creating dir " + sourceFile.getName());
661
					channelSftp.mkdir(sourceFile.getName());
662
				}
663
 
664
				for (File f : files) {
665
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
666
							destinationPath + "/" + sourceFile.getName());
667
				}
668
 
669
			}
670
		}
671
 
672
	}
673
 
674
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
675
			String folderName) throws SftpException, FileNotFoundException {
676
 
677
		channelSftp.cd(destinationPath);
678
		SftpATTRS attrs = null;
679
 
680
		// check if the directory is already existing
681
		try {
682
			attrs = channelSftp.stat(folderName);
683
		} catch (Exception e) {
684
			System.out.println(destinationPath + "/" + folderName + " not found");
685
		}
686
 
687
		// else create a directory
25413 amit.gupta 688
		if (attrs == null) {
689
			channelSftp.mkdir(folderName);
690
			channelSftp.chmod(0755, ".");
25380 amit.gupta 691
		}
692
		channelSftp.cd(folderName);
25413 amit.gupta 693
		channelSftp.rm("*");
25380 amit.gupta 694
 
695
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
696
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
697
		}
698
 
699
	}
700
 
701
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
702
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 703
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25404 amit.gupta 704
		for (int i = 0; i < entityMediaPojo.getMediaPojos().size(); i++) {
25380 amit.gupta 705
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
706
			String extension;
707
			String base64String = mediaPojo.getImageData();
708
			String[] strings = base64String.split(",");
709
			switch (strings[0]) {// check image's extension
710
			case "data:image/jpeg;base64":
711
				extension = "jpeg";
712
				break;
713
			case "data:image/png;base64":
714
				extension = "png";
715
				break;
716
			default:// should write cases for more images types
717
				extension = "jpg";
718
				break;
719
			}
25402 amit.gupta 720
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 721
			// convert base64 string to binary data
722
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
723
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 724
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 725
			mediaPojo.setImageData(null);
25430 amit.gupta 726
			String staticServerUrl = String.format(STATIC_SERVER_URL, entityMediaPojo.getEntityId() % 3);
25414 amit.gupta 727
			mediaPojo.setUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 728
			map.put(fileName, new ByteArrayInputStream(data));
729
			if (i == entityMediaPojo.getDefaultImageIndex()) {
730
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
731
				map.put(defaultFileName, new ByteArrayInputStream(data));
25414 amit.gupta 732
				contentPojo.setDefaultImageUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + defaultFileName);
25380 amit.gupta 733
			}
734
		}
735
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
736
 
737
		return map;
738
	}
739
 
25409 amit.gupta 740
	private String getMediaPrefix(String productName) {
741
		String mediaPrefix = productName.toLowerCase().replace(' ', '-');
742
		mediaPrefix = mediaPrefix.replaceAll("/", "-");
743
		mediaPrefix = mediaPrefix.replaceAll("-+", "-");
744
		return mediaPrefix;
745
	}
746
 
28264 tejbeer 747
	@GetMapping(value = "/urlGeneration")
748
	public String urlGeneration(HttpServletRequest request, Model model) throws Exception {
749
		return "url-generation";
750
	}
33443 ranu 751
	@Autowired
752
	UserRepository userRepository;
753
	@Autowired
754
	private CookiesProcessor cookiesProcessor;
755
 
756
	@GetMapping(value = "/printResources")
757
	public String printResources(HttpServletRequest request, Model model) throws Exception {
758
		List<Region> regionList = regionRepository.selectAll();
759
		model.addAttribute("regionList", regionList);
760
		return "print-resource";
761
	}
762
 
763
	@RequestMapping(value = "/postPrintResource", method = RequestMethod.POST)
764
	public String postPrintResource(HttpServletRequest request, @RequestBody PrintResourceModel printResourceModel,
765
									Model model) throws Exception {
766
		LOGGER.info("printResourceModel {}", printResourceModel);
767
		PrintResource printResource = new PrintResource();
768
		printResource.setTitle(printResourceModel.getTitle());
769
		printResource.setStartDate(printResourceModel.getStartDate().atStartOfDay());
770
		if (printResourceModel.getEndDate() != null) {
771
			printResource.setEndDate(printResourceModel.getEndDate().atStartOfDay());
772
		} else {
773
			printResource.setEndDate(null);
774
		}
775
 
776
		printResource.setCreateTimestamp(LocalDateTime.now());
777
		printResource.setImgUrl(printResourceModel.getImgUrl());
33501 ranu 778
		printResource.setThumbnailUrl(printResourceModel.getThumbnailUrl());
33443 ranu 779
		printResourceRepository.persist(printResource);
780
 
781
		PrintResourceRegion printResourceRegion = new PrintResourceRegion();
782
		int regionId = Integer.parseInt(printResourceModel.getRegion());
783
		printResourceRegion.setRegionId(regionId);
784
		printResourceRegion.setResourceId(printResource.getId());
785
		printResourceRegionRepository.persist(printResourceRegion);
786
 
787
 
788
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
789
 
790
		return "response";
791
	}
792
 
793
	@RequestMapping(value = "/changeEndDate", method = RequestMethod.POST)
794
	public String changeEndDate(HttpServletRequest request, @RequestParam LocalDate date, @RequestParam int resourceId,
795
								Model model) throws Exception {
796
 
797
		PrintResource printResource = printResourceRepository.selectById(resourceId);
798
		printResource.setEndDate(date.atStartOfDay());
799
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
800
		return "response";
801
	}
802
 
803
	@GetMapping(value = "/partnerPrintResources")
804
	public String partnerPrintResources(HttpServletRequest request, Model model) throws Exception {
805
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
806
		int fofoId = loginDetails.getFofoId();
807
		User user = userRepository.selectById(fofoId);
808
		List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(user.getId());
809
		LocalDateTime currentDate = LocalDateTime.now();
810
		List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
811
		LOGGER.info("printresourcesList {}", printResources);
812
		model.addAttribute("printResources", printResources);
813
		return "partner_print_resource";
814
	}
815
 
816
	@GetMapping(value = "/allPrintResources")
817
	public String allPrintResources(HttpServletRequest request, Model model) throws Exception {
818
		LocalDateTime currentDate = LocalDateTime.now();
819
		List<PrintResource> printResources = printResourceRepository.selectAllPrintResources(currentDate);
820
		model.addAttribute("printResources", printResources);
821
		return "all-print-resource";
822
	}
823
 
35346 ranu 824
	@GetMapping("/content/video/check/{catalogId}")
825
	public ResponseEntity<?> checkVideo(@PathVariable int catalogId) throws Exception {
826
		ContentPojo cp = mongoClient.getEntityById(catalogId);
827
 
828
		LOGGER.info("Video Url {}", cp.getVideoUrls());
829
		return ResponseEntity.ok(cp.getVideoUrls());
830
	}
831
 
832
 
35549 ranu 833
	@GetMapping(value = "/bulletin")
834
	public String bulletin(HttpServletRequest request, Model model) throws Exception {
835
		List<Region> regionList = regionRepository.selectAll();
836
		model.addAttribute("regionList", regionList);
837
		return "post-bulletin";
838
	}
839
 
840
 
841
	@RequestMapping(value = "/bulletinPost", method = RequestMethod.POST)
842
	public String bulletinPost(HttpServletRequest request, @RequestBody BulletinPostModel bulletinPostModel,
843
							   Model model) throws Exception {
35583 ranu 844
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
845
		String email = loginDetails.getEmailId();
846
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35549 ranu 847
		LOGGER.info("bulletinPostModel {}", bulletinPostModel);
848
		Bulletin bulletin = new Bulletin();
849
		bulletin.setRegionId(bulletinPostModel.getRegionId());
850
		bulletin.setDescription(bulletinPostModel.getDescription());
851
		bulletin.setDocumentIds(bulletinPostModel.getDocumentIds());
852
		bulletin.setCreatedAt(LocalDateTime.now());
35583 ranu 853
		bulletin.setCreatedBy(authUser.getFullName());
35549 ranu 854
		bulletinRepository.persist(bulletin);
855
 
856
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
857
 
858
		return "response";
859
	}
860
 
861
 
862
 
863
 
25380 amit.gupta 864
}