Subversion Repositories SmartDukaan

Rev

Rev 27020 | Rev 27030 | 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
		}
26889 amit.gupta 288
		if (hotDeal) {
289
			childFilter.add("hot_deal_b:true");
290
		} else {
291
			childFilter.add("active_b:true");
292
		}
293
		if (subCategoryId != 0) {
294
			parentFilter.add("subCategoryId_i:" + subCategoryId);
295
		}
296
		if (StringUtils.isNotBlank(brand)) {
297
			parentFilter.add("brand_ss:" + brand);
298
		}
27017 amit.gupta 299
		if (queryTerm == "") {
300
			params.put("sort", "create_s desc");
301
		} else {
27020 amit.gupta 302
			parentFilter.addAll(Arrays.asList(queryTerm.split(" ")));
27017 amit.gupta 303
		}
26889 amit.gupta 304
		String parentFilterString = "\"" + String.join(" AND ", parentFilter) + "\"";
305
		String childFilterString = String.join(" AND ", childFilter);
306
		logger.info(parentFilterString);
27017 amit.gupta 307
		params.put("q", String.format("{!parent which=%s}%s", parentFilterString, childFilterString));
26897 amit.gupta 308
		params.put("fl",
27019 amit.gupta 309
				String.format("*, [child parentFilter=id:catalog* childFilter=%s]", "\"" + childFilterString + "\""));
26889 amit.gupta 310
		params.put("start", String.valueOf(offset));
311
		params.put("rows", String.valueOf(limit));
312
		params.put("wt", "json");
313
		String response = null;
314
		try {
315
			response = restClient.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
316
		} catch (HttpHostConnectException e) {
317
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
318
		}
319
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
320
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
321
		return docs;
26589 amit.gupta 322
	}
323
 
