Subversion Repositories SmartDukaan

Rev

Rev 22348 | Rev 22361 | 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.time.LocalDateTime;
4
import java.util.ArrayList;
22336 amit.gupta 5
import java.util.Arrays;
21339 kshitij.so 6
import java.util.HashMap;
7
import java.util.List;
8
import java.util.Map;
9
 
10
import javax.servlet.http.HttpServletRequest;
11
 
22319 amit.gupta 12
import org.apache.commons.lang3.StringUtils;
13
import org.json.JSONArray;
14
import org.json.JSONObject;
21339 kshitij.so 15
import org.slf4j.Logger;
16
import org.slf4j.LoggerFactory;
22273 amit.gupta 17
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 18
import org.springframework.beans.factory.annotation.Value;
19
import org.springframework.http.HttpStatus;
20
import org.springframework.http.MediaType;
21
import org.springframework.http.ResponseEntity;
22
import org.springframework.stereotype.Controller;
22286 amit.gupta 23
import org.springframework.transaction.annotation.Transactional;
21339 kshitij.so 24
import org.springframework.web.bind.annotation.PathVariable;
25
import org.springframework.web.bind.annotation.RequestMapping;
26
import org.springframework.web.bind.annotation.RequestMethod;
27
import org.springframework.web.bind.annotation.RequestParam;
28
 
29
import com.eclipsesource.json.Json;
30
import com.eclipsesource.json.JsonArray;
31
import com.eclipsesource.json.JsonObject;
32
import com.eclipsesource.json.JsonValue;
33
import com.google.gson.Gson;
21356 kshitij.so 34
import com.google.gson.reflect.TypeToken;
21643 ashik.ali 35
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 36
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
37
import com.spice.profitmandi.common.model.ProfitMandiConstants;
21740 ashik.ali 38
import com.spice.profitmandi.common.model.ProfitMandiResponse;
39
import com.spice.profitmandi.common.model.ResponseStatus;
22289 amit.gupta 40
import com.spice.profitmandi.common.model.UserInfo;
21643 ashik.ali 41
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 42
import com.spice.profitmandi.common.web.util.ResponseSender;
22289 amit.gupta 43
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
22333 amit.gupta 44
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22287 amit.gupta 45
import com.spice.profitmandi.service.pricing.PricingService;
21356 kshitij.so 46
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 47
import com.spice.profitmandi.web.res.DealObjectResponse;
48
import com.spice.profitmandi.web.res.DealsResponse;
22328 amit.gupta 49
import com.spice.profitmandi.web.res.FofoAvailabilityInfo;
50
import com.spice.profitmandi.web.res.FofoCatalogResponse;
21339 kshitij.so 51
 
52
import io.swagger.annotations.ApiImplicitParam;
53
import io.swagger.annotations.ApiImplicitParams;
54
import io.swagger.annotations.ApiOperation;
55
 
56
@Controller
22319 amit.gupta 57
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 58
public class DealsController {
59
 
22319 amit.gupta 60
	private static final Logger logger = LoggerFactory.getLogger(DealsController.class);
21339 kshitij.so 61
 
62
	@Value("${python.api.host}")
63
	private String host;
64
	@Value("${python.api.port}")
65
	private int port;
22319 amit.gupta 66
 
67
	@Autowired
68
	private PricingService pricingService;
22273 amit.gupta 69
 
70
	@Autowired
22333 amit.gupta 71
	private Mongo mongoClient;
72
 
73
	@Autowired
22319 amit.gupta 74
	ResponseSender<?> responseSender;
22336 amit.gupta 75
 
76
	List<String> filterableParams = Arrays.asList("brand");
21339 kshitij.so 77
 
22319 amit.gupta 78
	@RequestMapping(value = ProfitMandiConstants.URL_DEALS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21339 kshitij.so 79
	@ApiImplicitParams({
22319 amit.gupta 80
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21339 kshitij.so 81
	@ApiOperation(value = "Get deals")
22319 amit.gupta 82
	public ResponseEntity<?> getDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String categoryId,
83
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
84
			@RequestParam(value = "sort", required = false) String sort,
85
			@RequestParam(value = "direction", required = false) String direction,
86
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
87
		logger.info("Request " + request.getParameterMap());
21339 kshitij.so 88
		String response = null;
22319 amit.gupta 89
		int userId = (int) request.getAttribute("userId");
90
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
91
		// TODO: move to properties
92
		String uri = "/deals/" + userId;
93
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
21339 kshitij.so 94
		Map<String, String> params = new HashMap<>();
95
		params.put("offset", offset);
96
		params.put("limit", limit);
97
		params.put("categoryId", categoryId);
98
		params.put("direction", direction);
99
		params.put("sort", sort);
100
		params.put("filterData", filterData);
22272 amit.gupta 101
		params.put("source", "deals");
22319 amit.gupta 102
		if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
22289 amit.gupta 103
			params.put("tag_ids", getCommaSeparateTags(userId));
104
		}
21356 kshitij.so 105
		List<Object> responseObject = new ArrayList<>();
21339 kshitij.so 106
		try {
107
			response = rc.get(uri, params);
108
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 109
			logger.error("Unable to get deals", e);
110
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
111
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
112
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, responseObject);
113
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
21339 kshitij.so 114
		}
115
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 116
		for (JsonValue j : result_json) {
117
			logger.info("res " + j.asArray());
21339 kshitij.so 118
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 119
			for (JsonValue jsonObject : j.asArray()) {
21356 kshitij.so 120
				innerObject.add(toDealObject(jsonObject.asObject()));
21339 kshitij.so 121
			}
22319 amit.gupta 122
			if (innerObject.size() > 0) {
21339 kshitij.so 123
				responseObject.add(innerObject);
124
			}
125
		}
22319 amit.gupta 126
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
127
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
128
				responseObject);
129
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
21339 kshitij.so 130
	}
