Subversion Repositories SmartDukaan

Rev

Rev 26773 | Rev 26789 | 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 {
23816 amit.gupta 221
				mandatoryQ.add(
26788 amit.gupta 222
						String.format("(categoryId_i:%s) +{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
22336 amit.gupta 223
			}
23816 amit.gupta 224
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 225
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24995 amit.gupta 226
			if (queryTerm == null) {
24975 amit.gupta 227
				params.put("sort", "create_s desc");
228
			}
22319 amit.gupta 229
			params.put("start", String.valueOf(offset));
230
			params.put("rows", String.valueOf(limit));
231
			params.put("wt", "json");
23532 amit.gupta 232
			String response = null;
233
			try {
26575 amit.gupta 234
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
23532 amit.gupta 235
			} catch (HttpHostConnectException e) {
236
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
237
			}
22319 amit.gupta 238
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
239
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 240
			dealResponse = getCatalogResponse(docs, hotDeal);
26589 amit.gupta 241
			/*
242
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
243
			 * dealResponse.stream() .filter(x ->
244
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
245
			 * ; }
246
			 */
247
		} else {
248
			return responseSender.badRequest(
249
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
250
		}
251
		return responseSender.ok(dealResponse);
252
	}
253
 
254
	@ApiImplicitParams({
255
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
256
	@RequestMapping(value = "/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
257
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
26758 amit.gupta 258
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
26589 amit.gupta 259
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
260
			@RequestParam(value = "sort", required = false) String sort,
261
			@RequestParam(value = "brand", required = false) String brand,
262
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
263
			@RequestParam(value = "q", required = false) String queryTerm,
264
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
265
			throws Throwable {
266
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
267
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
268
		UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
269
 
270
		logger.info("Retiler Id ==> {}", uc.getUserId());
271
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
272
			if(partnerStockOnly) {
273
 
24168 amit.gupta 274
			}
26589 amit.gupta 275
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
276
			RestClient rc = new RestClient();
277
			Map<String, String> params = new HashMap<>();
278
			List<String> mandatoryQ = new ArrayList<>();
279
			if (queryTerm != null && !queryTerm.equals("null")) {
280
				mandatoryQ.add(String.format("+(%s)", queryTerm));
281
			} else {
282
				queryTerm = null;
283
			}
284
			if (subCategoryId != 0) {
285
				mandatoryQ
286
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
287
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
288
			} else if (StringUtils.isNotBlank(brand)) {
289
				mandatoryQ.add(
290
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
291
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
292
 
293
			} else {
294
				mandatoryQ.add(
295
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
296
			}
297
			params.put("q", StringUtils.join(mandatoryQ, " "));
298
			params.put("fl", "*, [child parentFilter=id:catalog*]");
299
			if (queryTerm == null) {
300
				params.put("sort", "create_s desc");
301
			}
302
			params.put("start", String.valueOf(offset));
303
			params.put("rows", String.valueOf(limit));
304
			params.put("wt", "json");
305
			String response = null;
306
			try {
307
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
308
			} catch (HttpHostConnectException e) {
309
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
310
			}
311
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
312
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
313
			dealResponse = getCatalogResponse(docs, false);
314
			/*
315
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
316
			 * dealResponse.stream() .filter(x ->
317
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
318
			 * ; }
319
			 */
22319 amit.gupta 320
		} else {
23816 amit.gupta 321
			return responseSender.badRequest(
322
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 323
		}
324
		return responseSender.ok(dealResponse);
325
	}
22273 amit.gupta 326
 
22319 amit.gupta 327
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 328
	@ApiImplicitParams({
22319 amit.gupta 329
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 330
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 331
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
332
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
333
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
334
			@RequestParam(value = "direction", required = false) String direction,
335
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
336
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 337
		String response = null;
22319 amit.gupta 338
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 339
 
22319 amit.gupta 340
		String uri = "/deals/" + userId;
23532 amit.gupta 341
		RestClient rc = new RestClient();
22272 amit.gupta 342
		Map<String, String> params = new HashMap<>();
343
		params.put("offset", offset);
344
		params.put("limit", limit);
345
		params.put("categoryId", categoryId);
346
		params.put("direction", direction);
347
		params.put("sort", sort);
348
		params.put("source", "online");
349
		params.put("filterData", filterData);
23816 amit.gupta 350
		/*
351
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
352
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
353
		 */
22272 amit.gupta 354
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 355
		try {
356
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
357
		} catch (HttpHostConnectException e) {
358
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
359
		}
22931 ashik.ali 360
 
22272 amit.gupta 361
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 362
		for (JsonValue j : result_json) {
23816 amit.gupta 363
			// logger.info("res " + j.asArray());
22272 amit.gupta 364
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 365
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 366
				innerObject.add(toDealObject(jsonObject.asObject()));
367
			}
22319 amit.gupta 368
			if (innerObject.size() > 0) {
22272 amit.gupta 369
				responseObject.add(innerObject);
370
			}
371
		}
23022 ashik.ali 372
		return responseSender.ok(responseObject);
22272 amit.gupta 373
	}
374
 
22319 amit.gupta 375
	private Object toDealObject(JsonObject jsonObject) {
376
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 377
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
378
		}
379
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
380
	}
22319 amit.gupta 381
 
382
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 383
	@ApiImplicitParams({
22319 amit.gupta 384
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 385
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 386
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 387
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 388
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 389
		String response = null;
22319 amit.gupta 390
		// TODO: move to properties
21356 kshitij.so 391
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 392
		RestClient rc = new RestClient();
21356 kshitij.so 393
		Map<String, String> params = new HashMap<>();
394
		params.put("category_id", category_id);
21358 kshitij.so 395
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 396
		try {
397
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
398
		} catch (HttpHostConnectException e) {
399
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
400
		}
23816 amit.gupta 401
 
22319 amit.gupta 402
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
403
		}.getType());
23022 ashik.ali 404
 
405
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 406
	}
22319 amit.gupta 407
 
408
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 409
	@ApiImplicitParams({
22319 amit.gupta 410
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 411
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 412
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
413
			throws ProfitMandiBusinessException {
21445 kshitij.so 414
		String response = null;
22319 amit.gupta 415
		// TODO: move to properties
416
		String uri = "getDealById/" + id;
417
		System.out.println("Unit deal " + uri);
23532 amit.gupta 418
		RestClient rc = new RestClient();
21445 kshitij.so 419
		Map<String, String> params = new HashMap<>();
420
		DealsResponse dealsResponse = null;
23532 amit.gupta 421
		try {
422
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
423
		} catch (HttpHostConnectException e) {
424
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
425
		}
23816 amit.gupta 426
 
21445 kshitij.so 427
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 428
		if (!result_json.isEmpty()) {
21445 kshitij.so 429
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 430
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 431
			while (iter.hasNext()) {
22952 amit.gupta 432
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 433
				if (ai.getAvailability() <= 0)
22952 amit.gupta 434
					iter.remove();
435
			}
21445 kshitij.so 436
		}
22952 amit.gupta 437
		return responseSender.ok(dealsResponse);
21445 kshitij.so 438
	}
23816 amit.gupta 439
 
24091 tejbeer 440
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
441
	@ApiImplicitParams({
442
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
443
	@ApiOperation(value = "Get unit deal object")
444
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
445
			throws ProfitMandiBusinessException {
446
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
447
		List<Integer> tagIds = Arrays.asList(4);
448
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
449
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
450
			String categoryId = "(3 OR 6)";
451
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
452
			RestClient rc = new RestClient();
453
			Map<String, String> params = new HashMap<>();
454
			List<String> mandatoryQ = new ArrayList<>();
455
			String catalogString = "catalog" + id;
456
 
24149 amit.gupta 457
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
458
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
459
 
24091 tejbeer 460
			params.put("q", StringUtils.join(mandatoryQ, " "));
461
			params.put("fl", "*, [child parentFilter=id:catalog*]");
462
			params.put("sort", "rank_i asc, create_s desc");
463
			params.put("wt", "json");
464
			String response = null;
465
			try {
26575 amit.gupta 466
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 467
			} catch (HttpHostConnectException e) {
468
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
469
			}
470
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
471
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 472
			dealResponse = getCatalogResponse(docs, false);
24091 tejbeer 473
		} else {
474
			return responseSender.badRequest(
475
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
476
		}
477
		return responseSender.ok(dealResponse.get(0));
478
	}
479
 
22333 amit.gupta 480
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 481
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 482
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 483
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 484
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 485
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
486
				categoryId);
24163 amit.gupta 487
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 488
	}
25879 amit.gupta 489
 
25813 amit.gupta 490
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
491
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
492
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
493
		logger.info("userInfo [{}]", userInfo);
494
		List<DBObject> subCateogriesDisplay = this.getSubCategoriesToDisplay();
495
		return new ResponseEntity<>(subCateogriesDisplay, HttpStatus.OK);
496
	}
23816 amit.gupta 497
 
25011 amit.gupta 498
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 499
		List<DBObject> subCategories = new ArrayList<>();
500
		RestClient rc = new RestClient();
501
		Map<String, String> params = new HashMap<>();
502
		params.put("q", "categoryId_i:6");
503
		params.put("group", "true");
504
		params.put("group.field", "subCategoryId_i");
505
		params.put("wt", "json");
25126 amit.gupta 506
		params.put("rows", "50");
25014 amit.gupta 507
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 508
		String response = null;
509
		try {
26575 amit.gupta 510
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 511
		} catch (HttpHostConnectException e) {
512
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
513
		}
514
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
515
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
516
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 517
		for (int i = 0; i < groups.length(); i++) {
518
			JSONObject groupObject = groups.getJSONObject(i);
519
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 520
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 521
			categoryIds.add(subCategoryId);
25010 amit.gupta 522
		}
25015 amit.gupta 523
 
25010 amit.gupta 524
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 525
		AtomicInteger i = new AtomicInteger(0);
526
		categories.forEach(x -> {
25011 amit.gupta 527
			DBObject dbObject = new BasicDBObject();
528
			dbObject.put("name", x.getLabel());
529
			dbObject.put("subCategoryId", x.getId());
530
			dbObject.put("rank", i.incrementAndGet());
531
			dbObject.put("categoryId", 6);
26441 tejbeer 532
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 533
			subCategories.add(dbObject);
25010 amit.gupta 534
		});
25015 amit.gupta 535
 
25011 amit.gupta 536
		return subCategories;
25015 amit.gupta 537
 
25010 amit.gupta 538
	}
539
 
22446 amit.gupta 540
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 541
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 542
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 543
	}
23816 amit.gupta 544
 
23793 tejbeer 545
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
546
	public ResponseEntity<?> getSubcategoriesToDisplay() {
547
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
548
	}
23816 amit.gupta 549
 
22406 amit.gupta 550
	@ApiImplicitParams({
23816 amit.gupta 551
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 552
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 553
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 554
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
555
		String uri = sb.append(skus).toString();
23532 amit.gupta 556
		RestClient rc = new RestClient();
557
		String response;
558
		try {
559
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 560
		} catch (HttpHostConnectException e) {
23532 amit.gupta 561
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
562
		}
22406 amit.gupta 563
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 564
		List<Object> responseObject = new ArrayList<>();
565
		for (JsonValue j : result_json) {
23816 amit.gupta 566
			// logger.info("res " + j.asArray());
22407 amit.gupta 567
			List<Object> innerObject = new ArrayList<>();
568
			for (JsonValue jsonObject : j.asArray()) {
569
				innerObject.add(toDealObject(jsonObject.asObject()));
570
			}
571
			if (innerObject.size() > 0) {
572
				responseObject.add(innerObject);
573
			}
574
		}
22408 amit.gupta 575
		return responseSender.ok(responseObject);
22401 amit.gupta 576
	}
21339 kshitij.so 577
 
24149 amit.gupta 578
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
579
			throws ProfitMandiBusinessException {
24091 tejbeer 580
		Map<Integer, TagListing> itemTagListingMap = null;
581
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
582
		List<Integer> tagIds = Arrays.asList(4);
583
		if (docs.length() > 0) {
584
			HashSet<Integer> itemsSet = new HashSet<>();
585
			for (int i = 0; i < docs.length(); i++) {
586
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 587
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 588
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
589
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
590
						int itemId = childItem.getInt("itemId_i");
591
						itemsSet.add(itemId);
592
					}
24091 tejbeer 593
				}
594
			}
26589 amit.gupta 595
			if (itemsSet.size() == 0) {
26573 amit.gupta 596
				return dealResponse;
597
			}
24091 tejbeer 598
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
599
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
600
		}
601
 
602
		for (int i = 0; i < docs.length(); i++) {
603
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
604
			JSONObject doc = docs.getJSONObject(i);
605
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
606
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
607
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
608
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 609
			try {
610
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 611
			} catch (Exception e) {
24117 amit.gupta 612
				ffdr.setFeature(null);
24149 amit.gupta 613
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 614
			}
24091 tejbeer 615
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
26589 amit.gupta 616
			if (doc.has("_childDocuments_")) {
26515 amit.gupta 617
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
618
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
619
					int itemId = childItem.getInt("itemId_i");
620
					TagListing tl = itemTagListingMap.get(itemId);
621
					if (tl == null) {
622
						logger.warn("Could not find item id {}", itemId);
24091 tejbeer 623
						continue;
624
					}
26515 amit.gupta 625
					if (hotDeal) {
626
						if (!tl.isHotDeals()) {
627
							continue;
628
						}
24091 tejbeer 629
					}
26515 amit.gupta 630
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
631
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
632
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
633
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
634
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
635
						}
24091 tejbeer 636
					} else {
26515 amit.gupta 637
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
638
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
26665 amit.gupta 639
						fdi.setMrp((double)tl.getMrp());
26515 amit.gupta 640
						fdi.setMop((float) childItem.getDouble("mop_f"));
641
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
642
						fdi.setTagId(childItem.getInt("tagId_i"));
643
						fdi.setItem_id(itemId);
26696 amit.gupta 644
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
26699 amit.gupta 645
						cashBack = cashBack==null? 0 : cashBack;
26696 amit.gupta 646
						fdi.setCashback(cashBack);
26515 amit.gupta 647
						Item item = itemRepository.selectById(itemId);
648
						// In case its tampered glass moq should be 5
649
						if (item.getCategoryId() == 10020) {
650
							fdi.setMinBuyQuantity(10);
651
						} else {
652
							fdi.setMinBuyQuantity(1);
24091 tejbeer 653
						}
26515 amit.gupta 654
						if (hotDeal || !tl.isActive()) {
26589 amit.gupta 655
 
26515 amit.gupta 656
							int totalAvailability = 0; // Using item availability
657
							// cache for now but can be
658
							// changed to
659
							// use caching later.
660
							try {
661
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
662
								totalAvailability = iac.getTotalAvailability();
663
								fdi.setAvailability(totalAvailability);
664
							} catch (Exception e) {
665
								continue;
666
							}
667
							if (totalAvailability <= 0) {
668
								continue;
669
							}
670
						} else {
671
							// For accessories item availability should at be ordered for Rs.1000
672
							fdi.setAvailability(100);
24091 tejbeer 673
						}
26515 amit.gupta 674
						fdi.setQuantityStep(1);
675
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
676
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 677
					}
678
				}
679
			}
680
			if (fofoAvailabilityInfoMap.values().size() > 0) {
681
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
682
				dealResponse.add(ffdr);
683
			}
684
		}