324
	@ApiImplicitParams({
325
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
326
	@RequestMapping(value = "/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
327
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
26758 amit.gupta 328
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
26589 amit.gupta 329
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
330
			@RequestParam(value = "sort", required = false) String sort,
331
			@RequestParam(value = "brand", required = false) String brand,
332
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
333
			@RequestParam(value = "q", required = false) String queryTerm,
334
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
335
			throws Throwable {
336
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
337
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
338
		UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
26889 amit.gupta 339
		dealResponse = this.getCatalogResponse(this.getSolrDocs(uc.getUserId(), queryTerm, categoryId, offset, limit,
340
				sort, brand, subCategoryId, false), false, userInfo.getRetailerId());
22319 amit.gupta 341
		return responseSender.ok(dealResponse);
342
	}
22273 amit.gupta 343
 
22319 amit.gupta 344
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 345
	@ApiImplicitParams({
22319 amit.gupta 346
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 347
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 348
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
349
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
350
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
351
			@RequestParam(value = "direction", required = false) String direction,
352
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
353
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 354
		String response = null;
22319 amit.gupta 355
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 356
 
22319 amit.gupta 357
		String uri = "/deals/" + userId;
23532 amit.gupta 358
		RestClient rc = new RestClient();
22272 amit.gupta 359
		Map<String, String> params = new HashMap<>();
360
		params.put("offset", offset);
361
		params.put("limit", limit);
362
		params.put("categoryId", categoryId);
363
		params.put("direction", direction);
364
		params.put("sort", sort);
365
		params.put("source", "online");
366
		params.put("filterData", filterData);
23816 amit.gupta 367
		/*
368
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
369
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
370
		 */
22272 amit.gupta 371
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 372
		try {
373
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
374
		} catch (HttpHostConnectException e) {
375
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
376
		}
22931 ashik.ali 377
 
22272 amit.gupta 378
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 379
		for (JsonValue j : result_json) {
23816 amit.gupta 380
			// logger.info("res " + j.asArray());
22272 amit.gupta 381
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 382
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 383
				innerObject.add(toDealObject(jsonObject.asObject()));
384
			}
22319 amit.gupta 385
			if (innerObject.size() > 0) {
22272 amit.gupta 386
				responseObject.add(innerObject);
387
			}
388
		}
23022 ashik.ali 389
		return responseSender.ok(responseObject);
22272 amit.gupta 390
	}
391
 
22319 amit.gupta 392
	private Object toDealObject(JsonObject jsonObject) {
393
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 394
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
395
		}
396
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
397
	}
22319 amit.gupta 398
 
399
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 400
	@ApiImplicitParams({
22319 amit.gupta 401
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 402
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 403
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 404
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 405
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 406
		String response = null;
22319 amit.gupta 407
		// TODO: move to properties
21356 kshitij.so 408
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 409
		RestClient rc = new RestClient();
21356 kshitij.so 410
		Map<String, String> params = new HashMap<>();
411
		params.put("category_id", category_id);
21358 kshitij.so 412
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 413
		try {
414
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
415
		} catch (HttpHostConnectException e) {
416
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
417
		}
23816 amit.gupta 418
 
22319 amit.gupta 419
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
420
		}.getType());
23022 ashik.ali 421
 
422
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 423
	}
22319 amit.gupta 424
 
425
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 426
	@ApiImplicitParams({
22319 amit.gupta 427
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 428
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 429
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
430
			throws ProfitMandiBusinessException {
21445 kshitij.so 431
		String response = null;
22319 amit.gupta 432
		// TODO: move to properties
433
		String uri = "getDealById/" + id;
434
		System.out.println("Unit deal " + uri);
23532 amit.gupta 435
		RestClient rc = new RestClient();
21445 kshitij.so 436
		Map<String, String> params = new HashMap<>();
437
		DealsResponse dealsResponse = null;
23532 amit.gupta 438
		try {
439
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
440
		} catch (HttpHostConnectException e) {
441
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
442
		}
23816 amit.gupta 443
 
21445 kshitij.so 444
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 445
		if (!result_json.isEmpty()) {
21445 kshitij.so 446
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 447
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 448
			while (iter.hasNext()) {
22952 amit.gupta 449
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 450
				if (ai.getAvailability() <= 0)
22952 amit.gupta 451
					iter.remove();
452
			}
21445 kshitij.so 453
		}
22952 amit.gupta 454
		return responseSender.ok(dealsResponse);
21445 kshitij.so 455
	}
23816 amit.gupta 456
 
24091 tejbeer 457
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
458
	@ApiImplicitParams({
459
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
460
	@ApiOperation(value = "Get unit deal object")
461
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
462
			throws ProfitMandiBusinessException {
463
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
464
		List<Integer> tagIds = Arrays.asList(4);
465
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
466
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
467
			String categoryId = "(3 OR 6)";
468
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
469
			RestClient rc = new RestClient();
470
			Map<String, String> params = new HashMap<>();
471
			List<String> mandatoryQ = new ArrayList<>();
472
			String catalogString = "catalog" + id;
473
 
24149 amit.gupta 474
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
475
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
476
 
24091 tejbeer 477
			params.put("q", StringUtils.join(mandatoryQ, " "));
478
			params.put("fl", "*, [child parentFilter=id:catalog*]");
479
			params.put("sort", "rank_i asc, create_s desc");
480
			params.put("wt", "json");
481
			String response = null;
482
			try {
26575 amit.gupta 483
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 484
			} catch (HttpHostConnectException e) {
485
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
486
			}
487
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
488
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26889 amit.gupta 489
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
24091 tejbeer 490
		} else {
491
			return responseSender.badRequest(
492
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
493
		}
494
		return responseSender.ok(dealResponse.get(0));
495
	}
496
 
22333 amit.gupta 497
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 498
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 499
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 500
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 501
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 502
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
503
				categoryId);
24163 amit.gupta 504
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 505
	}
25879 amit.gupta 506
 
25813 amit.gupta 507
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
508
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
509
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
510
		logger.info("userInfo [{}]", userInfo);
26889 amit.gupta 511
		List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
512
		return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
25813 amit.gupta 513
	}
23816 amit.gupta 514
 
25011 amit.gupta 515
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 516
		List<DBObject> subCategories = new ArrayList<>();
517
		RestClient rc = new RestClient();
518
		Map<String, String> params = new HashMap<>();
519
		params.put("q", "categoryId_i:6");
520
		params.put("group", "true");
521
		params.put("group.field", "subCategoryId_i");
522
		params.put("wt", "json");
25126 amit.gupta 523
		params.put("rows", "50");
25014 amit.gupta 524
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 525
		String response = null;
526
		try {
26575 amit.gupta 527
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 528
		} catch (HttpHostConnectException e) {
529
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
530
		}
531
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
532
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
533
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 534
		for (int i = 0; i < groups.length(); i++) {
535
			JSONObject groupObject = groups.getJSONObject(i);
536
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 537
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 538
			categoryIds.add(subCategoryId);
25010 amit.gupta 539
		}
25015 amit.gupta 540
 
25010 amit.gupta 541
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 542
		AtomicInteger i = new AtomicInteger(0);
543
		categories.forEach(x -> {
25011 amit.gupta 544
			DBObject dbObject = new BasicDBObject();
545
			dbObject.put("name", x.getLabel());
546
			dbObject.put("subCategoryId", x.getId());
547
			dbObject.put("rank", i.incrementAndGet());
548
			dbObject.put("categoryId", 6);
26441 tejbeer 549
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 550
			subCategories.add(dbObject);
25010 amit.gupta 551
		});
25015 amit.gupta 552
 
25011 amit.gupta 553
		return subCategories;
25015 amit.gupta 554
 
25010 amit.gupta 555
	}
556
 
22446 amit.gupta 557
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 558
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 559
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 560
	}
