Subversion Repositories SmartDukaan

Rev

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