Subversion Repositories SmartDukaan

Rev

Rev 26788 | Rev 26846 | 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 java.util.ArrayList;
22336 amit.gupta 4
import java.util.Arrays;
21339 kshitij.so 5
import java.util.HashMap;
23814 amit.gupta 6
import java.util.HashSet;
22952 amit.gupta 7
import java.util.Iterator;
21339 kshitij.so 8
import java.util.List;
9
import java.util.Map;
25875 amit.gupta 10
import java.util.Optional;
25959 amit.gupta 11
import java.util.Set;
25010 amit.gupta 12
import java.util.concurrent.atomic.AtomicInteger;
23814 amit.gupta 13
import java.util.stream.Collectors;
21339 kshitij.so 14
 
15
import javax.servlet.http.HttpServletRequest;
16
 
22319 amit.gupta 17
import org.apache.commons.lang3.StringUtils;
23532 amit.gupta 18
import org.apache.http.conn.HttpHostConnectException;
23786 amit.gupta 19
import org.apache.logging.log4j.LogManager;
20
import org.apache.logging.log4j.Logger;
22319 amit.gupta 21
import org.json.JSONArray;
22
import org.json.JSONObject;
22273 amit.gupta 23
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 24
import org.springframework.beans.factory.annotation.Value;
25
import org.springframework.http.HttpStatus;
26
import org.springframework.http.MediaType;
27
import org.springframework.http.ResponseEntity;
28
import org.springframework.stereotype.Controller;
22286 amit.gupta 29
import org.springframework.transaction.annotation.Transactional;
21339 kshitij.so 30
import org.springframework.web.bind.annotation.PathVariable;
31
import org.springframework.web.bind.annotation.RequestMapping;
32
import org.springframework.web.bind.annotation.RequestMethod;
33
import org.springframework.web.bind.annotation.RequestParam;
34
 
35
import com.eclipsesource.json.Json;
36
import com.eclipsesource.json.JsonArray;
37
import com.eclipsesource.json.JsonObject;
38
import com.eclipsesource.json.JsonValue;
39
import com.google.gson.Gson;
21356 kshitij.so 40
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 41
import com.mongodb.BasicDBObject;
24163 amit.gupta 42
import com.mongodb.DBObject;
21643 ashik.ali 43
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
45
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 46
import com.spice.profitmandi.common.model.UserInfo;
21643 ashik.ali 47
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 48
import com.spice.profitmandi.common.web.util.ResponseSender;
25010 amit.gupta 49
import com.spice.profitmandi.dao.entity.catalog.Category;
23426 amit.gupta 50
import com.spice.profitmandi.dao.entity.catalog.Item;
23814 amit.gupta 51
import com.spice.profitmandi.dao.entity.catalog.TagListing;
23861 amit.gupta 52
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
22361 amit.gupta 53
import com.spice.profitmandi.dao.model.UserCart;
25010 amit.gupta 54
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
23426 amit.gupta 55
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23814 amit.gupta 56
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
22333 amit.gupta 57
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22361 amit.gupta 58
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
22989 amit.gupta 59
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
23798 amit.gupta 60
import com.spice.profitmandi.service.authentication.RoleManager;
25880 amit.gupta 61
import com.spice.profitmandi.service.inventory.AvailabilityInfo;
25882 amit.gupta 62
import com.spice.profitmandi.service.inventory.Bucket;
25880 amit.gupta 63
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
64
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
25875 amit.gupta 65
import com.spice.profitmandi.service.inventory.ItemBucketService;
25879 amit.gupta 66
import com.spice.profitmandi.service.inventory.ItemQuantityPojo;
22287 amit.gupta 67
import com.spice.profitmandi.service.pricing.PricingService;
26695 amit.gupta 68
import com.spice.profitmandi.service.scheme.SchemeService;
21356 kshitij.so 69
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 70
import com.spice.profitmandi.web.res.DealObjectResponse;
71
import com.spice.profitmandi.web.res.DealsResponse;
72
 
