Subversion Repositories SmartDukaan

Rev

Rev 25014 | Rev 25125 | 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())) {
22361 amit.gupta 198
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
199
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
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);
24995 amit.gupta 242
			if (Mongo.EMAIL_BLOCKED_BRANDS.containsKey(userInfo.getEmail())) {
25010 amit.gupta 243
				dealResponse.stream()
244
						.filter(x -> Mongo.EMAIL_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
	/*
24149 amit.gupta 302
	 * @RequestMapping(value = "/direct-deals", method=RequestMethod.GET,produces =
303
	 * MediaType.APPLICATION_JSON_VALUE)
22319 amit.gupta 304
	 * 
305
	 * @ApiImplicitParams({
306
	 * 
24149 amit.gupta 307
	 * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true,
308
	 * dataType = "string", paramType = "header") }) public ResponseEntity<?>
309
	 * getDirectDeals(HttpServletRequest request, @RequestParam(value="categoryId")
310
	 * String categoryId,@RequestParam(value="offset") String offset,
22319 amit.gupta 311
	 * 
312
	 * @RequestParam(value="limit") String limit, @RequestParam(value="sort",
24149 amit.gupta 313
	 * required=false) String sort, @RequestParam(value="direction", required=false)
314
	 * String direction,
22319 amit.gupta 315
	 * 
316
	 * @RequestParam(value="filterData", required=false) String filterData ){
317
	 * 
318
	 * return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK); }
319
	 */
320
 
321
	private Object toDealObject(JsonObject jsonObject) {
322
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 323
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
324
		}
325
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
326
	}
22319 amit.gupta 327
 
328
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 329
	@ApiImplicitParams({
22319 amit.gupta 330
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 331
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 332
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 333
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 334
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 335
		String response = null;
22319 amit.gupta 336
		// TODO: move to properties
21356 kshitij.so 337
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 338
		RestClient rc = new RestClient();
21356 kshitij.so 339
		Map<String, String> params = new HashMap<>();
340
		params.put("category_id", category_id);
21358 kshitij.so 341
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 342
		try {
343
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
344
		} catch (HttpHostConnectException e) {
345
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
346
		}
23816 amit.gupta 347
 
22319 amit.gupta 348
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
349
		}.getType());
23022 ashik.ali 350
 
351
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 352
	}
22319 amit.gupta 353
 
