Subversion Repositories SmartDukaan

Rev

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