Subversion Repositories SmartDukaan

Rev

Rev 26897 | Rev 27005 | 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;
25875 amit.gupta 10
import java.util.Optional;
25959 amit.gupta 11
import java.util.Set;
25010 amit.gupta 12
import java.util.concurrent.atomic.AtomicInteger;
23814 amit.gupta 13
import java.util.stream.Collectors;
21339 kshitij.so 14
 
15
import javax.servlet.http.HttpServletRequest;
16
 
22319 amit.gupta 17
import org.apache.commons.lang3.StringUtils;
23532 amit.gupta 18
import org.apache.http.conn.HttpHostConnectException;
23786 amit.gupta 19
import org.apache.logging.log4j.LogManager;
20
import org.apache.logging.log4j.Logger;
22319 amit.gupta 21
import org.json.JSONArray;
22
import org.json.JSONObject;
22273 amit.gupta 23
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 24
import org.springframework.beans.factory.annotation.Value;
25
import org.springframework.http.HttpStatus;
26
import org.springframework.http.MediaType;
27
import org.springframework.http.ResponseEntity;
28
import org.springframework.stereotype.Controller;
22286 amit.gupta 29
import org.springframework.transaction.annotation.Transactional;
21339 kshitij.so 30
import org.springframework.web.bind.annotation.PathVariable;
31
import org.springframework.web.bind.annotation.RequestMapping;
32
import org.springframework.web.bind.annotation.RequestMethod;
33
import org.springframework.web.bind.annotation.RequestParam;
34
 
35
import com.eclipsesource.json.Json;
36
import com.eclipsesource.json.JsonArray;
37
import com.eclipsesource.json.JsonObject;
38
import com.eclipsesource.json.JsonValue;
39
import com.google.gson.Gson;
21356 kshitij.so 40
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 41
import com.mongodb.BasicDBObject;
24163 amit.gupta 42
import com.mongodb.DBObject;
21643 ashik.ali 43
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
45
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 46
import com.spice.profitmandi.common.model.UserInfo;
21643 ashik.ali 47
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 48
import com.spice.profitmandi.common.web.util.ResponseSender;
25010 amit.gupta 49
import com.spice.profitmandi.dao.entity.catalog.Category;
23426 amit.gupta 50
import com.spice.profitmandi.dao.entity.catalog.Item;
23814 amit.gupta 51
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26847 tejbeer 52
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
26846 tejbeer 53
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
22361 amit.gupta 54
import com.spice.profitmandi.dao.model.UserCart;
25010 amit.gupta 55
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
23426 amit.gupta 56
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23814 amit.gupta 57
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
22333 amit.gupta 58
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22361 amit.gupta 59
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
26889 amit.gupta 60
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26846 tejbeer 61
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
26847 tejbeer 62
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
22989 amit.gupta 63
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
23798 amit.gupta 64
import com.spice.profitmandi.service.authentication.RoleManager;
25880 amit.gupta 65
import com.spice.profitmandi.service.inventory.AvailabilityInfo;
26924 amit.gupta 66
import com.spice.profitmandi.service.inventory.AvailabilityModel;
25882 amit.gupta 67
import com.spice.profitmandi.service.inventory.Bucket;
25880 amit.gupta 68
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
69
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
26924 amit.gupta 70
import com.spice.profitmandi.service.inventory.InventoryService;
25875 amit.gupta 71
import com.spice.profitmandi.service.inventory.ItemBucketService;
25879 amit.gupta 72
import com.spice.profitmandi.service.inventory.ItemQuantityPojo;
26889 amit.gupta 73
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
22287 amit.gupta 74
import com.spice.profitmandi.service.pricing.PricingService;
26695 amit.gupta 75
import com.spice.profitmandi.service.scheme.SchemeService;
21356 kshitij.so 76
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 77
import com.spice.profitmandi.web.res.DealObjectResponse;
78
import com.spice.profitmandi.web.res.DealsResponse;
79
 
80
import io.swagger.annotations.ApiImplicitParam;
81
import io.swagger.annotations.ApiImplicitParams;
82
import io.swagger.annotations.ApiOperation;
83
 