131
 
22319 amit.gupta 132
	private String getCommaSeparateTags(int userId) throws Throwable {
22287 amit.gupta 133
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userId);
134
		List<String> strTagIds = new ArrayList<>();
135
		for (Integer tagId : tagIds) {
136
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 137
		}
22287 amit.gupta 138
		return String.join(",", strTagIds);
22273 amit.gupta 139
	}
140
 
22319 amit.gupta 141
	@ApiImplicitParams({
142
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
143
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
144
	public ResponseEntity<?> getFofo(HttpServletRequest request, @RequestParam(value = "categoryId") String categoryId,
145
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
22336 amit.gupta 146
			@RequestParam(value = "sort", required = false) String sort, @RequestParam(value = "brand", required = false) String brand) throws Throwable {
22328 amit.gupta 147
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 148
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
149
		if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
150
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getUserId());
151
			RestClient rc  = new RestClient(SchemeType.HTTP, "dtr", 8984);
152
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 153
			List<String> mandatoryQ = new ArrayList<>();
154
			if(brand != null) {
22347 amit.gupta 155
 
22348 amit.gupta 156
				mandatoryQ.add(String.format("+{!parent which=\"brand_s=%s\"} tagId_i:(%s)", brand, StringUtils.join(tagIds, " ")));
22347 amit.gupta 157
			} else {
158
				mandatoryQ.add(String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
22336 amit.gupta 159
			}
22340 amit.gupta 160
			params.put("q", StringUtils.join(mandatoryQ," "));
22319 amit.gupta 161
			params.put("fl", "*, [child parentFilter=id:catalog*]");
162
			params.put("sort", "rank_i asc");
163
			params.put("start", String.valueOf(offset));
164
			params.put("rows", String.valueOf(limit));
165
			params.put("wt", "json");
22330 amit.gupta 166
			logger.info(rc.getUrl());
22319 amit.gupta 167
			String response  =rc.get("solr/demo/select", params);
168
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
169
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
170
			for(int i=0; i < docs.length(); i++) {
22328 amit.gupta 171
				Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
22319 amit.gupta 172
				JSONObject doc = docs.getJSONObject(i);
22328 amit.gupta 173
				FofoCatalogResponse ffdr = new FofoCatalogResponse();
22319 amit.gupta 174
				ffdr.setCatalogId(doc.getInt("catalogId_i"));
175
				ffdr.setImageUrl(doc.getString("imageUrl_s"));
176
				ffdr.setTitle(doc.getString("title_s"));
22333 amit.gupta 177
				ffdr.setBrand(doc.getString("brand_s"));
22323 amit.gupta 178
				for(int j=0; j< doc.getJSONArray("_childDocuments_").length(); j++) {
179
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
22319 amit.gupta 180
					int itemId = childItem.getInt("itemId_i");
181
					float sellingPrice = (float)childItem.getDouble("sellingPrice_f");
22328 amit.gupta 182
					if(fofoAvailabilityInfoMap.containsKey(itemId)) {
183
						if(fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
184
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
185
							fofoAvailabilityInfoMap.get(itemId).setMop((float)childItem.getDouble("mop_f"));
22319 amit.gupta 186
						} 
187
					} else {
22328 amit.gupta 188
							FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
22319 amit.gupta 189
							fdi.setSellingPrice((float)childItem.getDouble("sellingPrice_f"));
190
							fdi.setMop((float)childItem.getDouble("mop_f"));
22324 amit.gupta 191
							fdi.setColor(childItem.has("color_s")?childItem.getString("color_s"): "");
22319 amit.gupta 192
							fdi.setTagId(childItem.getInt("tagId_i"));
22328 amit.gupta 193
							fdi.setItem_id(itemId);
194
							fdi.setAvailability(100);
195
							fdi.setQuantityStep(1);
196
							fdi.setMinBuyQuantity(1);
197
							fdi.setMaxQuantity(100);
198
							fofoAvailabilityInfoMap.put(itemId, fdi);
22319 amit.gupta 199
					}
200
				}
22328 amit.gupta 201
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
22319 amit.gupta 202
				dealResponse.add(ffdr);
203
			}
204
 
205
		} else {
206
			return responseSender.badRequest(new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
207
		}
208
		return responseSender.ok(dealResponse);
209
	}
22273 amit.gupta 210
 
22319 amit.gupta 211
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 212
	@ApiImplicitParams({
22319 amit.gupta 213
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 214
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 215
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
216
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
217
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
218
			@RequestParam(value = "direction", required = false) String direction,
219
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
220
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 221
		String response = null;
22319 amit.gupta 222
		int userId = (int) request.getAttribute("userId");
223
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
22289 amit.gupta 224
 
22319 amit.gupta 225
		String uri = "/deals/" + userId;
226
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
22272 amit.gupta 227
		Map<String, String> params = new HashMap<>();
228
		params.put("offset", offset);
229
		params.put("limit", limit);
230
		params.put("categoryId", categoryId);
231
		params.put("direction", direction);
232
		params.put("sort", sort);
233
		params.put("source", "online");
234
		params.put("filterData", filterData);
22357 amit.gupta 235
		/*if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
22289 amit.gupta 236
			params.put("tag_ids", getCommaSeparateTags(userId));
22357 amit.gupta 237
		}*/
22272 amit.gupta 238
		List<Object> responseObject = new ArrayList<>();
239
		try {
240
			response = rc.get(uri, params);
241
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 242
			logger.error("Unable to get deals", e);
243
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
244
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
245
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, responseObject);
246
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
22272 amit.gupta 247
		}
248
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 249
		for (JsonValue j : result_json) {
250
			logger.info("res " + j.asArray());
22272 amit.gupta 251
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 252
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 253
				innerObject.add(toDealObject(jsonObject.asObject()));
254
			}
22319 amit.gupta 255
			if (innerObject.size() > 0) {
22272 amit.gupta 256
				responseObject.add(innerObject);
257
			}
258
		}
22319 amit.gupta 259
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
260
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
261
				responseObject);
262
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
22272 amit.gupta 263
	}
