Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21339 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.eclipsesource.json.Json;
4
import com.eclipsesource.json.JsonArray;
5
import com.eclipsesource.json.JsonObject;
6
import com.eclipsesource.json.JsonValue;
7
import com.google.gson.Gson;
21356 kshitij.so 8
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 9
import com.mongodb.BasicDBObject;
24163 amit.gupta 10
import com.mongodb.DBObject;
21643 ashik.ali 11
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 12
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
13
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 14
import com.spice.profitmandi.common.model.UserInfo;
27030 amit.gupta 15
import com.spice.profitmandi.common.solr.SolrService;
21643 ashik.ali 16
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 17
import com.spice.profitmandi.common.web.util.ResponseSender;
30686 amit.gupta 18
import com.spice.profitmandi.dao.entity.catalog.*;
31507 tejbeer 19
import com.spice.profitmandi.dao.entity.dtr.WebListing;
30595 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
31612 tejbeer 21
import com.spice.profitmandi.dao.entity.dtr.WebProductListing;
31625 tejbeer 22
import com.spice.profitmandi.dao.entity.fofo.CatalogFavourite;
27090 amit.gupta 23
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
26847 tejbeer 24
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
26846 tejbeer 25
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
30669 amit.gupta 26
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
27032 amit.gupta 27
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
31572 tejbeer 28
import com.spice.profitmandi.dao.enumuration.dtr.WebListingSource;
31507 tejbeer 29
import com.spice.profitmandi.dao.enumuration.dtr.WebListingType;
30188 amit.gupta 30
import com.spice.profitmandi.dao.model.CreateOfferRequest;
22361 amit.gupta 31
import com.spice.profitmandi.dao.model.UserCart;
30686 amit.gupta 32
import com.spice.profitmandi.dao.repository.catalog.*;
27030 amit.gupta 33
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22333 amit.gupta 34
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22361 amit.gupta 35
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
31547 tejbeer 36
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
30595 tejbeer 37
import com.spice.profitmandi.dao.repository.dtr.WebOfferRepository;
31547 tejbeer 38
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
31625 tejbeer 39
import com.spice.profitmandi.dao.repository.fofo.CatalogFavouriteRepository;
26846 tejbeer 40
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
26847 tejbeer 41
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
30669 amit.gupta 42
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
23798 amit.gupta 43
import com.spice.profitmandi.service.authentication.RoleManager;
31507 tejbeer 44
import com.spice.profitmandi.service.catalog.BrandsService;
30686 amit.gupta 45
import com.spice.profitmandi.service.inventory.*;
30123 amit.gupta 46
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModel;
47
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
48
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
22287 amit.gupta 49
import com.spice.profitmandi.service.pricing.PricingService;
26695 amit.gupta 50
import com.spice.profitmandi.service.scheme.SchemeService;
21356 kshitij.so 51
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 52
import com.spice.profitmandi.web.res.DealObjectResponse;
53
import com.spice.profitmandi.web.res.DealsResponse;
54
import io.swagger.annotations.ApiImplicitParam;
55
import io.swagger.annotations.ApiImplicitParams;
56
import io.swagger.annotations.ApiOperation;
30686 amit.gupta 57
import org.apache.commons.lang3.StringUtils;
58
import org.apache.http.conn.HttpHostConnectException;
59
import org.apache.logging.log4j.LogManager;
60
import org.apache.logging.log4j.Logger;
61
import org.json.JSONArray;
62
import org.json.JSONObject;
63
import org.springframework.beans.factory.annotation.Autowired;
64
import org.springframework.beans.factory.annotation.Value;
65
import org.springframework.http.HttpStatus;
66
import org.springframework.http.MediaType;
67
import org.springframework.http.ResponseEntity;
68
import org.springframework.stereotype.Controller;
69
import org.springframework.transaction.annotation.Transactional;
70
import org.springframework.web.bind.annotation.PathVariable;
71
import org.springframework.web.bind.annotation.RequestMapping;
72
import org.springframework.web.bind.annotation.RequestMethod;
73
import org.springframework.web.bind.annotation.RequestParam;
21339 kshitij.so 74
 
30686 amit.gupta 75
import javax.servlet.http.HttpServletRequest;
31625 tejbeer 76
 
77
import java.time.LocalDateTime;
30686 amit.gupta 78
import java.util.*;
79
import java.util.concurrent.atomic.AtomicInteger;
80
import java.util.stream.Collectors;
81
 
