Subversion Repositories SmartDukaan

Rev

Rev 24038 | Rev 24101 | 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())) {
24035 amit.gupta 184
			categoryId = "(3 OR 6)";
22361 amit.gupta 185
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
186
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
23816 amit.gupta 187
			RestClient rc = new RestClient();
22319 amit.gupta 188
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 189
			List<String> mandatoryQ = new ArrayList<>();
23816 amit.gupta 190
			if (brand != null) {
191
 
24091 tejbeer 192
				mandatoryQ.add(
193
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
194
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
23814 amit.gupta 195
			} else if (hotDeal) {
23816 amit.gupta 196
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
197
						StringUtils.join(tagIds, " ")));
22347 amit.gupta 198
			} else {
23816 amit.gupta 199
				mandatoryQ.add(
200
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
24091 tejbeer 201
 
202
 
22336 amit.gupta 203
			}
23816 amit.gupta 204
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 205
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24031 amit.gupta 206
			params.put("sort", "rank_i asc, create_s desc");
22319 amit.gupta 207
			params.put("start", String.valueOf(offset));
208
			params.put("rows", String.valueOf(limit));
209
			params.put("wt", "json");
23532 amit.gupta 210
			String response = null;
211
			try {
23816 amit.gupta 212
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
23532 amit.gupta 213
			} catch (HttpHostConnectException e) {
214
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
215
			}
22319 amit.gupta 216
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
217
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24091 tejbeer 218
			dealResponse=getCatalogResponse(docs,hotDeal);
22319 amit.gupta 219
		} else {
23816 amit.gupta 220
			return responseSender.badRequest(
221
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 222
		}
223
		return responseSender.ok(dealResponse);
224
	}
22273 amit.gupta 225
 
22319 amit.gupta 226
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 227
	@ApiImplicitParams({
22319 amit.gupta 228
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 229
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 230
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
231
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
232
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
233
			@RequestParam(value = "direction", required = false) String direction,
234
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
235
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 236
		String response = null;
22319 amit.gupta 237
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 238
 
22319 amit.gupta 239
		String uri = "/deals/" + userId;
23532 amit.gupta 240
		RestClient rc = new RestClient();
22272 amit.gupta 241
		Map<String, String> params = new HashMap<>();
242
		params.put("offset", offset);
243
		params.put("limit", limit);
244
		params.put("categoryId", categoryId);
245
		params.put("direction", direction);
246
		params.put("sort", sort);
247
		params.put("source", "online");
248
		params.put("filterData", filterData);
23816 amit.gupta 249
		/*
250
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
251
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
252
		 */
22272 amit.gupta 253
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 254
		try {
255
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
256
		} catch (HttpHostConnectException e) {
257
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
258
		}
22931 ashik.ali 259
 
22272 amit.gupta 260
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 261
		for (JsonValue j : result_json) {
23816 amit.gupta 262
			// logger.info("res " + j.asArray());
22272 amit.gupta 263
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 264
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 265
				innerObject.add(toDealObject(jsonObject.asObject()));
266
			}
22319 amit.gupta 267
			if (innerObject.size() > 0) {
22272 amit.gupta 268
				responseObject.add(innerObject);
269
			}
270
		}
23022 ashik.ali 271
		return responseSender.ok(responseObject);
22272 amit.gupta 272
	}
273
 
22319 amit.gupta 274
	/*
24091 tejbeer 275
	 * @RequestMapping(value = "/direct-deals",
276
	 * method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
22319 amit.gupta 277
	 * 
278
	 * @ApiImplicitParams({
279
	 * 
24091 tejbeer 280
	 * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required =
281
	 * true, dataType = "string", paramType = "header") }) public
282
	 * ResponseEntity<?> getDirectDeals(HttpServletRequest
283
	 * request, @RequestParam(value="categoryId") String
284
	 * categoryId,@RequestParam(value="offset") String offset,
22319 amit.gupta 285
	 * 
286
	 * @RequestParam(value="limit") String limit, @RequestParam(value="sort",
24091 tejbeer 287
	 * required=false) String sort, @RequestParam(value="direction",
288
	 * required=false) String direction,
22319 amit.gupta 289
	 * 
290
	 * @RequestParam(value="filterData", required=false) String filterData ){
291
	 * 
292
	 * return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK); }
293
	 */