685
		return dealResponse;
686
 
687
	}
688
 
25968 amit.gupta 689
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
690
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 691
		Map<Integer, TagListing> itemTagListingMap = null;
692
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
693
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 694
 
25968 amit.gupta 695
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
696
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 697
 
25879 amit.gupta 698
		for (int i = 0; i < docs.length(); i++) {
699
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
700
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 701
 
25879 amit.gupta 702
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
703
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
704
				int itemId = childItem.getInt("itemId_i");
705
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 706
				if (tl == null) {
25968 amit.gupta 707
					continue;
708
				}
25879 amit.gupta 709
				if (hotDeal) {
710
					if (!tl.isHotDeals()) {
711
						continue;
712
					}
713
				}
714
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
715
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
716
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
717
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
718
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
719
					}
720
				} else {
721
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
722
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
723
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 724
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 725
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
726
					fdi.setTagId(childItem.getInt("tagId_i"));
727
					fdi.setItem_id(itemId);
728
					Item item = itemRepository.selectById(itemId);
729
					// In case its tampered glass moq should be 5
730
					if (item.getCategoryId() == 10020) {
731
						fdi.setMinBuyQuantity(10);
732
					} else {
733
						fdi.setMinBuyQuantity(1);
734
					}
26050 amit.gupta 735
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 736
					fdi.setQuantityStep(1);
737
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
738
					fofoAvailabilityInfoMap.put(itemId, fdi);
739
				}
740
			}
741
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 742
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 743
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
744
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
745
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
746
					ffdr.setTitle(doc.getString("title_s"));
747
					try {
748
						ffdr.setFeature(doc.getString("feature_s"));
749
					} catch (Exception e) {
750
						ffdr.setFeature(null);
751
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
752
					}
753
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
754
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
755
					dealResponse.add(ffdr);
756
				}
757
			}
758
		}
759
		return dealResponse;
25880 amit.gupta 760
 
25879 amit.gupta 761
	}
25967 amit.gupta 762
}