21339 kshitij.so 82
@Controller
22319 amit.gupta 83
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 84
public class DealsController {
85
 
23568 govind 86
	private static final Logger logger = LogManager.getLogger(DealsController.class);
31547 tejbeer 87
	private static final List<Integer> TAG_IDS = Arrays.asList(4);
21339 kshitij.so 88
 
89
	@Value("${python.api.host}")
90
	private String host;
23816 amit.gupta 91
 
26889 amit.gupta 92
	@Value("${new.solr.url}")
93
	private String solrUrl;
94
 
21339 kshitij.so 95
	@Value("${python.api.port}")
96
	private int port;
23816 amit.gupta 97
 
26889 amit.gupta 98
	@Autowired
99
	RestClient restClient;
27051 amit.gupta 100
 
27030 amit.gupta 101
	@Autowired
102
	SolrService solrService;
26889 amit.gupta 103
 
26924 amit.gupta 104
	@Autowired
105
	InventoryService inventoryService;
106
 
23816 amit.gupta 107
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 108
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 109
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 110
 
111
	@Autowired
112
	private PricingService pricingService;
23816 amit.gupta 113
 
22273 amit.gupta 114
	@Autowired
25010 amit.gupta 115
	private CategoryRepository categoryRepository;
116
 
117
	@Autowired
26695 amit.gupta 118
	private SchemeService schemeService;
119
 
120
	@Autowired
26889 amit.gupta 121
	private SaholicInventoryService saholicInventoryService;
122
 
123
	@Autowired
22333 amit.gupta 124
	private Mongo mongoClient;
25879 amit.gupta 125
 
25875 amit.gupta 126
	@Autowired
127
	private ItemBucketService itemBucketService;
23816 amit.gupta 128
 
22333 amit.gupta 129
	@Autowired
22361 amit.gupta 130
	private UserAccountRepository userAccountRepository;
27051 amit.gupta 131
 
27030 amit.gupta 132
	@Autowired
133
	private FofoStoreRepository fofoStoreRepository;
23816 amit.gupta 134
 
22989 amit.gupta 135
	@Autowired
22931 ashik.ali 136
	private ResponseSender<?> responseSender;
23816 amit.gupta 137
 
22554 amit.gupta 138
	@Autowired
23814 amit.gupta 139
	private TagListingRepository tagListingRepository;
23816 amit.gupta 140
 
23814 amit.gupta 141
	@Autowired
23426 amit.gupta 142
	private ItemRepository itemRepository;
30123 amit.gupta 143
	@Autowired
144
	private PriceCircularService priceCircularService;
23816 amit.gupta 145
 
23786 amit.gupta 146
	@Autowired
23798 amit.gupta 147
	private RoleManager roleManagerService;
23816 amit.gupta 148
 
26846 tejbeer 149
	@Autowired
150
	private SuggestedPoDetailRepository monthlyPoDetailRepository;
151
 
26847 tejbeer 152
	@Autowired
153
	private SuggestedPoRepository suggestedPoRepository;
154
 
30595 tejbeer 155
	@Autowired
156
	private WebOfferRepository webOfferRepository;
157
 
30683 tejbeer 158
	@Autowired
159
	private ComboModelRepository comboModelRepository;
160
 
161
	@Autowired
162
	private ComboMappedModelRepository comboMappedModelRepository;
163
 
31507 tejbeer 164
	@Autowired
165
	private BrandsService brandsService;
31547 tejbeer 166
 
167
	@Autowired
168
	private WebListingRepository webListingRepository;
169
 
170
	@Autowired
171
	private WebProductListingRepository webProductListingRepository;
172
 
31625 tejbeer 173
	@Autowired
174
	private CatalogFavouriteRepository catalogFavouriteRepository;
175
 
22336 amit.gupta 176
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 177
 
25876 amit.gupta 178
	@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25879 amit.gupta 179
	public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
25875 amit.gupta 180
		logger.info("Request " + request.getParameterMap());
181
		return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
182
	}
25879 amit.gupta 183
 
184
	@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25880 amit.gupta 185
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 186
			throws ProfitMandiBusinessException {
25880 amit.gupta 187
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25968 amit.gupta 188
		Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream()
189
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
190
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
191
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
25879 amit.gupta 192
		RestClient rc = new RestClient();
193
		Map<String, String> params = new HashMap<>();
194
		List<String> mandatoryQ = new ArrayList<>();
25968 amit.gupta 195
		mandatoryQ.add(
196
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
25959 amit.gupta 197
		params.put("start", "0");
198
		params.put("rows", "100");
25879 amit.gupta 199
		params.put("q", StringUtils.join(mandatoryQ, " "));
200
		params.put("fl", "*, [child parentFilter=id:catalog*]");
201
 
202
		params.put("wt", "json");
203
		String response = null;
204
		try {
26889 amit.gupta 205
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
25879 amit.gupta 206
		} catch (HttpHostConnectException e) {
207
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
208
		}
209
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
210
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25968 amit.gupta 211
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26051 amit.gupta 212
 
26589 amit.gupta 213
		Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id)
214
				.collect(Collectors.toList()).get(0);
25882 amit.gupta 215
		bucket.setFofoCatalogResponses(dealResponse);
216
		return responseSender.ok(bucket);
25879 amit.gupta 217
	}
218
 
26846 tejbeer 219
	@RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
220
	public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id)
