Subversion Repositories SmartDukaan

Rev

Rev 25879 | Rev 25882 | 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;
25880 amit.gupta 60
import com.spice.profitmandi.service.inventory.AvailabilityInfo;
61
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
62
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
25875 amit.gupta 63
import com.spice.profitmandi.service.inventory.ItemBucketService;
25879 amit.gupta 64
import com.spice.profitmandi.service.inventory.ItemQuantityPojo;
22287 amit.gupta 65
import com.spice.profitmandi.service.pricing.PricingService;
21356 kshitij.so 66
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 67
import com.spice.profitmandi.web.res.DealObjectResponse;
68
import com.spice.profitmandi.web.res.DealsResponse;
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)
25880 amit.gupta 186
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 187
			throws ProfitMandiBusinessException {
25880 amit.gupta 188
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25879 amit.gupta 189
		List<Integer> itemIds = iqPojo.stream().map(x -> x.getItemId()).collect(Collectors.toList());
190
 
191
		RestClient rc = new RestClient();
192
		Map<String, String> params = new HashMap<>();
193
		List<String> mandatoryQ = new ArrayList<>();
194
		mandatoryQ.add(String.format("+{!parent which=\"id:catalog*\"} itemId_i:(%s)", StringUtils.join(itemIds, " ")));
195
 
196
		params.put("q", StringUtils.join(mandatoryQ, " "));
197
		params.put("fl", "*, [child parentFilter=id:catalog*]");
198
 
199
		params.put("wt", "json");
200
		String response = null;
201
		try {
202
			response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
203
		} catch (HttpHostConnectException e) {
204
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
205
		}
206
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
207
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25880 amit.gupta 208
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, false);
25879 amit.gupta 209
		return responseSender.ok(dealResponse);
210
	}
211
 
23816 amit.gupta 212
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 213
		UserCart uc = userAccountRepository.getUserCart(userId);
214
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 215
		List<String> strTagIds = new ArrayList<>();
216
		for (Integer tagId : tagIds) {
217
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 218
		}
22287 amit.gupta 219
		return String.join(",", strTagIds);
22273 amit.gupta 220
	}
221
 
22319 amit.gupta 222
	@ApiImplicitParams({
223
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
224
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 225
	public ResponseEntity<?> getFofo(HttpServletRequest request,
226
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
22319 amit.gupta 227
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
23816 amit.gupta 228
			@RequestParam(value = "sort", required = false) String sort,
229
			@RequestParam(value = "brand", required = false) String brand,
25011 amit.gupta 230
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
24946 amit.gupta 231
			@RequestParam(value = "q", required = false) String queryTerm,
24091 tejbeer 232
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
22328 amit.gupta 233
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 234
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
23786 amit.gupta 235
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
25879 amit.gupta 236
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
25389 tejbeer 237
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
23816 amit.gupta 238
			RestClient rc = new RestClient();
22319 amit.gupta 239
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 240
			List<String> mandatoryQ = new ArrayList<>();
24974 amit.gupta 241
			if (queryTerm != null && !queryTerm.equals("null")) {
24975 amit.gupta 242
				mandatoryQ.add(String.format("+(%s)", queryTerm));
243
			} else {
244
				queryTerm = null;
24971 amit.gupta 245
			}
25015 amit.gupta 246
			if (subCategoryId != 0) {
24949 amit.gupta 247
				mandatoryQ
248
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
24875 amit.gupta 249
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
23814 amit.gupta 250
			} else if (hotDeal) {
23816 amit.gupta 251
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
252
						StringUtils.join(tagIds, " ")));
25015 amit.gupta 253
 
254
			} else if (StringUtils.isNotBlank(brand)) {
255
				mandatoryQ.add(
256
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
257
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
258
 
22347 amit.gupta 259
			} else {
23816 amit.gupta 260
				mandatoryQ.add(
261
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
22336 amit.gupta 262
			}
23816 amit.gupta 263
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 264
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24995 amit.gupta 265
			if (queryTerm == null) {
24975 amit.gupta 266
				params.put("sort", "create_s desc");
267
			}
22319 amit.gupta 268
			params.put("start", String.valueOf(offset));
269
			params.put("rows", String.valueOf(limit));
270
			params.put("wt", "json");
23532 amit.gupta 271
			String response = null;
272
			try {
23816 amit.gupta 273
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
23532 amit.gupta 274
			} catch (HttpHostConnectException e) {
275
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
276
			}
22319 amit.gupta 277
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
278
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 279
			dealResponse = getCatalogResponse(docs, hotDeal);
25561 amit.gupta 280
			if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
25010 amit.gupta 281
				dealResponse.stream()
25561 amit.gupta 282
						.filter(x -> Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()));
24168 amit.gupta 283
			}
22319 amit.gupta 284
		} else {
23816 amit.gupta 285
			return responseSender.badRequest(
286
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 287
		}
288
		return responseSender.ok(dealResponse);
289
	}
