Subversion Repositories SmartDukaan

Rev

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