221
			throws ProfitMandiBusinessException {
222
 
223
		List<SuggestedPoDetail> mpd = monthlyPoDetailRepository.selectByPoId(id);
224
		Map<Integer, Integer> itemIdsQtyMap = mpd.stream()
225
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
226
 
227
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
228
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
229
		RestClient rc = new RestClient();
230
		Map<String, String> params = new HashMap<>();
231
		List<String> mandatoryQ = new ArrayList<>();
232
		mandatoryQ.add(
233
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
234
		params.put("start", "0");
235
		params.put("rows", "100");
236
		params.put("q", StringUtils.join(mandatoryQ, " "));
237
		params.put("fl", "*, [child parentFilter=id:catalog*]");
238
 
239
		params.put("wt", "json");
240
		String response = null;
241
		try {
26889 amit.gupta 242
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
26846 tejbeer 243
		} catch (HttpHostConnectException e) {
244
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
245
		}
246
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
247
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
248
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
249
 
250
		return responseSender.ok(dealResponse);
251
	}
252
 
26847 tejbeer 253
	@RequestMapping(value = "/suggestedPo/status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26848 tejbeer 254
	@ApiImplicitParams({
31507 tejbeer 255
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26848 tejbeer 256
	@ApiOperation(value = "")
26847 tejbeer 257
	public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id)
258
			throws ProfitMandiBusinessException {
259
		SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);
260
		suggestedPo.setStatus("closed");
261
 
262
		return responseSender.ok(true);
263
	}
264
 
31625 tejbeer 265
	@RequestMapping(value = "/fofo/fovourites", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
31629 tejbeer 266
	public ResponseEntity<?> getFavourites(HttpServletRequest request) throws Exception {
31625 tejbeer 267
 
31629 tejbeer 268
		int userId = (int) request.getAttribute("userId");
269
		UserCart uc = userAccountRepository.getUserCart(userId);
270
		int fofoId = uc.getUserId();
31670 tejbeer 271
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
31625 tejbeer 272
		Set<Integer> catalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream()
31628 tejbeer 273
				.map(x -> x.getCatalogId()).collect(Collectors.toSet());
31670 tejbeer 274
		if (!catalogIds.isEmpty()) {
31625 tejbeer 275
 
31670 tejbeer 276
			RestClient rc = new RestClient();
277
			Map<String, String> params = new HashMap<>();
278
			List<String> mandatoryQ = new ArrayList<>();
279
			mandatoryQ.add(String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}",
280
					StringUtils.join(catalogIds, " ")));
281
			params.put("start", "0");
282
			params.put("rows", "100");
283
			params.put("q", StringUtils.join(mandatoryQ, " "));
284
			params.put("fl", "*, [child parentFilter=id:catalog*]");
285
 
286
			params.put("wt", "json");
287
			String response = null;
288
			try {
289
				response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
290
			} catch (HttpHostConnectException e) {
291
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
292
			}
293
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
294
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
295
			dealResponse = getCatalogResponse(docs, false, fofoId);
31625 tejbeer 296
		}
297
		return responseSender.ok(dealResponse);
298
	}
299
 
300
	@RequestMapping(value = "/favourites/manage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
301
	@ApiImplicitParams({
302
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
303
	@ApiOperation(value = "")
304
	public ResponseEntity<?> mangeFavourites(HttpServletRequest request, @RequestParam int catalogId)
305
			throws ProfitMandiBusinessException {
306
 
307
		int userId = (int) request.getAttribute("userId");
308
		UserCart uc = userAccountRepository.getUserCart(userId);
309
		int fofoId = uc.getUserId();
310
 
311
		CatalogFavourite catalogFavourite = catalogFavouriteRepository.selectBypartnerAndCatalogId(fofoId, catalogId);
312
 
313
		if (catalogFavourite == null) {
314
			catalogFavourite = new CatalogFavourite();
31628 tejbeer 315
			catalogFavourite.setCatalogId(catalogId);
31625 tejbeer 316
			catalogFavourite.setFofoId(fofoId);
317
			catalogFavourite.setCreatedTimestamp(LocalDateTime.now());
318
			catalogFavouriteRepository.persist(catalogFavourite);
319
 
320
		}
321
 
322
		else {
323
			catalogFavouriteRepository.deleteByPartnerAndCatalogId(fofoId, catalogId);
324
		}
325
		return responseSender.ok(true);
326
	}
327
 
23816 amit.gupta 328
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 329
		UserCart uc = userAccountRepository.getUserCart(userId);
330
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 331
		List<String> strTagIds = new ArrayList<>();
332
		for (Integer tagId : tagIds) {
333
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 334
		}
22287 amit.gupta 335
		return String.join(",", strTagIds);
22273 amit.gupta 336
	}
337
 
22319 amit.gupta 338
	@ApiImplicitParams({
31507 tejbeer 339
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22319 amit.gupta 340
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 341
	public ResponseEntity<?> getFofo(HttpServletRequest request,
31507 tejbeer 342
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
343
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
344
			@RequestParam(value = "sort", required = false) String sort,
345
			@RequestParam(value = "brand", required = false) String brand,
346
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
347
			@RequestParam(value = "q", required = false) String queryTerm,
31548 tejbeer 348
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal,
349
			@RequestParam(value = "endPoint", required = false) String endPoint) throws Throwable {
22328 amit.gupta 350
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 351
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
27090 amit.gupta 352
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
28262 amit.gupta 353
		sort = "w" + fs.getWarehouseId() + "_i desc";
31548 tejbeer 354
 
355
		logger.info("endPoint {}", endPoint);
31552 tejbeer 356
 
31554 tejbeer 357
		if (endPoint != null && !endPoint.trim().isEmpty()) {
31552 tejbeer 358
			WebListing webListing = webListingRepository.selectByUrl(endPoint);
31557 tejbeer 359
			dealResponse = this.getDealResponses(userInfo, webListing, offset, limit);
31552 tejbeer 360
 
361
		} else {
362
 
31548 tejbeer 363
			dealResponse = this.getCatalogResponse(
364
					solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal),
365
					hotDeal, userInfo.getRetailerId());
366
		}
28101 amit.gupta 367
		logger.info("log me");
26889 amit.gupta 368
		return responseSender.ok(dealResponse);
369
	}
25015 amit.gupta 370
 
22319 amit.gupta 371
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 372
	@ApiImplicitParams({
31507 tejbeer 373
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 374
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 375
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
31507 tejbeer 376
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
377
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
378
			@RequestParam(value = "direction", required = false) String direction,
379
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
22319 amit.gupta 380
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 381
		String response = null;
22319 amit.gupta 382
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 383
 
22319 amit.gupta 384
		String uri = "/deals/" + userId;
23532 amit.gupta 385
		RestClient rc = new RestClient();
22272 amit.gupta 386
		Map<String, String> params = new HashMap<>();
387
		params.put("offset", offset);
388
		params.put("limit", limit);
389
		params.put("categoryId", categoryId);
390
		params.put("direction", direction);
391
		params.put("sort", sort);
392
		params.put("source", "online");
393
		params.put("filterData", filterData);
23816 amit.gupta 394
		/*
395
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
396
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
397
		 */
22272 amit.gupta 398
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 399
		try {
400
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
401
		} catch (HttpHostConnectException e) {
402
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
403
		}
22931 ashik.ali 404
 
22272 amit.gupta 405
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 406
		for (JsonValue j : result_json) {
23816 amit.gupta 407
			// logger.info("res " + j.asArray());
22272 amit.gupta 408
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 409
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 410
				innerObject.add(toDealObject(jsonObject.asObject()));
411
			}
22319 amit.gupta 412
			if (innerObject.size() > 0) {
22272 amit.gupta 413
				responseObject.add(innerObject);
414
			}
415
		}
23022 ashik.ali 416
		return responseSender.ok(responseObject);
22272 amit.gupta 417
	}
418
 
22319 amit.gupta 419
	private Object toDealObject(JsonObject jsonObject) {
420
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 421
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
422
		}
423
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
424
	}
22319 amit.gupta 425
 
426
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 427
	@ApiImplicitParams({
31507 tejbeer 428
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 429
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 430
	public ResponseEntity<?> getBrands(HttpServletRequest request,
31507 tejbeer 431
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 432
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 433
		String response = null;
22319 amit.gupta 434
		// TODO: move to properties
21356 kshitij.so 435
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 436
		RestClient rc = new RestClient();
21356 kshitij.so 437
		Map<String, String> params = new HashMap<>();
438
		params.put("category_id", category_id);
21358 kshitij.so 439
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 440
		try {
441
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
442
		} catch (HttpHostConnectException e) {
443
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
444
		}
23816 amit.gupta 445
 
22319 amit.gupta 446
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
447
		}.getType());
23022 ashik.ali 448
 
449
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 450
	}
22319 amit.gupta 451
 
452
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 453
	@ApiImplicitParams({
31507 tejbeer 454
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 455
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 456
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
457
			throws ProfitMandiBusinessException {
21445 kshitij.so 458
		String response = null;
22319 amit.gupta 459
		// TODO: move to properties
460
		String uri = "getDealById/" + id;
461
		System.out.println("Unit deal " + uri);
23532 amit.gupta 462
		RestClient rc = new RestClient();
21445 kshitij.so 463
		Map<String, String> params = new HashMap<>();
464
		DealsResponse dealsResponse = null;
23532 amit.gupta 465
		try {
466
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
467
		} catch (HttpHostConnectException e) {
468
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
469
		}
23816 amit.gupta 470
 
21445 kshitij.so 471
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 472
		if (!result_json.isEmpty()) {
21445 kshitij.so 473
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 474
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 475
			while (iter.hasNext()) {
22952 amit.gupta 476
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 477
				if (ai.getAvailability() <= 0)
22952 amit.gupta 478
					iter.remove();
479
			}
21445 kshitij.so 480
		}
22952 amit.gupta 481
		return responseSender.ok(dealsResponse);
21445 kshitij.so 482
	}
23816 amit.gupta 483
 
24091 tejbeer 484
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
485
	@ApiImplicitParams({
31507 tejbeer 486
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
24091 tejbeer 487
	@ApiOperation(value = "Get unit deal object")
488
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
27030 amit.gupta 489
			throws Exception {
24091 tejbeer 490
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
491
		List<Integer> tagIds = Arrays.asList(4);
492
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
493
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
494
			String categoryId = "(3 OR 6)";
495
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
496
			RestClient rc = new RestClient();
497
			Map<String, String> params = new HashMap<>();
498
			List<String> mandatoryQ = new ArrayList<>();
499
			String catalogString = "catalog" + id;
500
 
24149 amit.gupta 501
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
502
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
503
 
24091 tejbeer 504
			params.put("q", StringUtils.join(mandatoryQ, " "));
505
			params.put("fl", "*, [child parentFilter=id:catalog*]");
506
			params.put("sort", "rank_i asc, create_s desc");
507
			params.put("wt", "json");
508
			String response = null;
509
			try {
26575 amit.gupta 510
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 511
			} catch (HttpHostConnectException e) {
512
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
513
			}
514
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
515
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26889 amit.gupta 516
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
24091 tejbeer 517
		} else {
518
			return responseSender.badRequest(
519
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
520
		}
521
		return responseSender.ok(dealResponse.get(0));
522
	}
523
 
22333 amit.gupta 524
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 525
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
31507 tejbeer 526
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 527
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 528
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 529
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
530
				categoryId);
24163 amit.gupta 531
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 532
	}
25879 amit.gupta 533
 
31507 tejbeer 534
	@RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
535
	public ResponseEntity<?> getBrands(HttpServletRequest request,
536
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
537
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
538
		logger.info("userInfo [{}]", userInfo);
539
 
540
		List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(),
541
				categoryId);
542
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
543
	}
544
 
25813 amit.gupta 545
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
546
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
547
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
548
		logger.info("userInfo [{}]", userInfo);
26889 amit.gupta 549
		List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
550
		return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
25813 amit.gupta 551
	}
23816 amit.gupta 552
 
25011 amit.gupta 553
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 554
		List<DBObject> subCategories = new ArrayList<>();
555
		RestClient rc = new RestClient();
556
		Map<String, String> params = new HashMap<>();
557
		params.put("q", "categoryId_i:6");
558
		params.put("group", "true");
559
		params.put("group.field", "subCategoryId_i");
560
		params.put("wt", "json");
25126 amit.gupta 561
		params.put("rows", "50");
25014 amit.gupta 562
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 563
		String response = null;
564
		try {
26575 amit.gupta 565
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 566
		} catch (HttpHostConnectException e) {
567
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
568
		}
569
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
570
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
571
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 572
		for (int i = 0; i < groups.length(); i++) {
573
			JSONObject groupObject = groups.getJSONObject(i);
574
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 575
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 576
			categoryIds.add(subCategoryId);
25010 amit.gupta 577
		}
25015 amit.gupta 578
 
25010 amit.gupta 579
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 580
		AtomicInteger i = new AtomicInteger(0);
581
		categories.forEach(x -> {
25011 amit.gupta 582
			DBObject dbObject = new BasicDBObject();
583
			dbObject.put("name", x.getLabel());
584
			dbObject.put("subCategoryId", x.getId());
585
			dbObject.put("rank", i.incrementAndGet());
586
			dbObject.put("categoryId", 6);
26441 tejbeer 587
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 588
			subCategories.add(dbObject);
25010 amit.gupta 589
		});
25015 amit.gupta 590
 
25011 amit.gupta 591
		return subCategories;
25015 amit.gupta 592
 
25010 amit.gupta 593
	}
594
 
22446 amit.gupta 595
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 596
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 597
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 598
	}
23816 amit.gupta 599
 
23793 tejbeer 600
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
601
	public ResponseEntity<?> getSubcategoriesToDisplay() {
602
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
603
	}
23816 amit.gupta 604
 
22406 amit.gupta 605
	@ApiImplicitParams({
31507 tejbeer 606
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 607
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 608
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 609
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
610
		String uri = sb.append(skus).toString();
23532 amit.gupta 611
		RestClient rc = new RestClient();
612
		String response;
613
		try {
614
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 615
		} catch (HttpHostConnectException e) {
23532 amit.gupta 616
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
617
		}
22406 amit.gupta 618
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 619
		List<Object> responseObject = new ArrayList<>();
620
		for (JsonValue j : result_json) {
23816 amit.gupta 621
			// logger.info("res " + j.asArray());
22407 amit.gupta 622
			List<Object> innerObject = new ArrayList<>();
623
			for (JsonValue jsonObject : j.asArray()) {
624
				innerObject.add(toDealObject(jsonObject.asObject()));
625
			}
626
			if (innerObject.size() > 0) {
627
				responseObject.add(innerObject);
628
			}
629
		}
22408 amit.gupta 630
		return responseSender.ok(responseObject);
22401 amit.gupta 631
	}
21339 kshitij.so 632
 
31547 tejbeer 633
	@RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
634
	public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
635
		List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true),
31572 tejbeer 636
				WebListingSource.partner);