73
import io.swagger.annotations.ApiImplicitParam;
74
import io.swagger.annotations.ApiImplicitParams;
75
import io.swagger.annotations.ApiOperation;
76
 
77
@Controller
22319 amit.gupta 78
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 79
public class DealsController {
80
 
23568 govind 81
	private static final Logger logger = LogManager.getLogger(DealsController.class);
21339 kshitij.so 82
 
83
	@Value("${python.api.host}")
84
	private String host;
23816 amit.gupta 85
 
21339 kshitij.so 86
	@Value("${python.api.port}")
87
	private int port;
23816 amit.gupta 88
 
89
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 90
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 91
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 92
 
93
	@Autowired
94
	private PricingService pricingService;
23816 amit.gupta 95
 
22273 amit.gupta 96
	@Autowired
25010 amit.gupta 97
	private CategoryRepository categoryRepository;
98
 
99
	@Autowired
26695 amit.gupta 100
	private SchemeService schemeService;
101
 
102
	@Autowired
22333 amit.gupta 103
	private Mongo mongoClient;
25879 amit.gupta 104
 
25875 amit.gupta 105
	@Autowired
106
	private ItemBucketService itemBucketService;
23816 amit.gupta 107
 
22333 amit.gupta 108
	@Autowired
22361 amit.gupta 109
	private UserAccountRepository userAccountRepository;
23816 amit.gupta 110
 
22989 amit.gupta 111
	@Autowired
22931 ashik.ali 112
	private ResponseSender<?> responseSender;
23816 amit.gupta 113
 
22554 amit.gupta 114
	@Autowired
25010 amit.gupta 115
	private CategoryRepository repository;
116
 
117
	@Autowired
23814 amit.gupta 118
	private TagListingRepository tagListingRepository;
23816 amit.gupta 119
 
23814 amit.gupta 120
	@Autowired
23426 amit.gupta 121
	private ItemRepository itemRepository;
23816 amit.gupta 122
 
23786 amit.gupta 123
	@Autowired
23861 amit.gupta 124
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
125
 
126
	@Autowired
23798 amit.gupta 127
	private RoleManager roleManagerService;
23816 amit.gupta 128
 
22336 amit.gupta 129
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 130
 
23816 amit.gupta 131
 
25876 amit.gupta 132
	@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25879 amit.gupta 133
	public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
25875 amit.gupta 134
		logger.info("Request " + request.getParameterMap());
135
		return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
136
	}
25879 amit.gupta 137
 
138
	@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25880 amit.gupta 139
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 140
			throws ProfitMandiBusinessException {
25880 amit.gupta 141
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25968 amit.gupta 142
		Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream()
143
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
144
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
145
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
25879 amit.gupta 146
		RestClient rc = new RestClient();
147
		Map<String, String> params = new HashMap<>();
148
		List<String> mandatoryQ = new ArrayList<>();
25968 amit.gupta 149
		mandatoryQ.add(
150
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
25959 amit.gupta 151
		params.put("start", "0");
152
		params.put("rows", "100");
25879 amit.gupta 153
		params.put("q", StringUtils.join(mandatoryQ, " "));
154
		params.put("fl", "*, [child parentFilter=id:catalog*]");
155
 
156
		params.put("wt", "json");
157
		String response = null;
158
		try {
26573 amit.gupta 159
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25879 amit.gupta 160
		} catch (HttpHostConnectException e) {
161
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
162
		}
163
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
164
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25968 amit.gupta 165
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26051 amit.gupta 166
 
26589 amit.gupta 167
		Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id)
168
				.collect(Collectors.toList()).get(0);
25882 amit.gupta 169
		bucket.setFofoCatalogResponses(dealResponse);
170
		return responseSender.ok(bucket);
25879 amit.gupta 171
	}
172
 
23816 amit.gupta 173
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 174
		UserCart uc = userAccountRepository.getUserCart(userId);
