Subversion Repositories SmartDukaan

Rev

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