Subversion Repositories SmartDukaan

Rev

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