22273 amit.gupta 290
 
22319 amit.gupta 291
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 292
	@ApiImplicitParams({
22319 amit.gupta 293
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 294
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 295
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
296
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
297
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
298
			@RequestParam(value = "direction", required = false) String direction,
299
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
300
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 301
		String response = null;
22319 amit.gupta 302
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 303
 
22319 amit.gupta 304
		String uri = "/deals/" + userId;
23532 amit.gupta 305
		RestClient rc = new RestClient();
22272 amit.gupta 306
		Map<String, String> params = new HashMap<>();
307
		params.put("offset", offset);
308
		params.put("limit", limit);
309
		params.put("categoryId", categoryId);
310
		params.put("direction", direction);
311
		params.put("sort", sort);
312
		params.put("source", "online");
313
		params.put("filterData", filterData);
23816 amit.gupta 314
		/*
315
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
316
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
317
		 */
22272 amit.gupta 318
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 319
		try {
320
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
321
		} catch (HttpHostConnectException e) {
322
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
323
		}
22931 ashik.ali 324
 
22272 amit.gupta 325
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 326
		for (JsonValue j : result_json) {
23816 amit.gupta 327
			// logger.info("res " + j.asArray());
22272 amit.gupta 328
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 329
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 330
				innerObject.add(toDealObject(jsonObject.asObject()));
331
			}
22319 amit.gupta 332
			if (innerObject.size() > 0) {
22272 amit.gupta 333
				responseObject.add(innerObject);
334
			}
335
		}
23022 ashik.ali 336
		return responseSender.ok(responseObject);
22272 amit.gupta 337
	}
338
 
22319 amit.gupta 339
	private Object toDealObject(JsonObject jsonObject) {
340
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 341
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
342
		}
343
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
344
	}
22319 amit.gupta 345
 
346
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 347
	@ApiImplicitParams({
22319 amit.gupta 348
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 349
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 350
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 351
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 352
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 353
		String response = null;
22319 amit.gupta 354
		// TODO: move to properties
21356 kshitij.so 355
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 356
		RestClient rc = new RestClient();
21356 kshitij.so 357
		Map<String, String> params = new HashMap<>();
358
		params.put("category_id", category_id);
21358 kshitij.so 359
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 360
		try {
361
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
362
		} catch (HttpHostConnectException e) {
363
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
364
		}
23816 amit.gupta 365
 
22319 amit.gupta 366
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
367
		}.getType());
23022 ashik.ali 368
 
369
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 370
	}
22319 amit.gupta 371
 
