Subversion Repositories SmartDukaan

Rev

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