23816 amit.gupta 561
 
23793 tejbeer 562
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
563
	public ResponseEntity<?> getSubcategoriesToDisplay() {
564
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
565
	}
23816 amit.gupta 566
 
22406 amit.gupta 567
	@ApiImplicitParams({
23816 amit.gupta 568
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 569
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 570
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 571
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
572
		String uri = sb.append(skus).toString();
23532 amit.gupta 573
		RestClient rc = new RestClient();
574
		String response;
575
		try {
576
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 577
		} catch (HttpHostConnectException e) {
23532 amit.gupta 578
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
579
		}
22406 amit.gupta 580
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 581
		List<Object> responseObject = new ArrayList<>();
582
		for (JsonValue j : result_json) {
23816 amit.gupta 583
			// logger.info("res " + j.asArray());
22407 amit.gupta 584
			List<Object> innerObject = new ArrayList<>();
585
			for (JsonValue jsonObject : j.asArray()) {
586
				innerObject.add(toDealObject(jsonObject.asObject()));
587
			}
588
			if (innerObject.size() > 0) {
589
				responseObject.add(innerObject);
590
			}
591
		}
22408 amit.gupta 592
		return responseSender.ok(responseObject);
22401 amit.gupta 593
	}
21339 kshitij.so 594
 
26889 amit.gupta 595
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
24149 amit.gupta 596
			throws ProfitMandiBusinessException {
24091 tejbeer 597
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
598
		List<Integer> tagIds = Arrays.asList(4);
26924 amit.gupta 599
		List<Integer> itemIds = new ArrayList<>();
24091 tejbeer 600
		if (docs.length() > 0) {
601
			for (int i = 0; i < docs.length(); i++) {
602
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 603
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 604
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
605
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
606
						int itemId = childItem.getInt("itemId_i");
26924 amit.gupta 607
						itemIds.add(itemId);
26515 amit.gupta 608
					}
24091 tejbeer 609
				}
610
			}
26924 amit.gupta 611
			if (itemIds.size() == 0) {
26573 amit.gupta 612
				return dealResponse;
613
			}
24091 tejbeer 614
		}
26924 amit.gupta 615
 
616
		Map<Integer, AvailabilityModel> itemAvailabilityMap = inventoryService.getStoreAndOurStock(fofoId, itemIds);
617
 