372
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 373
	@ApiImplicitParams({
22319 amit.gupta 374
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 375
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 376
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
377
			throws ProfitMandiBusinessException {
21445 kshitij.so 378
		String response = null;
22319 amit.gupta 379
		// TODO: move to properties
380
		String uri = "getDealById/" + id;
381
		System.out.println("Unit deal " + uri);
23532 amit.gupta 382
		RestClient rc = new RestClient();
21445 kshitij.so 383
		Map<String, String> params = new HashMap<>();
384
		DealsResponse dealsResponse = null;
23532 amit.gupta 385
		try {
386
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
387
		} catch (HttpHostConnectException e) {
388
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
389
		}
23816 amit.gupta 390
 
21445 kshitij.so 391
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 392
		if (!result_json.isEmpty()) {
21445 kshitij.so 393
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 394
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 395
			while (iter.hasNext()) {
22952 amit.gupta 396
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 397
				if (ai.getAvailability() <= 0)
22952 amit.gupta 398
					iter.remove();
399
			}
21445 kshitij.so 400
		}
22952 amit.gupta 401
		return responseSender.ok(dealsResponse);
21445 kshitij.so 402
	}
23816 amit.gupta 403
 
24091 tejbeer 404
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
405
	@ApiImplicitParams({
406
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
407
	@ApiOperation(value = "Get unit deal object")
408
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
409
			throws ProfitMandiBusinessException {
410
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
411
		List<Integer> tagIds = Arrays.asList(4);
412
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
413
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
414
			String categoryId = "(3 OR 6)";
415
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
416
			RestClient rc = new RestClient();
417
			Map<String, String> params = new HashMap<>();
418
			List<String> mandatoryQ = new ArrayList<>();
419
			String catalogString = "catalog" + id;
420
 
24149 amit.gupta 421
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
422
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
423
 
24091 tejbeer 424
			params.put("q", StringUtils.join(mandatoryQ, " "));
425
			params.put("fl", "*, [child parentFilter=id:catalog*]");
426
			params.put("sort", "rank_i asc, create_s desc");
427
			params.put("wt", "json");
428
			String response = null;
429
			try {
430
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
431
			} catch (HttpHostConnectException e) {
432
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
433
			}
434
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
435
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 436
			dealResponse = getCatalogResponse(docs, false);
24091 tejbeer 437
		} else {
438
			return responseSender.badRequest(
439
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
440
		}
441
		return responseSender.ok(dealResponse.get(0));
442
	}
443
 
22333 amit.gupta 444
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 445
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 446
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 447
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 448
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 449
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
450
				categoryId);
24163 amit.gupta 451
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 452
	}
25879 amit.gupta 453
 
25813 amit.gupta 454
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
455
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
456
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
457
		logger.info("userInfo [{}]", userInfo);
458
		List<DBObject> subCateogriesDisplay = this.getSubCategoriesToDisplay();
459
		return new ResponseEntity<>(subCateogriesDisplay, HttpStatus.OK);
460
	}
23816 amit.gupta 461
 
25011 amit.gupta 462
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 463
		List<DBObject> subCategories = new ArrayList<>();
464
		RestClient rc = new RestClient();
465
		Map<String, String> params = new HashMap<>();
466
		params.put("q", "categoryId_i:6");
467
		params.put("group", "true");
468
		params.put("group.field", "subCategoryId_i");
469
		params.put("wt", "json");
25126 amit.gupta 470
		params.put("rows", "50");
25014 amit.gupta 471
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 472
		String response = null;
473
		try {
474
			response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
475
		} catch (HttpHostConnectException e) {
476
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
477
		}
478
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
479
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
480
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 481
		for (int i = 0; i < groups.length(); i++) {
482
			JSONObject groupObject = groups.getJSONObject(i);
483
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 484
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 485
			categoryIds.add(subCategoryId);
25010 amit.gupta 486
		}
25015 amit.gupta 487
 
25010 amit.gupta 488
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 489
		AtomicInteger i = new AtomicInteger(0);
490
		categories.forEach(x -> {
25011 amit.gupta 491
			DBObject dbObject = new BasicDBObject();
492
			dbObject.put("name", x.getLabel());
493
			dbObject.put("subCategoryId", x.getId());
494
			dbObject.put("rank", i.incrementAndGet());
495
			dbObject.put("categoryId", 6);
496
			dbObject.put("url", "http://api.profittill.com/uploads/campaigns/" + x.getId() + ".png");
497
			subCategories.add(dbObject);
25010 amit.gupta 498
		});
25015 amit.gupta 499
 
25011 amit.gupta 500
		return subCategories;
25015 amit.gupta 501
 
25010 amit.gupta 502
	}