175
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 176
		List<String> strTagIds = new ArrayList<>();
177
		for (Integer tagId : tagIds) {
178
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 179
		}
22287 amit.gupta 180
		return String.join(",", strTagIds);
22273 amit.gupta 181
	}
182
 
22319 amit.gupta 183
	@ApiImplicitParams({
184
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
185
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 186
	public ResponseEntity<?> getFofo(HttpServletRequest request,
26758 amit.gupta 187
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
22319 amit.gupta 188
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
23816 amit.gupta 189
			@RequestParam(value = "sort", required = false) String sort,
190
			@RequestParam(value = "brand", required = false) String brand,
25011 amit.gupta 191
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
24946 amit.gupta 192
			@RequestParam(value = "q", required = false) String queryTerm,
24091 tejbeer 193
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
22328 amit.gupta 194
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 195
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
23786 amit.gupta 196
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
25879 amit.gupta 197
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
25389 tejbeer 198
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
23816 amit.gupta 199
			RestClient rc = new RestClient();
22319 amit.gupta 200
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 201
			List<String> mandatoryQ = new ArrayList<>();
24974 amit.gupta 202
			if (queryTerm != null && !queryTerm.equals("null")) {
24975 amit.gupta 203
				mandatoryQ.add(String.format("+(%s)", queryTerm));
204
			} else {
205
				queryTerm = null;
24971 amit.gupta 206
			}
25015 amit.gupta 207
			if (subCategoryId != 0) {
24949 amit.gupta 208
				mandatoryQ
209
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
24875 amit.gupta 210
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
23814 amit.gupta 211
			} else if (hotDeal) {
23816 amit.gupta 212
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
213
						StringUtils.join(tagIds, " ")));
25015 amit.gupta 214
 
215
			} else if (StringUtils.isNotBlank(brand)) {
216
				mandatoryQ.add(
217
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
218
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
219
 
22347 amit.gupta 220
			} else {
26789 amit.gupta 221
				mandatoryQ
222
				.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
223
						categoryId, categoryId, StringUtils.join(tagIds, " ")));
22336 amit.gupta 224
			}
23816 amit.gupta 225
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 226
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24995 amit.gupta 227
			if (queryTerm == null) {
24975 amit.gupta 228
				params.put("sort", "create_s desc");
229
			}
22319 amit.gupta 230
			params.put("start", String.valueOf(offset));
231
			params.put("rows", String.valueOf(limit));
232
			params.put("wt", "json");
23532 amit.gupta 233
			String response = null;
234
			try {
26575 amit.gupta 235
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
23532 amit.gupta 236
			} catch (HttpHostConnectException e) {
237
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
238
			}
22319 amit.gupta 239
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
240
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 241
			dealResponse = getCatalogResponse(docs, hotDeal);
26589 amit.gupta 242
			/*
243
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
244
			 * dealResponse.stream() .filter(x ->
245
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
246
			 * ; }
247
			 */
248
		} else {
249
			return responseSender.badRequest(
250
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
251
		}
252
		return responseSender.ok(dealResponse);
253
	}
254
 