31547 tejbeer 637
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
638
		for (WebListing webListing : webListings) {
31642 tejbeer 639
 
31649 tejbeer 640
			webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing, "0", "20"));
31547 tejbeer 641
		}
642
		return responseSender.ok(webListings);
643
	}
644
 
31557 tejbeer 645
	private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing, String offset,
646
			String limit) throws Exception {
31572 tejbeer 647
 
31547 tejbeer 648
		RestClient rc = new RestClient();
649
		Map<String, String> params = new HashMap<>();
650
		List<String> mandatoryQ = new ArrayList<>();
31596 amit.gupta 651
		mandatoryQ.add("show_default_b:true");
31625 tejbeer 652
 
31670 tejbeer 653
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
654
 
655
		params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
656
 
31612 tejbeer 657
		List<Integer> webProducts = null;
31578 tejbeer 658
		if (webListing.getType().equals(WebListingType.solr)) {
31576 tejbeer 659
			logger.info("solrtype {}", webListing.getSolrQuery());
31584 tejbeer 660
			mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true"));
31572 tejbeer 661
		} else {
31576 tejbeer 662
			logger.info("solrtype2 {}", webListing.getSolrQuery());
663
 
31612 tejbeer 664
			webProducts = webProductListingRepository
31572 tejbeer 665
					.selectAllByWebListingId(webListing.getId(), Integer.parseInt(offset), Integer.parseInt(limit))
666
					.stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31675 tejbeer 667
 
31572 tejbeer 668
			if (webProducts.size() == 0) {
669
				return new ArrayList<>();
670
			}
671
 
31676 tejbeer 672
			mandatoryQ.add(String.format("+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ")
673
					+ "\"} AND active_b:true AND hsncode_s:85171300"));
31572 tejbeer 674
 
675
		}