84
@Controller
22319 amit.gupta 85
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 86
public class DealsController {
87
 
23568 govind 88
	private static final Logger logger = LogManager.getLogger(DealsController.class);
21339 kshitij.so 89
 
90
	@Value("${python.api.host}")
91
	private String host;
23816 amit.gupta 92
 
26889 amit.gupta 93
	@Value("${new.solr.url}")
94
	private String solrUrl;
95
 
21339 kshitij.so 96
	@Value("${python.api.port}")
97
	private int port;
23816 amit.gupta 98
 
26889 amit.gupta 99
	@Autowired
100
	RestClient restClient;
101
 
26924 amit.gupta 102
	@Autowired
103
	InventoryService inventoryService;
104
 
23816 amit.gupta 105
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 106
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 107
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 108
 
109
	@Autowired
110
	private PricingService pricingService;
23816 amit.gupta 111
 
22273 amit.gupta 112
	@Autowired
26889 amit.gupta 113
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
114
 
115
	@Autowired
25010 amit.gupta 116
	private CategoryRepository categoryRepository;
117
 
118
	@Autowired
26695 amit.gupta 119
	private SchemeService schemeService;
120
 
121
	@Autowired
26889 amit.gupta 122
	private SaholicInventoryService saholicInventoryService;
123
 
124
	@Autowired
22333 amit.gupta 125
	private Mongo mongoClient;
25879 amit.gupta 126
 
25875 amit.gupta 127
	@Autowired
128
	private ItemBucketService itemBucketService;
23816 amit.gupta 129
 
22333 amit.gupta 130
	@Autowired
22361 amit.gupta 131
	private UserAccountRepository userAccountRepository;
23816 amit.gupta 132
 
22989 amit.gupta 133
	@Autowired
22931 ashik.ali 134
	private ResponseSender<?> responseSender;
23816 amit.gupta 135
 
22554 amit.gupta 136
	@Autowired
25010 amit.gupta 137
	private CategoryRepository repository;
138
 
139
	@Autowired
23814 amit.gupta 140
	private TagListingRepository tagListingRepository;
23816 amit.gupta 141
 
23814 amit.gupta 142
	@Autowired
23426 amit.gupta 143
	private ItemRepository itemRepository;
23816 amit.gupta 144
 
23786 amit.gupta 145
	@Autowired
23861 amit.gupta 146
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
147
 
148
	@Autowired
23798 amit.gupta 149
	private RoleManager roleManagerService;
23816 amit.gupta 150
 
26846 tejbeer 151
	@Autowired
152
	private SuggestedPoDetailRepository monthlyPoDetailRepository;
153
 
26847 tejbeer 154
	@Autowired
155
	private SuggestedPoRepository suggestedPoRepository;
156
 
22336 amit.gupta 157
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 158
 
25876 amit.gupta 159
	@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25879 amit.gupta 160
	public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
25875 amit.gupta 161
		logger.info("Request " + request.getParameterMap());
162
		return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
163
	}
25879 amit.gupta 164
 
165
	@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25880 amit.gupta 166
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 167
			throws ProfitMandiBusinessException {
25880 amit.gupta 168
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25968 amit.gupta 169
		Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream()
170
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
171
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
172
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
25879 amit.gupta 173
		RestClient rc = new RestClient();
174
		Map<String, String> params = new HashMap<>();
175
		List<String> mandatoryQ = new ArrayList<>();
25968 amit.gupta 176
		mandatoryQ.add(
177
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
25959 amit.gupta 178
		params.put("start", "0");
179
		params.put("rows", "100");
25879 amit.gupta 180
		params.put("q", StringUtils.join(mandatoryQ, " "));
181
		params.put("fl", "*, [child parentFilter=id:catalog*]");
182
 
183
		params.put("wt", "json");
184
		String response = null;
185
		try {
26889 amit.gupta 186
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
25879 amit.gupta 187
		} catch (HttpHostConnectException e) {
188
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
189
		}
190
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
191
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25968 amit.gupta 192
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26051 amit.gupta 193
 
26589 amit.gupta 194
		Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id)
195
				.collect(Collectors.toList()).get(0);
25882 amit.gupta 196
		bucket.setFofoCatalogResponses(dealResponse);
197
		return responseSender.ok(bucket);
25879 amit.gupta 198
	}