354
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 355
	@ApiImplicitParams({
22319 amit.gupta 356
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 357
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 358
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
359
			throws ProfitMandiBusinessException {
21445 kshitij.so 360
		String response = null;
22319 amit.gupta 361
		// TODO: move to properties
362
		String uri = "getDealById/" + id;
363
		System.out.println("Unit deal " + uri);
23532 amit.gupta 364
		RestClient rc = new RestClient();
21445 kshitij.so 365
		Map<String, String> params = new HashMap<>();
366
		DealsResponse dealsResponse = null;
23532 amit.gupta 367
		try {
368
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
369
		} catch (HttpHostConnectException e) {
370
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
371
		}
23816 amit.gupta 372
 
21445 kshitij.so 373
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 374
		if (!result_json.isEmpty()) {
21445 kshitij.so 375
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 376
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 377
			while (iter.hasNext()) {
22952 amit.gupta 378
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 379
				if (ai.getAvailability() <= 0)
22952 amit.gupta 380
					iter.remove();
381
			}
21445 kshitij.so 382
		}
23816 amit.gupta 383
		/*
384
		 * final ProfitMandiResponse<?> profitMandiResponse = new
385
		 * ProfitMandiResponse<>(LocalDateTime.now(),
24149 amit.gupta 386
		 * request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK,
387
		 * ResponseStatus.SUCCESS, dealsResponse);
23816 amit.gupta 388
		 */
22952 amit.gupta 389
		return responseSender.ok(dealsResponse);
21445 kshitij.so 390
	}
23816 amit.gupta 391
 
24091 tejbeer 392
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
393
	@ApiImplicitParams({
394
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
395
	@ApiOperation(value = "Get unit deal object")
396
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
397
			throws ProfitMandiBusinessException {
398
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
399
		List<Integer> tagIds = Arrays.asList(4);
400
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
401
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
402
			String categoryId = "(3 OR 6)";
403
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
404
			RestClient rc = new RestClient();
405
			Map<String, String> params = new HashMap<>();
406
			List<String> mandatoryQ = new ArrayList<>();
407
			String catalogString = "catalog" + id;
408
 
24149 amit.gupta 409
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
410
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
411
 
24091 tejbeer 412
			params.put("q", StringUtils.join(mandatoryQ, " "));
413
			params.put("fl", "*, [child parentFilter=id:catalog*]");
414
			params.put("sort", "rank_i asc, create_s desc");
415
			params.put("wt", "json");
416
			String response = null;
417
			try {
418
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
419
			} catch (HttpHostConnectException e) {
420
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
421
			}
422
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
423
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 424
			dealResponse = getCatalogResponse(docs, false);
24091 tejbeer 425
		} else {
426
			return responseSender.badRequest(
427
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
428
		}
429
		return responseSender.ok(dealResponse.get(0));
430
	}
431
 
22333 amit.gupta 432
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25010 amit.gupta 433
	@Cacheable(value = "display", cacheManager = "thirtyMinsTimeOutCacheManager")
24949 amit.gupta 434
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 435
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 436
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25010 amit.gupta 437
		List<DBObject> brandsDisplay = null;
438
		if (categoryId == 3) {
439
			brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
440
		} else {
25011 amit.gupta 441
			brandsDisplay = this.getSubCategoriesToDisplay();
25010 amit.gupta 442
		}
24163 amit.gupta 443
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 444
	}
23816 amit.gupta 445
 
25011 amit.gupta 446
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 447
		List<DBObject> subCategories = new ArrayList<>();
448
		RestClient rc = new RestClient();
449
		Map<String, String> params = new HashMap<>();
450
		params.put("q", "categoryId_i:6");
451
		params.put("group", "true");
452
		params.put("group.field", "subCategoryId_i");
453
		params.put("wt", "json");
25014 amit.gupta 454
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 455
		String response = null;
456
		try {
457
			response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
458
		} catch (HttpHostConnectException e) {
459
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
460
		}
461
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
462
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
463
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 464
		for (int i = 0; i < groups.length(); i++) {
465
			JSONObject groupObject = groups.getJSONObject(i);
466
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 467
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 468
			categoryIds.add(subCategoryId);
25010 amit.gupta 469
		}
25015 amit.gupta 470
 
25010 amit.gupta 471
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 472
		AtomicInteger i = new AtomicInteger(0);
473
		categories.forEach(x -> {
25011 amit.gupta 474
			DBObject dbObject = new BasicDBObject();
475
			dbObject.put("name", x.getLabel());
476
			dbObject.put("subCategoryId", x.getId());
477
			dbObject.put("rank", i.incrementAndGet());
478
			dbObject.put("categoryId", 6);
479
			dbObject.put("url", "http://api.profittill.com/uploads/campaigns/" + x.getId() + ".png");
480
			subCategories.add(dbObject);
25010 amit.gupta 481
		});
25015 amit.gupta 482
 
25011 amit.gupta 483
		return subCategories;
25015 amit.gupta 484
 
25010 amit.gupta 485
	}
486
 
22446 amit.gupta 487
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 488
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 489
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 490
	}
23816 amit.gupta 491
 
23793 tejbeer 492
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
493
	public ResponseEntity<?> getSubcategoriesToDisplay() {
494
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
495
	}
23816 amit.gupta 496
 
22406 amit.gupta 497
	@ApiImplicitParams({
23816 amit.gupta 498
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 499
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 500
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 501
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
502
		String uri = sb.append(skus).toString();
23532 amit.gupta 503
		RestClient rc = new RestClient();
504
		String response;
505
		try {
506
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 507
		} catch (HttpHostConnectException e) {
23532 amit.gupta 508
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
509
		}
22406 amit.gupta 510
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 511
		List<Object> responseObject = new ArrayList<>();
512
		for (JsonValue j : result_json) {
23816 amit.gupta 513
			// logger.info("res " + j.asArray());
22407 amit.gupta 514
			List<Object> innerObject = new ArrayList<>();
515
			for (JsonValue jsonObject : j.asArray()) {
516
				innerObject.add(toDealObject(jsonObject.asObject()));
517
			}
518
			if (innerObject.size() > 0) {
519
				responseObject.add(innerObject);
520
			}
521
		}
22408 amit.gupta 522
		return responseSender.ok(responseObject);
22401 amit.gupta 523
	}
21339 kshitij.so 524
 
24149 amit.gupta 525
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
526
			throws ProfitMandiBusinessException {
24091 tejbeer 527
		Map<Integer, TagListing> itemTagListingMap = null;
528
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
529
		List<Integer> tagIds = Arrays.asList(4);
530
		if (docs.length() > 0) {
531
			HashSet<Integer> itemsSet = new HashSet<>();
532
			for (int i = 0; i < docs.length(); i++) {
533
				JSONObject doc = docs.getJSONObject(i);
534
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
535
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
536
					int itemId = childItem.getInt("itemId_i");
537
					itemsSet.add(itemId);
538
				}
539
			}
540
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
541
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
542
		}
543
 
544
		for (int i = 0; i < docs.length(); i++) {
545
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
546
			JSONObject doc = docs.getJSONObject(i);
547
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
548
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
549
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
550
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 551
			try {
552
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 553
			} catch (Exception e) {
24117 amit.gupta 554
				ffdr.setFeature(null);
24149 amit.gupta 555
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 556
			}
24091 tejbeer 557
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
558
 
559
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
560
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
561
				int itemId = childItem.getInt("itemId_i");
562
				TagListing tl = itemTagListingMap.get(itemId);
563
				if (hotDeal) {
564
					if (!tl.isHotDeals()) {
565
						continue;
566
					}
567
				}
568
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
569
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
570
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
571
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
572
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
573
					}
574
				} else {
575
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
576
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
577
					fdi.setMop((float) childItem.getDouble("mop_f"));
578
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
579
					fdi.setTagId(childItem.getInt("tagId_i"));
580
					fdi.setItem_id(itemId);
581
					Item item = itemRepository.selectById(itemId);
582
					// In case its tampered glass moq should be 5
583
					if (item.getCategoryId() == 10020) {
584
						fdi.setMinBuyQuantity(10);
585
					} else {
586
						fdi.setMinBuyQuantity(1);
587
					}
588
					if (hotDeal || !tl.isActive()) {
589
 
590
						int totalAvailability = 0; // Using item availability
591
													// cache for now but can be
592
													// changed to
593
													// use caching later.
594
						try {
595
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
596
							totalAvailability = iac.getTotalAvailability();
597
							fdi.setAvailability(totalAvailability);
598
						} catch (Exception e) {
599
							continue;
600
						}
601
						if (totalAvailability <= 0) {
602
							continue;
603
						}
604
					} else {
24149 amit.gupta 605
						// For accessories item availability should at be ordered for Rs.1000
606
						if (item.getCategoryId() == 10020 || fdi.getSellingPrice() < 100) {
607
							fdi.setAvailability((int) Math.ceil(1000 / fdi.getSellingPrice()));
608
						} else {
609
							fdi.setAvailability(10);
610
						}
24091 tejbeer 611
					}
612
					fdi.setQuantityStep(1);
613
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
614
					fofoAvailabilityInfoMap.put(itemId, fdi);
615
				}
616
			}
617
			if (fofoAvailabilityInfoMap.values().size() > 0) {
618
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
619
				dealResponse.add(ffdr);
620
			}
621
		}
622
		return dealResponse;
623
 
624
	}
625
 
21339 kshitij.so 626
}