255
	@ApiImplicitParams({
256
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
257
	@RequestMapping(value = "/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
258
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
26758 amit.gupta 259
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
26589 amit.gupta 260
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
261
			@RequestParam(value = "sort", required = false) String sort,
262
			@RequestParam(value = "brand", required = false) String brand,
263
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
264
			@RequestParam(value = "q", required = false) String queryTerm,
265
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
266
			throws Throwable {
267
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
268
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
269
		UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
270
 
271
		logger.info("Retiler Id ==> {}", uc.getUserId());
272
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
273
			if(partnerStockOnly) {
274
 
24168 amit.gupta 275
			}
26589 amit.gupta 276
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
277
			RestClient rc = new RestClient();
278
			Map<String, String> params = new HashMap<>();
279
			List<String> mandatoryQ = new ArrayList<>();
280
			if (queryTerm != null && !queryTerm.equals("null")) {
281
				mandatoryQ.add(String.format("+(%s)", queryTerm));
282
			} else {
283
				queryTerm = null;
284
			}
285
			if (subCategoryId != 0) {
286
				mandatoryQ
287
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
288
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
289
			} else if (StringUtils.isNotBlank(brand)) {
290
				mandatoryQ.add(
291
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
292
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
293
 
294
			} else {
295
				mandatoryQ.add(
296
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
297
			}
298
			params.put("q", StringUtils.join(mandatoryQ, " "));
299
			params.put("fl", "*, [child parentFilter=id:catalog*]");
300
			if (queryTerm == null) {
301
				params.put("sort", "create_s desc");
302
			}
303
			params.put("start", String.valueOf(offset));
304
			params.put("rows", String.valueOf(limit));
305
			params.put("wt", "json");
306
			String response = null;
307
			try {
308
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
309
			} catch (HttpHostConnectException e) {
310
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
311
			}
312
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
313
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
314
			dealResponse = getCatalogResponse(docs, false);
315
			/*
316
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
317
			 * dealResponse.stream() .filter(x ->
318
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
319
			 * ; }
320
			 */
22319 amit.gupta 321
		} else {
23816 amit.gupta 322
			return responseSender.badRequest(
323
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 324
		}
325
		return responseSender.ok(dealResponse);
326
	}
22273 amit.gupta 327
 
22319 amit.gupta 328
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 329
	@ApiImplicitParams({
22319 amit.gupta 330
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 331
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 332
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
333
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
334
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
335
			@RequestParam(value = "direction", required = false) String direction,
336
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
337
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 338
		String response = null;
22319 amit.gupta 339
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 340
 
22319 amit.gupta 341
		String uri = "/deals/" + userId;
23532 amit.gupta 342
		RestClient rc = new RestClient();
22272 amit.gupta 343
		Map<String, String> params = new HashMap<>();
344
		params.put("offset", offset);
345
		params.put("limit", limit);
346
		params.put("categoryId", categoryId);
347
		params.put("direction", direction);
348
		params.put("sort", sort);
349
		params.put("source", "online");
350
		params.put("filterData", filterData);
23816 amit.gupta 351
		/*
352
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
353
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
354
		 */
22272 amit.gupta 355
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 356
		try {
357
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
358
		} catch (HttpHostConnectException e) {
359
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
360
		}
22931 ashik.ali 361
 
22272 amit.gupta 362
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 363
		for (JsonValue j : result_json) {
23816 amit.gupta 364
			// logger.info("res " + j.asArray());
22272 amit.gupta 365
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 366
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 367
				innerObject.add(toDealObject(jsonObject.asObject()));
368
			}
22319 amit.gupta 369
			if (innerObject.size() > 0) {
22272 amit.gupta 370
				responseObject.add(innerObject);
371
			}
372
		}
23022 ashik.ali 373
		return responseSender.ok(responseObject);
22272 amit.gupta 374
	}
375
 
22319 amit.gupta 376
	private Object toDealObject(JsonObject jsonObject) {
377
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 378
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
379
		}
380
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
381
	}
22319 amit.gupta 382
 
383
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 384
	@ApiImplicitParams({
22319 amit.gupta 385
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 386
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 387
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 388
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 389
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 390
		String response = null;
22319 amit.gupta 391
		// TODO: move to properties
21356 kshitij.so 392
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 393
		RestClient rc = new RestClient();
21356 kshitij.so 394
		Map<String, String> params = new HashMap<>();
395
		params.put("category_id", category_id);
21358 kshitij.so 396
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 397
		try {
398
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
399
		} catch (HttpHostConnectException e) {
400
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
401
		}
23816 amit.gupta 402
 
22319 amit.gupta 403
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
404
		}.getType());
23022 ashik.ali 405
 
406
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 407
	}
22319 amit.gupta 408
 
409
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 410
	@ApiImplicitParams({
22319 amit.gupta 411
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 412
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 413
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
414
			throws ProfitMandiBusinessException {
21445 kshitij.so 415
		String response = null;
22319 amit.gupta 416
		// TODO: move to properties
417
		String uri = "getDealById/" + id;
418
		System.out.println("Unit deal " + uri);
23532 amit.gupta 419
		RestClient rc = new RestClient();
21445 kshitij.so 420
		Map<String, String> params = new HashMap<>();
421
		DealsResponse dealsResponse = null;
23532 amit.gupta 422
		try {
423
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
424
		} catch (HttpHostConnectException e) {
425
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
426
		}
23816 amit.gupta 427
 
21445 kshitij.so 428
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 429
		if (!result_json.isEmpty()) {
21445 kshitij.so 430
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 431
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 432
			while (iter.hasNext()) {
22952 amit.gupta 433
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 434
				if (ai.getAvailability() <= 0)
22952 amit.gupta 435
					iter.remove();
436
			}
21445 kshitij.so 437
		}
22952 amit.gupta 438
		return responseSender.ok(dealsResponse);
21445 kshitij.so 439
	}
23816 amit.gupta 440
 
24091 tejbeer 441
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
442
	@ApiImplicitParams({
443
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
444
	@ApiOperation(value = "Get unit deal object")
445
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
446
			throws ProfitMandiBusinessException {
447
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
448
		List<Integer> tagIds = Arrays.asList(4);
449
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
450
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
451
			String categoryId = "(3 OR 6)";
452
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
453
			RestClient rc = new RestClient();
454
			Map<String, String> params = new HashMap<>();
455
			List<String> mandatoryQ = new ArrayList<>();
456
			String catalogString = "catalog" + id;
457
 
24149 amit.gupta 458
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
459
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
460
 
24091 tejbeer 461
			params.put("q", StringUtils.join(mandatoryQ, " "));
462
			params.put("fl", "*, [child parentFilter=id:catalog*]");
463
			params.put("sort", "rank_i asc, create_s desc");
464
			params.put("wt", "json");
465
			String response = null;
466
			try {
26575 amit.gupta 467
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 468
			} catch (HttpHostConnectException e) {
469
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
470
			}
471
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
472
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 473
			dealResponse = getCatalogResponse(docs, false);
24091 tejbeer 474
		} else {
475
			return responseSender.badRequest(
476
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
477
		}
478
		return responseSender.ok(dealResponse.get(0));
479
	}
480
 
22333 amit.gupta 481
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 482
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 483
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 484
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 485
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 486
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
487
				categoryId);
24163 amit.gupta 488
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 489
	}
25879 amit.gupta 490
 
25813 amit.gupta 491
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
492
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
493
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
494
		logger.info("userInfo [{}]", userInfo);
495
		List<DBObject> subCateogriesDisplay = this.getSubCategoriesToDisplay();
496
		return new ResponseEntity<>(subCateogriesDisplay, HttpStatus.OK);
497
	}
23816 amit.gupta 498
 
25011 amit.gupta 499
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 500
		List<DBObject> subCategories = new ArrayList<>();
501
		RestClient rc = new RestClient();
502
		Map<String, String> params = new HashMap<>();
503
		params.put("q", "categoryId_i:6");
504
		params.put("group", "true");
505
		params.put("group.field", "subCategoryId_i");
506
		params.put("wt", "json");
25126 amit.gupta 507
		params.put("rows", "50");
25014 amit.gupta 508
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 509
		String response = null;
510
		try {
26575 amit.gupta 511
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 512
		} catch (HttpHostConnectException e) {
513
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
514
		}
515
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
516
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
517
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 518
		for (int i = 0; i < groups.length(); i++) {
519
			JSONObject groupObject = groups.getJSONObject(i);
520
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 521
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 522
			categoryIds.add(subCategoryId);
25010 amit.gupta 523
		}
25015 amit.gupta 524
 
25010 amit.gupta 525
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 526
		AtomicInteger i = new AtomicInteger(0);
527
		categories.forEach(x -> {
25011 amit.gupta 528
			DBObject dbObject = new BasicDBObject();
529
			dbObject.put("name", x.getLabel());
530
			dbObject.put("subCategoryId", x.getId());
531
			dbObject.put("rank", i.incrementAndGet());
532
			dbObject.put("categoryId", 6);
26441 tejbeer 533
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 534
			subCategories.add(dbObject);
25010 amit.gupta 535
		});
25015 amit.gupta 536
 
25011 amit.gupta 537
		return subCategories;
25015 amit.gupta 538
 
25010 amit.gupta 539
	}
540
 
22446 amit.gupta 541
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 542
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 543
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 544
	}
23816 amit.gupta 545
 
23793 tejbeer 546
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
547
	public ResponseEntity<?> getSubcategoriesToDisplay() {
548
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
549
	}
23816 amit.gupta 550
 
22406 amit.gupta 551
	@ApiImplicitParams({
23816 amit.gupta 552
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 553
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 554
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 555
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
556
		String uri = sb.append(skus).toString();
23532 amit.gupta 557
		RestClient rc = new RestClient();
558
		String response;
559
		try {
560
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 561
		} catch (HttpHostConnectException e) {
23532 amit.gupta 562
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
563
		}
22406 amit.gupta 564
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 565
		List<Object> responseObject = new ArrayList<>();
566
		for (JsonValue j : result_json) {
23816 amit.gupta 567
			// logger.info("res " + j.asArray());
22407 amit.gupta 568
			List<Object> innerObject = new ArrayList<>();
569
			for (JsonValue jsonObject : j.asArray()) {
570
				innerObject.add(toDealObject(jsonObject.asObject()));
571
			}
572
			if (innerObject.size() > 0) {
573
				responseObject.add(innerObject);
574
			}
575
		}
22408 amit.gupta 576
		return responseSender.ok(responseObject);
22401 amit.gupta 577
	}
21339 kshitij.so 578
 
24149 amit.gupta 579
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
580
			throws ProfitMandiBusinessException {
24091 tejbeer 581
		Map<Integer, TagListing> itemTagListingMap = null;
582
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
583
		List<Integer> tagIds = Arrays.asList(4);
584
		if (docs.length() > 0) {
585
			HashSet<Integer> itemsSet = new HashSet<>();
586
			for (int i = 0; i < docs.length(); i++) {
587
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 588
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 589
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
590
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
591
						int itemId = childItem.getInt("itemId_i");
592
						itemsSet.add(itemId);
593
					}
24091 tejbeer 594
				}
595
			}
26589 amit.gupta 596
			if (itemsSet.size() == 0) {
26573 amit.gupta 597
				return dealResponse;
598
			}
24091 tejbeer 599
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
600
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
601
		}
602
 
603
		for (int i = 0; i < docs.length(); i++) {
604
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
605
			JSONObject doc = docs.getJSONObject(i);
606
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
607
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
608
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
609
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 610
			try {
611
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 612
			} catch (Exception e) {
24117 amit.gupta 613
				ffdr.setFeature(null);
24149 amit.gupta 614
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 615
			}
24091 tejbeer 616
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
26589 amit.gupta 617
			if (doc.has("_childDocuments_")) {
26515 amit.gupta 618
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
619
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
620
					int itemId = childItem.getInt("itemId_i");
621
					TagListing tl = itemTagListingMap.get(itemId);
622
					if (tl == null) {
623
						logger.warn("Could not find item id {}", itemId);
24091 tejbeer 624
						continue;
625
					}
26515 amit.gupta 626
					if (hotDeal) {
627
						if (!tl.isHotDeals()) {
628
							continue;
629
						}
24091 tejbeer 630
					}
26515 amit.gupta 631
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
632
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
633
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
634
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
635
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
636
						}
24091 tejbeer 637
					} else {
26515 amit.gupta 638
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
639
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
26665 amit.gupta 640
						fdi.setMrp((double)tl.getMrp());
26515 amit.gupta 641
						fdi.setMop((float) childItem.getDouble("mop_f"));
642
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
643
						fdi.setTagId(childItem.getInt("tagId_i"));
644
						fdi.setItem_id(itemId);
26696 amit.gupta 645
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
26699 amit.gupta 646
						cashBack = cashBack==null? 0 : cashBack;
26696 amit.gupta 647
						fdi.setCashback(cashBack);
26515 amit.gupta 648
						Item item = itemRepository.selectById(itemId);
649
						// In case its tampered glass moq should be 5
650
						if (item.getCategoryId() == 10020) {
651
							fdi.setMinBuyQuantity(10);
652
						} else {
653
							fdi.setMinBuyQuantity(1);
24091 tejbeer 654
						}
26515 amit.gupta 655
						if (hotDeal || !tl.isActive()) {
26589 amit.gupta 656
 
26515 amit.gupta 657
							int totalAvailability = 0; // Using item availability
658
							// cache for now but can be
659
							// changed to
660
							// use caching later.
661
							try {
662
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
663
								totalAvailability = iac.getTotalAvailability();
664
								fdi.setAvailability(totalAvailability);
665
							} catch (Exception e) {
666
								continue;
667
							}
668
							if (totalAvailability <= 0) {
669
								continue;
670
							}
671
						} else {
672
							// For accessories item availability should at be ordered for Rs.1000
673
							fdi.setAvailability(100);
24091 tejbeer 674
						}
26515 amit.gupta 675
						fdi.setQuantityStep(1);
676
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
677
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 678
					}
679
				}
680
			}
