Subversion Repositories SmartDukaan

Rev

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