31547 tejbeer 676
		params.put("q", StringUtils.join(mandatoryQ, " "));
31581 tejbeer 677
		params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31642 tejbeer 678
 
31557 tejbeer 679
		params.put("start", String.valueOf(offset));
680
		params.put("rows", String.valueOf(limit));
31547 tejbeer 681
		params.put("wt", "json");
682
		String response = null;
683
		try {
31612 tejbeer 684
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
31547 tejbeer 685
		} catch (HttpHostConnectException e) {
686
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
687
		}
688
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
689
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
690
		List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31612 tejbeer 691
 
31671 tejbeer 692
		if (webProducts != null && webListing.getUrl().equals("new-launches")) {
693
			List<Integer> webProductsFinal = webProducts;
694
			dealResponse = dealResponse.stream()
695
					.sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId())))
696
					.collect(Collectors.toList());
697
 
698
		}
699
 
31547 tejbeer 700
		return dealResponse;
701
	}
702
 
30669 amit.gupta 703
	@Autowired
704
	private SaholicCISTableRepository saholicCISTableRepository;
705
 
27053 amit.gupta 706
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
24091 tejbeer 707
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
708
		List<Integer> tagIds = Arrays.asList(4);
26924 amit.gupta 709
		List<Integer> itemIds = new ArrayList<>();
