Subversion Repositories SmartDukaan

Rev

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