199
 
26846 tejbeer 200
	@RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
201
	public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id)
202
			throws ProfitMandiBusinessException {
203
 
204
		List<SuggestedPoDetail> mpd = monthlyPoDetailRepository.selectByPoId(id);
205
		Map<Integer, Integer> itemIdsQtyMap = mpd.stream()
206
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
207
 
208
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
209
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
210
		RestClient rc = new RestClient();
211
		Map<String, String> params = new HashMap<>();
212
		List<String> mandatoryQ = new ArrayList<>();
213
		mandatoryQ.add(
214
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
215
		params.put("start", "0");
216
		params.put("rows", "100");
217
		params.put("q", StringUtils.join(mandatoryQ, " "));
218
		params.put("fl", "*, [child parentFilter=id:catalog*]");
219
 
220
		params.put("wt", "json");
221
		String response = null;
222
		try {
26889 amit.gupta 223
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
26846 tejbeer 224
		} catch (HttpHostConnectException e) {
225
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
226
		}
227
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
228
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
229
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
230
 
231
		return responseSender.ok(dealResponse);
232
	}
233
 
26847 tejbeer 234
	@RequestMapping(value = "/suggestedPo/status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26848 tejbeer 235
	@ApiImplicitParams({
236
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
237
	@ApiOperation(value = "")
26847 tejbeer 238
	public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id)
239
			throws ProfitMandiBusinessException {
240
		SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);
241
		suggestedPo.setStatus("closed");
242
 
243
		return responseSender.ok(true);
244
	}
245
 
23816 amit.gupta 246
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 247
		UserCart uc = userAccountRepository.getUserCart(userId);
248
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 249
		List<String> strTagIds = new ArrayList<>();
250
		for (Integer tagId : tagIds) {
251
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 252
		}
22287 amit.gupta 253
		return String.join(",", strTagIds);
22273 amit.gupta 254
	}
255
 
22319 amit.gupta 256
	@ApiImplicitParams({
257
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
258
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 259
	public ResponseEntity<?> getFofo(HttpServletRequest request,
26758 amit.gupta 260
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
22319 amit.gupta 261
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
23816 amit.gupta 262
			@RequestParam(value = "sort", required = false) String sort,
263
			@RequestParam(value = "brand", required = false) String brand,
25011 amit.gupta 264
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
24946 amit.gupta 265
			@RequestParam(value = "q", required = false) String queryTerm,
24091 tejbeer 266
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
22328 amit.gupta 267
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 268
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
26889 amit.gupta 269
		dealResponse = this.getCatalogResponse(this.getSolrDocs(userInfo.getRetailerId(), queryTerm, categoryId, offset,
270
				limit, sort, brand, subCategoryId, hotDeal), hotDeal, 0);
271
		return responseSender.ok(dealResponse);
272
	}
25015 amit.gupta 273
 
26889 amit.gupta 274
	private JSONArray getSolrDocs(int fofoId, String queryTerm, String categoryId, String offset, String limit,
275
			String sort, String brand, int subCategoryId, boolean hotDeal) throws Throwable {
276
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(fofoId);
277
		List<String> parentFilter = new ArrayList<>();
278
		parentFilter.add("categoryId_i:" + categoryId);
25015 amit.gupta 279
 
26889 amit.gupta 280
		List<String> childFilter = new ArrayList<>();
281
		childFilter.add("itemId_i:*");
282
 
283
		Map<String, String> params = new HashMap<>();
284
		if (queryTerm == null || queryTerm.equals("null")) {
285
			queryTerm = "";
26589 amit.gupta 286
		} else {
26889 amit.gupta 287
			queryTerm = "(" + queryTerm + ")";
26589 amit.gupta 288
		}
26889 amit.gupta 289
		if (hotDeal) {
290
			childFilter.add("hot_deal_b:true");
291
		} else {
292
			childFilter.add("active_b:true");
293
		}
294
		if (subCategoryId != 0) {
295
			parentFilter.add("subCategoryId_i:" + subCategoryId);
296
		}
297
		if (StringUtils.isNotBlank(brand)) {
298
			parentFilter.add("brand_ss:" + brand);
299
		}
300
		String parentFilterString = "\"" + String.join(" AND ", parentFilter) + "\"";
301
		String childFilterString = String.join(" AND ", childFilter);
302
		logger.info(parentFilterString);
303
		params.put("q", String.format("%s{!parent which=%s}%s", queryTerm, parentFilterString, childFilterString));
26897 amit.gupta 304
		params.put("fl",
305
				String.format("*, [child parentFilter=id:catalog* childFilter=%s]", "\"" + childFilterString + "\""));
26889 amit.gupta 306
		if (queryTerm == "") {
307
			params.put("sort", "create_s desc");
308
		}
309
		params.put("start", String.valueOf(offset));
310
		params.put("rows", String.valueOf(limit));
311
		params.put("wt", "json");
312
		String response = null;
313
		try {
314
			response = restClient.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
315
		} catch (HttpHostConnectException e) {
316
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
317
		}
318
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
319
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
320
		return docs;
26589 amit.gupta 321
	}
322
 
323
	@ApiImplicitParams({
324
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
325
	@RequestMapping(value = "/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
326
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
26758 amit.gupta 327
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
26589 amit.gupta 328
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
329
			@RequestParam(value = "sort", required = false) String sort,
330
			@RequestParam(value = "brand", required = false) String brand,
331
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
332
			@RequestParam(value = "q", required = false) String queryTerm,
333
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
334
			throws Throwable {
335
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
336
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
337
		UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
26889 amit.gupta 338
		dealResponse = this.getCatalogResponse(this.getSolrDocs(uc.getUserId(), queryTerm, categoryId, offset, limit,
339
				sort, brand, subCategoryId, false), false, userInfo.getRetailerId());
22319 amit.gupta 340
		return responseSender.ok(dealResponse);
341
	}
22273 amit.gupta 342
 
22319 amit.gupta 343
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 344
	@ApiImplicitParams({
22319 amit.gupta 345
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 346
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 347
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
348
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
349
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
350
			@RequestParam(value = "direction", required = false) String direction,
351
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
352
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 353
		String response = null;
22319 amit.gupta 354
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 355
 
22319 amit.gupta 356
		String uri = "/deals/" + userId;
23532 amit.gupta 357
		RestClient rc = new RestClient();
22272 amit.gupta 358
		Map<String, String> params = new HashMap<>();
359
		params.put("offset", offset);
360
		params.put("limit", limit);
361
		params.put("categoryId", categoryId);
362
		params.put("direction", direction);
363
		params.put("sort", sort);
364
		params.put("source", "online");
365
		params.put("filterData", filterData);
23816 amit.gupta 366
		/*
367
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
368
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
369
		 */
22272 amit.gupta 370
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 371
		try {
372
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
373
		} catch (HttpHostConnectException e) {
374
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
375
		}
22931 ashik.ali 376
 
22272 amit.gupta 377
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 378
		for (JsonValue j : result_json) {
23816 amit.gupta 379
			// logger.info("res " + j.asArray());
22272 amit.gupta 380
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 381
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 382
				innerObject.add(toDealObject(jsonObject.asObject()));
383
			}
22319 amit.gupta 384
			if (innerObject.size() > 0) {
22272 amit.gupta 385
				responseObject.add(innerObject);
386
			}
387
		}
23022 ashik.ali 388
		return responseSender.ok(responseObject);
22272 amit.gupta 389
	}
390
 
22319 amit.gupta 391
	private Object toDealObject(JsonObject jsonObject) {
392
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 393
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
394
		}
395
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
396
	}
22319 amit.gupta 397
 
398
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 399
	@ApiImplicitParams({
22319 amit.gupta 400
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 401
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 402
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 403
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 404
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 405
		String response = null;
22319 amit.gupta 406
		// TODO: move to properties
21356 kshitij.so 407
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 408
		RestClient rc = new RestClient();
21356 kshitij.so 409
		Map<String, String> params = new HashMap<>();
410
		params.put("category_id", category_id);
21358 kshitij.so 411
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 412
		try {
413
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
414
		} catch (HttpHostConnectException e) {
415
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
416
		}
23816 amit.gupta 417
 
22319 amit.gupta 418
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
419
		}.getType());
23022 ashik.ali 420
 
421
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 422
	}
22319 amit.gupta 423
 
424
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 425
	@ApiImplicitParams({
22319 amit.gupta 426
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 427
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 428
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
429
			throws ProfitMandiBusinessException {
21445 kshitij.so 430
		String response = null;
22319 amit.gupta 431
		// TODO: move to properties
432
		String uri = "getDealById/" + id;
433
		System.out.println("Unit deal " + uri);
23532 amit.gupta 434
		RestClient rc = new RestClient();
21445 kshitij.so 435
		Map<String, String> params = new HashMap<>();
436
		DealsResponse dealsResponse = null;
23532 amit.gupta 437
		try {
438
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
439
		} catch (HttpHostConnectException e) {
440
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
441
		}
23816 amit.gupta 442
 
21445 kshitij.so 443
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 444
		if (!result_json.isEmpty()) {
21445 kshitij.so 445
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 446
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 447
			while (iter.hasNext()) {
22952 amit.gupta 448
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 449
				if (ai.getAvailability() <= 0)
22952 amit.gupta 450
					iter.remove();
451
			}
21445 kshitij.so 452
		}
22952 amit.gupta 453
		return responseSender.ok(dealsResponse);
21445 kshitij.so 454
	}
23816 amit.gupta 455
 
24091 tejbeer 456
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
457
	@ApiImplicitParams({
458
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
459
	@ApiOperation(value = "Get unit deal object")
460
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
461
			throws ProfitMandiBusinessException {
462
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
463
		List<Integer> tagIds = Arrays.asList(4);
464
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
465
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
466
			String categoryId = "(3 OR 6)";
467
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
468
			RestClient rc = new RestClient();
469
			Map<String, String> params = new HashMap<>();
470
			List<String> mandatoryQ = new ArrayList<>();
471
			String catalogString = "catalog" + id;
472
 
24149 amit.gupta 473
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
474
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
475
 
24091 tejbeer 476
			params.put("q", StringUtils.join(mandatoryQ, " "));
477
			params.put("fl", "*, [child parentFilter=id:catalog*]");
478
			params.put("sort", "rank_i asc, create_s desc");
479
			params.put("wt", "json");
480
			String response = null;
481
			try {
26575 amit.gupta 482
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 483
			} catch (HttpHostConnectException e) {
484
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
485
			}
486
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
487
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26889 amit.gupta 488
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
24091 tejbeer 489
		} else {
490
			return responseSender.badRequest(
491
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
492
		}
493
		return responseSender.ok(dealResponse.get(0));
494
	}
495
 
22333 amit.gupta 496
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 497
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 498
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 499
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 500
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 501
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
502
				categoryId);
24163 amit.gupta 503
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 504
	}
25879 amit.gupta 505
 
25813 amit.gupta 506
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
507
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
508
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
509
		logger.info("userInfo [{}]", userInfo);
26889 amit.gupta 510
		List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
511
		return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
25813 amit.gupta 512
	}
23816 amit.gupta 513
 
25011 amit.gupta 514
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 515
		List<DBObject> subCategories = new ArrayList<>();
516
		RestClient rc = new RestClient();
517
		Map<String, String> params = new HashMap<>();
518
		params.put("q", "categoryId_i:6");
519
		params.put("group", "true");
520
		params.put("group.field", "subCategoryId_i");
521
		params.put("wt", "json");
25126 amit.gupta 522
		params.put("rows", "50");
25014 amit.gupta 523
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 524
		String response = null;
525
		try {
26575 amit.gupta 526
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 527
		} catch (HttpHostConnectException e) {
528
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
529
		}
530
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
531
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
532
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 533
		for (int i = 0; i < groups.length(); i++) {
534
			JSONObject groupObject = groups.getJSONObject(i);
535
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 536
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 537
			categoryIds.add(subCategoryId);
25010 amit.gupta 538
		}
25015 amit.gupta 539
 
25010 amit.gupta 540
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 541
		AtomicInteger i = new AtomicInteger(0);
542
		categories.forEach(x -> {
25011 amit.gupta 543
			DBObject dbObject = new BasicDBObject();
544
			dbObject.put("name", x.getLabel());
545
			dbObject.put("subCategoryId", x.getId());
546
			dbObject.put("rank", i.incrementAndGet());
547
			dbObject.put("categoryId", 6);
26441 tejbeer 548
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 549
			subCategories.add(dbObject);
25010 amit.gupta 550
		});
25015 amit.gupta 551
 
25011 amit.gupta 552
		return subCategories;
25015 amit.gupta 553
 
25010 amit.gupta 554
	}
555
 
22446 amit.gupta 556
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 557
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 558
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 559
	}
23816 amit.gupta 560
 
23793 tejbeer 561
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
562
	public ResponseEntity<?> getSubcategoriesToDisplay() {
563
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
564
	}
23816 amit.gupta 565
 
22406 amit.gupta 566
	@ApiImplicitParams({
23816 amit.gupta 567
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 568
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 569
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 570
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
571
		String uri = sb.append(skus).toString();
23532 amit.gupta 572
		RestClient rc = new RestClient();
573
		String response;
574
		try {
575
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 576
		} catch (HttpHostConnectException e) {
23532 amit.gupta 577
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
578
		}
22406 amit.gupta 579
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 580
		List<Object> responseObject = new ArrayList<>();
581
		for (JsonValue j : result_json) {
23816 amit.gupta 582
			// logger.info("res " + j.asArray());
22407 amit.gupta 583
			List<Object> innerObject = new ArrayList<>();
584
			for (JsonValue jsonObject : j.asArray()) {
585
				innerObject.add(toDealObject(jsonObject.asObject()));
586
			}
587
			if (innerObject.size() > 0) {
588
				responseObject.add(innerObject);
589
			}
590
		}
22408 amit.gupta 591
		return responseSender.ok(responseObject);
22401 amit.gupta 592
	}
21339 kshitij.so 593
 
26889 amit.gupta 594
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
24149 amit.gupta 595
			throws ProfitMandiBusinessException {
24091 tejbeer 596
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
597
		List<Integer> tagIds = Arrays.asList(4);
26924 amit.gupta 598
		List<Integer> itemIds = new ArrayList<>();
24091 tejbeer 599
		if (docs.length() > 0) {
600
			for (int i = 0; i < docs.length(); i++) {
601
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 602
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 603
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
604
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
605
						int itemId = childItem.getInt("itemId_i");
26924 amit.gupta 606
						itemIds.add(itemId);
26515 amit.gupta 607
					}
24091 tejbeer 608
				}
609
			}
26924 amit.gupta 610
			if (itemIds.size() == 0) {
26573 amit.gupta 611
				return dealResponse;
612
			}
24091 tejbeer 613
		}
26924 amit.gupta 614
 
615
		Map<Integer, AvailabilityModel> itemAvailabilityMap = inventoryService.getStoreAndOurStock(fofoId, itemIds);
616
 
24091 tejbeer 617
		for (int i = 0; i < docs.length(); i++) {
618
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
619
			JSONObject doc = docs.getJSONObject(i);
620
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
621
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
622
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
623
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 624
			try {
625
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 626
			} catch (Exception e) {
24117 amit.gupta 627
				ffdr.setFeature(null);
24149 amit.gupta 628
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 629
			}
24091 tejbeer 630
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
26589 amit.gupta 631
			if (doc.has("_childDocuments_")) {
26515 amit.gupta 632
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
633
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
634
					int itemId = childItem.getInt("itemId_i");
635
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
636
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
637
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
638
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
639
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
640
						}
24091 tejbeer 641
					} else {
26515 amit.gupta 642
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26924 amit.gupta 643
						AvailabilityModel currentAvailability = itemAvailabilityMap.get(itemId);
26889 amit.gupta 644
						fdi.setSellingPrice(sellingPrice);
645
						fdi.setActive(childItem.getBoolean("active_b"));
646
						fdi.setMrp(childItem.getDouble("mrp_f"));
26515 amit.gupta 647
						fdi.setMop((float) childItem.getDouble("mop_f"));
648
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
649
						fdi.setTagId(childItem.getInt("tagId_i"));
650
						fdi.setItem_id(itemId);
26696 amit.gupta 651
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
26846 tejbeer 652
						cashBack = cashBack == null ? 0 : cashBack;
26696 amit.gupta 653
						fdi.setCashback(cashBack);
26897 amit.gupta 654
						fdi.setMinBuyQuantity(1);
26889 amit.gupta 655
						if (hotDeal) {
26924 amit.gupta 656
							fdi.setAvailability(currentAvailability.getWarehouseAvailability());
26889 amit.gupta 657
						} else if (fofoId == 0) {
658
							// For accessories item availability should at be ordered for Rs.1000
659
							fdi.setAvailability(100);
660
							Item item = itemRepository.selectById(itemId);
661
							// In case its tampered glass moq should be 5
662
							if (item.getCategoryId() == 10020) {
663
								fdi.setMinBuyQuantity(5);
26515 amit.gupta 664
							}
665
						} else {
26924 amit.gupta 666
							fdi.setAvailability(currentAvailability.getMaxAvailability());
24091 tejbeer 667
						}
26515 amit.gupta 668
						fdi.setQuantityStep(1);
669
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
670
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 671
					}
672
				}
673
			}
674
			if (fofoAvailabilityInfoMap.values().size() > 0) {
675
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
676
				dealResponse.add(ffdr);
677
			}
678
		}