24091 tejbeer 710
		if (docs.length() > 0) {
711
			for (int i = 0; i < docs.length(); i++) {
712
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 713
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 714
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
715
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
716
						int itemId = childItem.getInt("itemId_i");
26924 amit.gupta 717
						itemIds.add(itemId);
26515 amit.gupta 718
					}
24091 tejbeer 719
				}
720
			}
26924 amit.gupta 721
			if (itemIds.size() == 0) {
26573 amit.gupta 722
				return dealResponse;
723
			}
24091 tejbeer 724
		}
27053 amit.gupta 725
		// get warehouse Id
27030 amit.gupta 726
		int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
27053 amit.gupta 727
		Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems()
728
				.get(warehouseId);
30123 amit.gupta 729
		List<Integer> catalogIds = new ArrayList<>();
730
		for (int i = 0; i < docs.length(); i++) {
731
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
732
			JSONObject doc = docs.getJSONObject(i);
733
			catalogIds.add(doc.getInt("catalogId_i"));
734
		}
30188 amit.gupta 735
		List<CreateOfferRequest> allSchemOffers = null;
30156 amit.gupta 736
		Map<Integer, PriceCircularItemModel> priceCircularItemModelMap = new HashMap<>();
737
		if (catalogIds.size() > 0) {
738
			PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds);
30188 amit.gupta 739
			allSchemOffers = priceCircularModel.getOffers();
27053 amit.gupta 740
 
30156 amit.gupta 741
			List<PriceCircularItemModel> priceCircularItemModels = priceCircularModel.getPriceCircularItemModels();
742
			if (priceCircularItemModels != null) {
30595 tejbeer 743
				priceCircularItemModelMap = priceCircularItemModels.stream()
744
						.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
30156 amit.gupta 745
			}
30123 amit.gupta 746
		}
30188 amit.gupta 747
 
31629 tejbeer 748
		List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
749
		List<Integer> catalogFavouriteIds = new ArrayList<>();
750
		if (!catalogFavourites.isEmpty()) {
751
			catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
752
		}
753
 
754
		if (!catalogFavourites.isEmpty()) {
755
			catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
756
		}
757
 
24091 tejbeer 758
		for (int i = 0; i < docs.length(); i++) {
759
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
760
			JSONObject doc = docs.getJSONObject(i);
30188 amit.gupta 761
			FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
762
			fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
763
			fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
764
			fofoCatalogResponse.setTitle(doc.getString("title_s"));
30595 tejbeer 765
 
31629 tejbeer 766
			if (catalogFavouriteIds.contains(fofoCatalogResponse.getCatalogId())) {
767
				fofoCatalogResponse.setFavourite(true);
768
			}
769
 
30595 tejbeer 770
			List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers()
771
					.get(fofoCatalogResponse.getCatalogId());
30683 tejbeer 772
 
30617 tejbeer 773
			logger.info("webOffers {}", webOffers);
30595 tejbeer 774
			if (webOffers != null && webOffers.size() > 0) {
30597 tejbeer 775
				fofoCatalogResponse.setWebOffers(webOffers);
31612 tejbeer 776
				fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
777
 
30595 tejbeer 778
			}
30683 tejbeer 779
 
780
			List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream()
781
					.filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());
782
 
783
			for (ComboModel comboModel : comboModels) {
784
 
785
				List<ComboMappedModel> mappedModels = comboMappedModelRepository.selectByComboId(comboModel.getId());
786
 
787
				comboModel.setComboMappedModels(mappedModels);
788
 
789
			}
790
 
791
			if (comboModels != null && comboModels.size() > 0) {
792
				fofoCatalogResponse.setComboModels(comboModels);
793
			}
794
 
24117 amit.gupta 795
			try {
30188 amit.gupta 796
				fofoCatalogResponse.setFeature(doc.getString("feature_s"));
24149 amit.gupta 797
			} catch (Exception e) {
30188 amit.gupta 798
				fofoCatalogResponse.setFeature(null);
799
				logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
24117 amit.gupta 800
			}
31612 tejbeer 801
 
30188 amit.gupta 802
			fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