681
			if (fofoAvailabilityInfoMap.values().size() > 0) {
682
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
683
				dealResponse.add(ffdr);
684
			}
685
		}
686
		return dealResponse;
687
 
688
	}
689
 
25968 amit.gupta 690
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
691
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 692
		Map<Integer, TagListing> itemTagListingMap = null;
693
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
694
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 695
 
25968 amit.gupta 696
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
697
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 698
 
25879 amit.gupta 699
		for (int i = 0; i < docs.length(); i++) {
700
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
701
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 702
 
25879 amit.gupta 703
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
704
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
705
				int itemId = childItem.getInt("itemId_i");
706
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 707
				if (tl == null) {
25968 amit.gupta 708
					continue;
709
				}
25879 amit.gupta 710
				if (hotDeal) {
711
					if (!tl.isHotDeals()) {
712
						continue;
713
					}
714
				}
715
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
716
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
717
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
718
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
719
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
720
					}
721
				} else {
722
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
723
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
724
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 725
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 726
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
727
					fdi.setTagId(childItem.getInt("tagId_i"));
728
					fdi.setItem_id(itemId);
729
					Item item = itemRepository.selectById(itemId);
730
					// In case its tampered glass moq should be 5
731
					if (item.getCategoryId() == 10020) {
732
						fdi.setMinBuyQuantity(10);
733
					} else {
734
						fdi.setMinBuyQuantity(1);
735
					}
26050 amit.gupta 736
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 737
					fdi.setQuantityStep(1);
738
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
739
					fofoAvailabilityInfoMap.put(itemId, fdi);
740
				}
741
			}
742
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 743
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 744
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
745
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
746
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
747
					ffdr.setTitle(doc.getString("title_s"));
748
					try {
749
						ffdr.setFeature(doc.getString("feature_s"));
750
					} catch (Exception e) {
751
						ffdr.setFeature(null);
752
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
753
					}
754
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
755
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
756
					dealResponse.add(ffdr);
757
				}
758
			}
759
		}
760
		return dealResponse;
25880 amit.gupta 761
 
25879 amit.gupta 762
	}
25967 amit.gupta 763
}