679
		return dealResponse;
680
 
681
	}
682
 
25968 amit.gupta 683
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
684
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 685
		Map<Integer, TagListing> itemTagListingMap = null;
686
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
687
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 688
 
25968 amit.gupta 689
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
690
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 691
 
25879 amit.gupta 692
		for (int i = 0; i < docs.length(); i++) {
693
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
694
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 695
 
25879 amit.gupta 696
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
697
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
698
				int itemId = childItem.getInt("itemId_i");
699
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 700
				if (tl == null) {
25968 amit.gupta 701
					continue;
702
				}
25879 amit.gupta 703
				if (hotDeal) {
704
					if (!tl.isHotDeals()) {
705
						continue;
706
					}
707
				}
708
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
709
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
710
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
711
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
712
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
713
					}
714
				} else {
715
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
716
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
717
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 718
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 719
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
720
					fdi.setTagId(childItem.getInt("tagId_i"));
721
					fdi.setItem_id(itemId);
722
					Item item = itemRepository.selectById(itemId);
723
					// In case its tampered glass moq should be 5
724
					if (item.getCategoryId() == 10020) {
725
						fdi.setMinBuyQuantity(10);
726
					} else {
727
						fdi.setMinBuyQuantity(1);
728
					}
26050 amit.gupta 729
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 730
					fdi.setQuantityStep(1);
731
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
732
					fofoAvailabilityInfoMap.put(itemId, fdi);
733
				}
734
			}
735
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 736
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 737
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
738
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
739
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
740
					ffdr.setTitle(doc.getString("title_s"));
741
					try {
742
						ffdr.setFeature(doc.getString("feature_s"));
743
					} catch (Exception e) {
744
						ffdr.setFeature(null);
745
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
746
					}
747
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
748
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
749
					dealResponse.add(ffdr);
750
				}
751
			}
752
		}
753
		return dealResponse;
25880 amit.gupta 754
 
25879 amit.gupta 755
	}
25967 amit.gupta 756
}