31612 tejbeer 803
			logger.info("labelss {}", doc.has("label_ss"));
804
 
805
			if (doc.has("label_ss")) {
806
				logger.info("label {}", doc.getJSONArray("label_ss"));
807
 
808
				JSONArray arr = doc.getJSONArray("label_ss");
809
				List<String> labels = new ArrayList<String>();
31635 tejbeer 810
				for (int j = 0; j < arr.length(); j++) {
31612 tejbeer 811
					labels.add(arr.getString(j));
812
				}
813
 
814
				fofoCatalogResponse.setLabels(labels);
815
 
816
			}
817
 
26589 amit.gupta 818
			if (doc.has("_childDocuments_")) {
27035 amit.gupta 819
				String modelColorClass = "grey";
27042 amit.gupta 820
				FofoAvailabilityInfo fdiAnyColour = null;
31507 tejbeer 821
				// Iterating itemIds
26515 amit.gupta 822
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
30595 tejbeer 823
					PriceCircularItemModel priceCircularItemModel = priceCircularItemModelMap
824
							.get(fofoCatalogResponse.getCatalogId());
26515 amit.gupta 825
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
826
					int itemId = childItem.getInt("itemId_i");
827
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
31507 tejbeer 828
					if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
26515 amit.gupta 829
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
31507 tejbeer 830
						List<SaholicCISTable> currentAvailability = saholicCISTableRepository
831
								.selectByItemWarehouse(itemId, warehouseId);
27869 amit.gupta 832
						List<SaholicPOItem> poItemAvailability = null;
28262 amit.gupta 833
						if (poItemAvailabilityMap != null) {
27869 amit.gupta 834
							poItemAvailability = poItemAvailabilityMap.get(itemId);
835
						}
30175 amit.gupta 836
						fdi.setNlc(priceCircularItemModel == null ? 0 : priceCircularItemModel.getNetPrice());
30686 amit.gupta 837
 
31625 tejbeer 838
						fdi.setNlc(fdi.getNlc() == 0 ? sellingPrice : priceCircularItemModel.getNetPrice());
839
 
30686 amit.gupta 840
						for (SaholicCISTable saholicCISTable : currentAvailability) {
841
							saholicCISTable.setWarehouseName(
842
									ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
27062 amit.gupta 843
						}
30693 amit.gupta 844
 
845
						Map<Integer, SaholicCISTable> map = currentAvailability.stream()
30686 amit.gupta 846
								.collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
28262 amit.gupta 847
						if (poItemAvailability != null) {
30686 amit.gupta 848
							for (SaholicPOItem saholicPOItem : poItemAvailability) {
849
								if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
850
									map.get(saholicPOItem.getWarehouseFrom())
851
											.setPopendingQty(saholicPOItem.getUnfulfilledQty());
852
								} else {
30669 amit.gupta 853
									SaholicCISTable saholicCISTable = new SaholicCISTable();
854
									saholicCISTable.setAvailability(0);
855
									saholicCISTable.setReserved(0);
856
									saholicCISTable.setItemId(itemId);
30692 amit.gupta 857
									saholicCISTable.setWarehouseId(warehouseId);
30669 amit.gupta 858
									saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
859
									saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
31507 tejbeer 860
									saholicCISTable.setWarehouseName(
861
											ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
30669 amit.gupta 862
									map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
27053 amit.gupta 863
								}
864
							}
865
						}
30669 amit.gupta 866
						fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
27042 amit.gupta 867
						String poColor = "grey";
27032 amit.gupta 868
						boolean active = false;
27053 amit.gupta 869
						if (currentAvailability != null && currentAvailability.stream()
30669 amit.gupta 870
								.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
27053 amit.gupta 871
							poColor = "green";
872
							modelColorClass = "green";
873
						} else if (poItemAvailability != null && poItemAvailability.stream()
874
								.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
875
							if (currentAvailability != null && poItemAvailability.stream()
876
									.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty))
877
									+ currentAvailability.stream()
31507 tejbeer 878
											.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
27042 amit.gupta 879
								poColor = "grey";
27032 amit.gupta 880
							} else {
27040 amit.gupta 881
								poColor = "yellow";
27053 amit.gupta 882
								if (modelColorClass != "green") {
27035 amit.gupta 883
									modelColorClass = poColor;
884
								}
27032 amit.gupta 885
							}
27031 amit.gupta 886
						}
27032 amit.gupta 887
						fdi.setColorClass(poColor);
26889 amit.gupta 888
						fdi.setSellingPrice(sellingPrice);
27031 amit.gupta 889
						fdi.setActive(active);
26889 amit.gupta 890
						fdi.setMrp(childItem.getDouble("mrp_f"));
26515 amit.gupta 891
						fdi.setMop((float) childItem.getDouble("mop_f"));
892
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
27042 amit.gupta 893
						if (fdi.getColor().equalsIgnoreCase("any colour")) {
27053 amit.gupta 894
							fdiAnyColour = fdi;
27042 amit.gupta 895
						}
26515 amit.gupta 896
						fdi.setTagId(childItem.getInt("tagId_i"));
897
						fdi.setItem_id(itemId);
30595 tejbeer 898
						Float cashBack = schemeService.getCatalogSchemeCashBack()
899
								.get(fofoCatalogResponse.getCatalogId());
26846 tejbeer 900
						cashBack = cashBack == null ? 0 : cashBack;