24091 tejbeer 618
		for (int i = 0; i < docs.length(); i++) {
619
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
620
			JSONObject doc = docs.getJSONObject(i);
621
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
622
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
623
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
624
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 625
			try {
626
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 627
			} catch (Exception e) {
24117 amit.gupta 628
				ffdr.setFeature(null);
24149 amit.gupta 629
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 630
			}
24091 tejbeer 631
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
26589 amit.gupta 632
			if (doc.has("_childDocuments_")) {
26515 amit.gupta 633
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
634
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
635
					int itemId = childItem.getInt("itemId_i");
636
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
637
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
638
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
639
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
640
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
641
						}
24091 tejbeer 642
					} else {
26515 amit.gupta 643
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26924 amit.gupta 644
						AvailabilityModel currentAvailability = itemAvailabilityMap.get(itemId);
26889 amit.gupta 645
						fdi.setSellingPrice(sellingPrice);
646
						fdi.setActive(childItem.getBoolean("active_b"));
647
						fdi.setMrp(childItem.getDouble("mrp_f"));
26515 amit.gupta 648
						fdi.setMop((float) childItem.getDouble("mop_f"));
649
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
650
						fdi.setTagId(childItem.getInt("tagId_i"));
651
						fdi.setItem_id(itemId);
26696 amit.gupta 652
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
26846 tejbeer 653
						cashBack = cashBack == null ? 0 : cashBack;
26696 amit.gupta 654
						fdi.setCashback(cashBack);
26897 amit.gupta 655
						fdi.setMinBuyQuantity(1);
26889 amit.gupta 656
						if (hotDeal) {
26924 amit.gupta 657
							fdi.setAvailability(currentAvailability.getWarehouseAvailability());
26889 amit.gupta 658
						} else if (fofoId == 0) {
659
							// For accessories item availability should at be ordered for Rs.1000
660
							fdi.setAvailability(100);
661
							Item item = itemRepository.selectById(itemId);
662
							// In case its tampered glass moq should be 5
663
							if (item.getCategoryId() == 10020) {
664
								fdi.setMinBuyQuantity(5);
26515 amit.gupta 665
							}
666
						} else {
26924 amit.gupta 667
							fdi.setAvailability(currentAvailability.getMaxAvailability());
24091 tejbeer 668
						}
26515 amit.gupta 669
						fdi.setQuantityStep(1);
670
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
671
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 672
					}
673
				}
674
			}
675
			if (fofoAvailabilityInfoMap.values().size() > 0) {
27005 amit.gupta 676
				List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values()
27006 amit.gupta 677
				.stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
27005 amit.gupta 678
				ffdr.setItems(availabilityList);
24091 tejbeer 679
				dealResponse.add(ffdr);
680
			}
681
		}
682
		return dealResponse;
683
 
684
	}
685
 
25968 amit.gupta 686
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
687
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 688
		Map<Integer, TagListing> itemTagListingMap = null;
689
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
690
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 691
 
25968 amit.gupta 692
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
693
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 694
 
25879 amit.gupta 695
		for (int i = 0; i < docs.length(); i++) {
696
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
697
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 698
 
25879 amit.gupta 699
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
700
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
701
				int itemId = childItem.getInt("itemId_i");
702
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 703
				if (tl == null) {
25968 amit.gupta 704
					continue;
705
				}
25879 amit.gupta 706
				if (hotDeal) {
707
					if (!tl.isHotDeals()) {
708
						continue;
709
					}
710
				}
711
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
712
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
713
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
714
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
715
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
716
					}
717
				} else {
718
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
719
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
720
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 721
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 722
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
723
					fdi.setTagId(childItem.getInt("tagId_i"));
724
					fdi.setItem_id(itemId);
725
					Item item = itemRepository.selectById(itemId);
726
					// In case its tampered glass moq should be 5
727
					if (item.getCategoryId() == 10020) {
728
						fdi.setMinBuyQuantity(10);
729
					} else {
730
						fdi.setMinBuyQuantity(1);
731
					}
26050 amit.gupta 732
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 733
					fdi.setQuantityStep(1);
734
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
735
					fofoAvailabilityInfoMap.put(itemId, fdi);
736
				}
737
			}
738
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 739
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 740
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
741
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
742
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
743
					ffdr.setTitle(doc.getString("title_s"));
744
					try {
745
						ffdr.setFeature(doc.getString("feature_s"));
746
					} catch (Exception e) {
747
						ffdr.setFeature(null);
748
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
749
					}
750
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
751
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
752
					dealResponse.add(ffdr);
753
				}
754
			}
755
		}
756
		return dealResponse;
25880 amit.gupta 757
 
25879 amit.gupta 758
	}
25967 amit.gupta 759
}