503
 
22446 amit.gupta 504
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 505
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 506
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 507
	}
23816 amit.gupta 508
 
23793 tejbeer 509
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
510
	public ResponseEntity<?> getSubcategoriesToDisplay() {
511
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
512
	}
23816 amit.gupta 513
 
22406 amit.gupta 514
	@ApiImplicitParams({
23816 amit.gupta 515
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 516
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 517
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 518
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
519
		String uri = sb.append(skus).toString();
23532 amit.gupta 520
		RestClient rc = new RestClient();
521
		String response;
522
		try {
523
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 524
		} catch (HttpHostConnectException e) {
23532 amit.gupta 525
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
526
		}
22406 amit.gupta 527
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 528
		List<Object> responseObject = new ArrayList<>();
529
		for (JsonValue j : result_json) {
23816 amit.gupta 530
			// logger.info("res " + j.asArray());
22407 amit.gupta 531
			List<Object> innerObject = new ArrayList<>();
532
			for (JsonValue jsonObject : j.asArray()) {
533
				innerObject.add(toDealObject(jsonObject.asObject()));
534
			}
535
			if (innerObject.size() > 0) {
536
				responseObject.add(innerObject);
537
			}
538
		}
22408 amit.gupta 539
		return responseSender.ok(responseObject);
22401 amit.gupta 540
	}
21339 kshitij.so 541
 
24149 amit.gupta 542
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
543
			throws ProfitMandiBusinessException {
24091 tejbeer 544
		Map<Integer, TagListing> itemTagListingMap = null;
545
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
546
		List<Integer> tagIds = Arrays.asList(4);
547
		if (docs.length() > 0) {
548
			HashSet<Integer> itemsSet = new HashSet<>();
549
			for (int i = 0; i < docs.length(); i++) {
550
				JSONObject doc = docs.getJSONObject(i);
551
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
552
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
553
					int itemId = childItem.getInt("itemId_i");
554
					itemsSet.add(itemId);
555
				}
556
			}
557
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
558
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
559
		}
560
 
561
		for (int i = 0; i < docs.length(); i++) {
562
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
563
			JSONObject doc = docs.getJSONObject(i);
564
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
565
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
566
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
567
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 568
			try {
569
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 570
			} catch (Exception e) {
24117 amit.gupta 571
				ffdr.setFeature(null);
24149 amit.gupta 572
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 573
			}
24091 tejbeer 574
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
575
 
576
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
577
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
578
				int itemId = childItem.getInt("itemId_i");
579
				TagListing tl = itemTagListingMap.get(itemId);
580
				if (hotDeal) {
581
					if (!tl.isHotDeals()) {
582
						continue;
583
					}
584
				}
585
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
586
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
587
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
588
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
589
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
590
					}
591
				} else {
592
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
593
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
594
					fdi.setMop((float) childItem.getDouble("mop_f"));
595
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
596
					fdi.setTagId(childItem.getInt("tagId_i"));
597
					fdi.setItem_id(itemId);
598
					Item item = itemRepository.selectById(itemId);
599
					// In case its tampered glass moq should be 5
600
					if (item.getCategoryId() == 10020) {
601
						fdi.setMinBuyQuantity(10);
602
					} else {
603
						fdi.setMinBuyQuantity(1);
604
					}
605
					if (hotDeal || !tl.isActive()) {
606
 
607
						int totalAvailability = 0; // Using item availability
608
													// cache for now but can be
609
													// changed to
610
													// use caching later.
611
						try {
612
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
613
							totalAvailability = iac.getTotalAvailability();
614
							fdi.setAvailability(totalAvailability);
615
						} catch (Exception e) {
616
							continue;
617
						}
618
						if (totalAvailability <= 0) {
619
							continue;
620
						}
621
					} else {
24149 amit.gupta 622
						// For accessories item availability should at be ordered for Rs.1000
25276 amit.gupta 623
						fdi.setAvailability(100);
24091 tejbeer 624
					}
625
					fdi.setQuantityStep(1);
626
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
627
					fofoAvailabilityInfoMap.put(itemId, fdi);
628
				}