26696 amit.gupta 901
						fdi.setCashback(cashBack);
26897 amit.gupta 902
						fdi.setMinBuyQuantity(1);
28268 amit.gupta 903
						if (hotDeal) {
904
							if (currentAvailability != null) {
905
								fdi.setAvailability(currentAvailability.stream()
30669 amit.gupta 906
										.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
28268 amit.gupta 907
							} else {
908
								fdi.setAvailability(0);
909
							}
910
						} else {
30595 tejbeer 911
							// Lets consider that its out of stock
28268 amit.gupta 912
							fdi.setAvailability(100);
913
							Item item = null;
30135 amit.gupta 914
							try {
28268 amit.gupta 915
								item = itemRepository.selectById(itemId);
30135 amit.gupta 916
							} catch (Exception e) {
28268 amit.gupta 917
								e.printStackTrace();
918
								continue;
919
							}
30711 amit.gupta 920
							// In case its tampered glass moq should be
28268 amit.gupta 921
							if (item.getCategoryId() == 10020) {
922
								fdi.setMinBuyQuantity(5);
923
							}
24091 tejbeer 924
						}
26515 amit.gupta 925
						fdi.setQuantityStep(1);
926
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
927
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 928
					}
929
				}
27053 amit.gupta 930
				if (fdiAnyColour != null) {
30444 amit.gupta 931
					fdiAnyColour.setColorClass(modelColorClass);
27042 amit.gupta 932
				}
24091 tejbeer 933
			}
934
			if (fofoAvailabilityInfoMap.values().size() > 0) {
27053 amit.gupta 935
				List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream()
936
						.sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed())
937
						.collect(Collectors.toList());
30188 amit.gupta 938
				fofoCatalogResponse.setItems(availabilityList);
939
				if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
30595 tejbeer 940
					PriceCircularItemModel priceCircularItemModel = priceCircularItemModelMap
941
							.get(fofoCatalogResponse.getCatalogId());
30193 amit.gupta 942
					if (priceCircularItemModel.getSlabPayouts() != null) {
943
						List<CreateOfferRequest> schemeOffers = new ArrayList<>();
30196 amit.gupta 944
						List<Map<Integer, Long>> slabPayouts = priceCircularItemModel.getSlabPayouts();
945
						Iterator<Map<Integer, Long>> iterator = slabPayouts.iterator();
946
						int iteratorCount = 0;
947
						while (iterator.hasNext()) {
948
							Map<Integer, Long> slabPayoutMap = iterator.next();
949
							if (slabPayoutMap != null) {
950
								schemeOffers.add(allSchemOffers.get(iteratorCount));
30193 amit.gupta 951
							} else {
30196 amit.gupta 952
								iterator.remove();
30193 amit.gupta 953
							}
30198 amit.gupta 954
							iteratorCount++;
30188 amit.gupta 955
						}
30193 amit.gupta 956
						fofoCatalogResponse.setSchemeOffers(schemeOffers);
957
					}
30188 amit.gupta 958
					fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
959
				}
960
				dealResponse.add(fofoCatalogResponse);
24091 tejbeer 961
			}
27053 amit.gupta 962
		}
963
		return dealResponse;
24091 tejbeer 964
 
965
	}
966
 
25968 amit.gupta 967
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
31507 tejbeer 968
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 969
		Map<Integer, TagListing> itemTagListingMap = null;
970
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
971
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 972
 
25968 amit.gupta 973
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
974
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 975
 
25879 amit.gupta 976
		for (int i = 0; i < docs.length(); i++) {
977
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
978
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 979
 
25879 amit.gupta 980
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
981
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
982
				int itemId = childItem.getInt("itemId_i");
983
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 984
				if (tl == null) {
25968 amit.gupta 985
					continue;
986
				}
25879 amit.gupta 987
				if (hotDeal) {
988
					if (!tl.isHotDeals()) {
989
						continue;
990
					}
991
				}
992
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
993
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
994
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
995
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
996
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
997
					}
998
				} else {
999
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
1000
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
1001
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 1002
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 1003
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1004
					fdi.setTagId(childItem.getInt("tagId_i"));
1005
					fdi.setItem_id(itemId);
1006
					Item item = itemRepository.selectById(itemId);
1007
					// In case its tampered glass moq should be 5
1008
					if (item.getCategoryId() == 10020) {
1009
						fdi.setMinBuyQuantity(10);
1010
					} else {
1011
						fdi.setMinBuyQuantity(1);
1012
					}
26050 amit.gupta 1013
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 1014
					fdi.setQuantityStep(1);
1015
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
1016
					fofoAvailabilityInfoMap.put(itemId, fdi);
1017
				}
1018
			}
1019
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 1020
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 1021
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
1022
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
1023
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
1024
					ffdr.setTitle(doc.getString("title_s"));
1025
					try {
1026
						ffdr.setFeature(doc.getString("feature_s"));
1027
					} catch (Exception e) {
1028
						ffdr.setFeature(null);
1029
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
1030
					}
1031
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
1032
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
1033
					dealResponse.add(ffdr);
1034
				}
1035
			}
1036
		}
1037
		return dealResponse;
25880 amit.gupta 1038
 
25879 amit.gupta 1039
	}
30683 tejbeer 1040
 
1041
	@RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1042
	public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
1043
		List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
1044
		return responseSender.ok(comboModels);
1045
	}
25967 amit.gupta 1046
}