294
 
295
	private Object toDealObject(JsonObject jsonObject) {
296
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 297
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
298
		}
299
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
300
	}
22319 amit.gupta 301
 
302
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 303
	@ApiImplicitParams({
22319 amit.gupta 304
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 305
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 306
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 307
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 308
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 309
		String response = null;
22319 amit.gupta 310
		// TODO: move to properties
21356 kshitij.so 311
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 312
		RestClient rc = new RestClient();
21356 kshitij.so 313
		Map<String, String> params = new HashMap<>();
314
		params.put("category_id", category_id);
21358 kshitij.so 315
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 316
		try {
317
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
318
		} catch (HttpHostConnectException e) {
319
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
320
		}
23816 amit.gupta 321
 
22319 amit.gupta 322
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
323
		}.getType());
23022 ashik.ali 324
 
325
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 326
	}
22319 amit.gupta 327
 
328
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 329
	@ApiImplicitParams({
22319 amit.gupta 330
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 331
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 332
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
333
			throws ProfitMandiBusinessException {
21445 kshitij.so 334
		String response = null;
22319 amit.gupta 335
		// TODO: move to properties
336
		String uri = "getDealById/" + id;
337
		System.out.println("Unit deal " + uri);
23532 amit.gupta 338
		RestClient rc = new RestClient();
21445 kshitij.so 339
		Map<String, String> params = new HashMap<>();
340
		DealsResponse dealsResponse = null;
23532 amit.gupta 341
		try {
342
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
343
		} catch (HttpHostConnectException e) {
344
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
345
		}
23816 amit.gupta 346
 
21445 kshitij.so 347
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 348
		if (!result_json.isEmpty()) {
21445 kshitij.so 349
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 350
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 351
			while (iter.hasNext()) {
22952 amit.gupta 352
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 353
				if (ai.getAvailability() <= 0)
22952 amit.gupta 354
					iter.remove();
355
			}
21445 kshitij.so 356
		}
23816 amit.gupta 357
		/*
358
		 * final ProfitMandiResponse<?> profitMandiResponse = new
359
		 * ProfitMandiResponse<>(LocalDateTime.now(),
24091 tejbeer 360
		 * request.getRequestURL().toString(), HttpStatus.OK.toString(),
361
		 * HttpStatus.OK, ResponseStatus.SUCCESS, dealsResponse);
23816 amit.gupta 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
 
383
				mandatoryQ.add(
384
						String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
385
								categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
386
 
387
			params.put("q", StringUtils.join(mandatoryQ, " "));
388
			params.put("fl", "*, [child parentFilter=id:catalog*]");
389
			params.put("sort", "rank_i asc, create_s desc");
390
			params.put("wt", "json");
391
			String response = null;
392
			try {
393
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
394
			} catch (HttpHostConnectException e) {
395
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
396
			}
397
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
398
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
399
			dealResponse=getCatalogResponse(docs,false);
400
		} else {
401
			return responseSender.badRequest(
402
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
403
		}
404
		return responseSender.ok(dealResponse.get(0));
405
	}
406
 
407
 
22333 amit.gupta 408
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 409
	public ResponseEntity<?> getBrandsToDisplay(@RequestParam(required = false, defaultValue = "0") int categoryId) {
24031 amit.gupta 410
		return new ResponseEntity<>(mongoClient.getBrandsToDisplay(categoryId), HttpStatus.OK);
22333 amit.gupta 411
	}
23816 amit.gupta 412
 
22446 amit.gupta 413
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 414
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 415
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 416
	}
23816 amit.gupta 417
 
23793 tejbeer 418
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
419
	public ResponseEntity<?> getSubcategoriesToDisplay() {
420
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
421
	}
23816 amit.gupta 422
 
22406 amit.gupta 423
	@ApiImplicitParams({
23816 amit.gupta 424
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 425
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 426
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 427
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
428
		String uri = sb.append(skus).toString();
23532 amit.gupta 429
		RestClient rc = new RestClient();
430
		String response;
431
		try {
432
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 433
		} catch (HttpHostConnectException e) {
23532 amit.gupta 434
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
435
		}
22406 amit.gupta 436
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 437
		List<Object> responseObject = new ArrayList<>();
438
		for (JsonValue j : result_json) {
23816 amit.gupta 439
			// logger.info("res " + j.asArray());
22407 amit.gupta 440
			List<Object> innerObject = new ArrayList<>();
441
			for (JsonValue jsonObject : j.asArray()) {
442
				innerObject.add(toDealObject(jsonObject.asObject()));
443
			}
444
			if (innerObject.size() > 0) {
445
				responseObject.add(innerObject);
446
			}
447
		}
22408 amit.gupta 448
		return responseSender.ok(responseObject);
22401 amit.gupta 449
	}
21339 kshitij.so 450
 
24091 tejbeer 451
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal) throws ProfitMandiBusinessException {
452
		Map<Integer, TagListing> itemTagListingMap = null;
453
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
454
		List<Integer> tagIds = Arrays.asList(4);
455
		if (docs.length() > 0) {
456
			HashSet<Integer> itemsSet = new HashSet<>();
457
			for (int i = 0; i < docs.length(); i++) {
458
				JSONObject doc = docs.getJSONObject(i);
459
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
460
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
461
					int itemId = childItem.getInt("itemId_i");
462
					itemsSet.add(itemId);
463
				}
464
			}
465
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
466
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
467
		}
468
 
469
		for (int i = 0; i < docs.length(); i++) {
470
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
471
			JSONObject doc = docs.getJSONObject(i);
472
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
473
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
474
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
475
			ffdr.setTitle(doc.getString("title_s"));
476
 
477
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
478
 
479
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
480
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
481
				int itemId = childItem.getInt("itemId_i");
482
				TagListing tl = itemTagListingMap.get(itemId);
483
				if (hotDeal) {
484
					if (!tl.isHotDeals()) {
485
						continue;
486
					}
487
				}
488
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
489
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
490
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
491
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
492
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
493
					}
494
				} else {
495
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
496
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
497
					fdi.setMop((float) childItem.getDouble("mop_f"));
498
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
499
					fdi.setTagId(childItem.getInt("tagId_i"));
500
					fdi.setItem_id(itemId);
501
					Item item = itemRepository.selectById(itemId);
502
					// In case its tampered glass moq should be 5
503
					if (item.getCategoryId() == 10020) {
504
						fdi.setMinBuyQuantity(10);
505
					} else {
506
						fdi.setMinBuyQuantity(1);
507
					}
508
					if (hotDeal || !tl.isActive()) {
509
 
510
						int totalAvailability = 0; // Using item availability
511
													// cache for now but can be
512
													// changed to
513
													// use caching later.
514
						try {
515
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
516
							totalAvailability = iac.getTotalAvailability();
517
							fdi.setAvailability(totalAvailability);
518
						} catch (Exception e) {
519
							continue;
520
						}
521
						if (totalAvailability <= 0) {
522
							continue;
523
						}
524
					} else {
525
						fdi.setAvailability(10);
526
					}
527
					fdi.setQuantityStep(1);
528
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
529
					fofoAvailabilityInfoMap.put(itemId, fdi);
530
				}
531
			}
532
			if (fofoAvailabilityInfoMap.values().size() > 0) {
533
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
534
				dealResponse.add(ffdr);
535
			}
536
		}
537
		return dealResponse;
538
 
539
	}
540
 
21339 kshitij.so 541
}