629
			}
630
			if (fofoAvailabilityInfoMap.values().size() > 0) {
631
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
632
				dealResponse.add(ffdr);
633
			}
634
		}
635
		return dealResponse;
636
 
637
	}
638
 
25879 amit.gupta 639
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, boolean hotDeal)
640
			throws ProfitMandiBusinessException {
641
		Map<Integer, TagListing> itemTagListingMap = null;
642
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
643
		List<Integer> tagIds = Arrays.asList(4);
644
		if (docs.length() > 0) {
645
			HashSet<Integer> itemsSet = new HashSet<>();
646
			for (int i = 0; i < docs.length(); i++) {
647
				JSONObject doc = docs.getJSONObject(i);
648
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
649
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
650
					int itemId = childItem.getInt("itemId_i");
651
					itemsSet.add(itemId);
652
				}
653
			}
654
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
655
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
656
		}
25880 amit.gupta 657
 
25879 amit.gupta 658
		for (int i = 0; i < docs.length(); i++) {
659
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
660
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 661
 
25879 amit.gupta 662
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
663
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
664
				int itemId = childItem.getInt("itemId_i");
665
				TagListing tl = itemTagListingMap.get(itemId);
666
				if (hotDeal) {
667
					if (!tl.isHotDeals()) {
668
						continue;
669
					}
670
				}
671
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
672
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
673
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
674
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
675
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
676
					}
677
				} else {
678
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
679
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
680
					fdi.setMop((float) childItem.getDouble("mop_f"));
681
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
682
					fdi.setTagId(childItem.getInt("tagId_i"));
683
					fdi.setItem_id(itemId);
684
					Item item = itemRepository.selectById(itemId);
685
					// In case its tampered glass moq should be 5
686
					if (item.getCategoryId() == 10020) {
687
						fdi.setMinBuyQuantity(10);
688
					} else {
689
						fdi.setMinBuyQuantity(1);
690
					}
691
					if (hotDeal || !tl.isActive()) {
25880 amit.gupta 692
 
25879 amit.gupta 693
						int totalAvailability = 0; // Using item availability
694
						// cache for now but can be
695
						// changed to
696
						// use caching later.
697
						try {
698
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
699
							totalAvailability = iac.getTotalAvailability();
700
							fdi.setAvailability(totalAvailability);
701
						} catch (Exception e) {
702
							continue;
703
						}
704
						if (totalAvailability <= 0) {
705
							continue;
706
						}
707
					} else {
708
						// For accessories item availability should at be ordered for Rs.1000
709
						fdi.setAvailability(100);
710
					}
711
					fdi.setQuantityStep(1);
712
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
713
					fofoAvailabilityInfoMap.put(itemId, fdi);
714
				}
715
			}
716
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 717
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 718
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
719
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
720
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
721
					ffdr.setTitle(doc.getString("title_s"));
722
					try {
723
						ffdr.setFeature(doc.getString("feature_s"));
724
					} catch (Exception e) {
725
						ffdr.setFeature(null);
726
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
727
					}
728
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
729
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
730
					dealResponse.add(ffdr);
731
				}
732
			}
733
		}
734
		return dealResponse;
25880 amit.gupta 735
 
25879 amit.gupta 736
	}
737
 
21339 kshitij.so 738
}