Subversion Repositories SmartDukaan

Rev

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