264
 
22319 amit.gupta 265
	/*
266
	 * @RequestMapping(value = "/direct-deals",
267
	 * method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
268
	 * 
269
	 * @ApiImplicitParams({
270
	 * 
271
	 * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required =
272
	 * true, dataType = "string", paramType = "header") }) public
273
	 * ResponseEntity<?> getDirectDeals(HttpServletRequest
274
	 * request, @RequestParam(value="categoryId") String
275
	 * categoryId,@RequestParam(value="offset") String offset,
276
	 * 
277
	 * @RequestParam(value="limit") String limit, @RequestParam(value="sort",
278
	 * required=false) String sort, @RequestParam(value="direction",
279
	 * required=false) String direction,
280
	 * 
281
	 * @RequestParam(value="filterData", required=false) String filterData ){
282
	 * 
283
	 * return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK); }
284
	 */
285
 
286
	private Object toDealObject(JsonObject jsonObject) {
287
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 288
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
289
		}
290
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
291
	}
22319 amit.gupta 292
 
293
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 294
	@ApiImplicitParams({
22319 amit.gupta 295
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 296
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 297
	public ResponseEntity<?> getBrands(HttpServletRequest request,
298
			@RequestParam(value = "category_id") String category_id) {
299
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 300
		String response = null;
22319 amit.gupta 301
		// TODO: move to properties
21356 kshitij.so 302
		String uri = ProfitMandiConstants.URL_BRANDS;
22319 amit.gupta 303
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
21356 kshitij.so 304
		Map<String, String> params = new HashMap<>();
305
		params.put("category_id", category_id);
21358 kshitij.so 306
		List<DealBrands> dealBrandsResponse = null;
21356 kshitij.so 307
		try {
308
			response = rc.get(uri, params);
309
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 310
			logger.error("Unable to get deals", e);
311
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
312
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
313
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, dealBrandsResponse);
314
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
21356 kshitij.so 315
		}
22319 amit.gupta 316
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
317
		}.getType());
318
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
319
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
320
				dealBrandsResponse);
321
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
21356 kshitij.so 322
	}
22319 amit.gupta 323
 
324
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 325
	@ApiImplicitParams({
22319 amit.gupta 326
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 327
	@ApiOperation(value = "Get unit deal object")
22319 amit.gupta 328
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id) {
21445 kshitij.so 329
		String response = null;
22319 amit.gupta 330
		// TODO: move to properties
331
		String uri = "getDealById/" + id;
332
		System.out.println("Unit deal " + uri);
333
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
21445 kshitij.so 334
		Map<String, String> params = new HashMap<>();
335
		DealsResponse dealsResponse = null;
336
		try {
337
			response = rc.get(uri, params);
338
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 339
			logger.error("Unable to get deals", e);
340
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
341
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
342
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, dealsResponse);
343
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
21445 kshitij.so 344
		}
345
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 346
		if (!result_json.isEmpty()) {
21445 kshitij.so 347
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
348
		}
22319 amit.gupta 349
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
350
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
351
				dealsResponse);
352
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
21445 kshitij.so 353
	}
22333 amit.gupta 354
 
355
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
356
	public ResponseEntity<?> getBrandsToDisplay() {
357
		return new ResponseEntity<>(mongoClient.getBrandsToDisplay(), HttpStatus.OK);
358
	}
21339 kshitij.so 359
 
360
}