Subversion Repositories SmartDukaan

Rev

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