Subversion Repositories SmartDukaan

Rev

Rev 28392 | Rev 28394 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
26607 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
27025 tejbeer 3
import java.time.LocalDateTime;
26628 amit.gupta 4
import java.time.LocalTime;
27069 tejbeer 5
import java.time.format.DateTimeFormatter;
26607 amit.gupta 6
import java.util.ArrayList;
7
import java.util.Arrays;
28312 amit.gupta 8
import java.util.Comparator;
26607 amit.gupta 9
import java.util.HashMap;
10
import java.util.HashSet;
11
import java.util.List;
12
import java.util.Map;
26745 amit.gupta 13
import java.util.Optional;
26607 amit.gupta 14
import java.util.Set;
15
import java.util.stream.Collectors;
16
 
17
import javax.servlet.http.HttpServletRequest;
28334 amit.gupta 18
import javax.servlet.http.HttpServletResponse;
26607 amit.gupta 19
 
20
import org.apache.commons.lang3.StringUtils;
21
import org.apache.http.conn.HttpHostConnectException;
22
import org.apache.logging.log4j.LogManager;
23
import org.apache.logging.log4j.Logger;
24
import org.json.JSONArray;
25
import org.json.JSONObject;
26
import org.springframework.beans.factory.annotation.Autowired;
27
import org.springframework.beans.factory.annotation.Value;
26745 amit.gupta 28
import org.springframework.cache.annotation.Cacheable;
26607 amit.gupta 29
import org.springframework.http.MediaType;
30
import org.springframework.http.ResponseEntity;
31
import org.springframework.stereotype.Controller;
32
import org.springframework.transaction.annotation.Transactional;
26923 amit.gupta 33
import org.springframework.web.bind.annotation.GetMapping;
26662 amit.gupta 34
import org.springframework.web.bind.annotation.PathVariable;
26607 amit.gupta 35
import org.springframework.web.bind.annotation.RequestBody;
36
import org.springframework.web.bind.annotation.RequestMapping;
37
import org.springframework.web.bind.annotation.RequestMethod;
38
import org.springframework.web.bind.annotation.RequestParam;
28322 amit.gupta 39
import org.springframework.web.bind.annotation.ResponseBody;
26607 amit.gupta 40
 
41
import com.eclipsesource.json.JsonObject;
26774 amit.gupta 42
import com.fasterxml.jackson.annotation.JsonProperty;
26607 amit.gupta 43
import com.google.gson.Gson;
44
import com.google.gson.reflect.TypeToken;
28377 tejbeer 45
import com.spice.profitmandi.common.enumuration.MessageType;
26607 amit.gupta 46
import com.spice.profitmandi.common.enumuration.SchemeType;
47
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
26923 amit.gupta 48
import com.spice.profitmandi.common.model.CreatePendingOrderItem;
26648 amit.gupta 49
import com.spice.profitmandi.common.model.CreatePendingOrderRequest;
26651 amit.gupta 50
import com.spice.profitmandi.common.model.CustomRetailer;
26607 amit.gupta 51
import com.spice.profitmandi.common.model.ProfitMandiConstants;
28377 tejbeer 52
import com.spice.profitmandi.common.model.SendNotificationModel;
26607 amit.gupta 53
import com.spice.profitmandi.common.model.UserInfo;
54
import com.spice.profitmandi.common.solr.SolrService;
28304 amit.gupta 55
import com.spice.profitmandi.common.util.FormattingUtils;
26607 amit.gupta 56
import com.spice.profitmandi.common.web.client.RestClient;
57
import com.spice.profitmandi.common.web.util.ResponseSender;
58
import com.spice.profitmandi.dao.entity.catalog.Item;
59
import com.spice.profitmandi.dao.entity.catalog.TagListing;
28377 tejbeer 60
import com.spice.profitmandi.dao.entity.dtr.User;
26745 amit.gupta 61
import com.spice.profitmandi.dao.entity.dtr.WebListing;
28374 amit.gupta 62
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
26774 amit.gupta 63
import com.spice.profitmandi.dao.entity.fofo.Customer;
26857 amit.gupta 64
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
28267 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
26855 tejbeer 66
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
67
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
26715 amit.gupta 68
import com.spice.profitmandi.dao.entity.fofo.PincodePartner;
28377 tejbeer 69
import com.spice.profitmandi.dao.entity.fofo.RazorPay;
26630 amit.gupta 70
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
27045 tejbeer 71
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
26607 amit.gupta 72
import com.spice.profitmandi.dao.model.AddCartRequest;
73
import com.spice.profitmandi.dao.model.CartItem;
74
import com.spice.profitmandi.dao.model.CartItemResponseModel;
75
import com.spice.profitmandi.dao.model.CartResponse;
27045 tejbeer 76
import com.spice.profitmandi.dao.model.CustomerOrderDetail;
26607 amit.gupta 77
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
78
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
28290 tejbeer 79
import com.spice.profitmandi.dao.repository.cs.CsService;
26718 amit.gupta 80
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27030 amit.gupta 81
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
26745 amit.gupta 82
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
28374 amit.gupta 83
import com.spice.profitmandi.dao.repository.dtr.WebOfferRepository;
26745 amit.gupta 84
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
26607 amit.gupta 85
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26788 amit.gupta 86
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
26774 amit.gupta 87
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
26855 tejbeer 88
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
89
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
26648 amit.gupta 90
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
26715 amit.gupta 91
import com.spice.profitmandi.dao.repository.fofo.PincodePartnerRepository;
28377 tejbeer 92
import com.spice.profitmandi.dao.repository.fofo.RazorPayRepository;
26607 amit.gupta 93
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
26784 amit.gupta 94
import com.spice.profitmandi.service.CustomerService;
28377 tejbeer 95
import com.spice.profitmandi.service.EmailService;
96
import com.spice.profitmandi.service.NotificationService;
26607 amit.gupta 97
import com.spice.profitmandi.service.authentication.RoleManager;
26923 amit.gupta 98
import com.spice.profitmandi.service.inventory.AvailabilityModel;
26607 amit.gupta 99
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
100
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
26923 amit.gupta 101
import com.spice.profitmandi.service.inventory.InventoryService;
26909 amit.gupta 102
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
26683 amit.gupta 103
import com.spice.profitmandi.service.scheme.SchemeService;
26651 amit.gupta 104
import com.spice.profitmandi.service.user.RetailerService;
26630 amit.gupta 105
import com.spice.profitmandi.web.processor.OtpProcessor;
26607 amit.gupta 106
import com.spice.profitmandi.web.res.DealBrands;
107
import com.spice.profitmandi.web.res.DealObjectResponse;
108
import com.spice.profitmandi.web.res.DealsResponse;
109
import com.spice.profitmandi.web.res.ValidateCartResponse;
28322 amit.gupta 110
import com.spice.profitmandi.web.services.PartnerIndexService;
26607 amit.gupta 111
 
112
import io.swagger.annotations.ApiImplicitParam;
113
import io.swagger.annotations.ApiImplicitParams;
114
import io.swagger.annotations.ApiOperation;
115
 
116
@Controller
117
@Transactional(rollbackFor = Throwable.class)
118
public class StoreController {
119
 
120
	private static final Logger logger = LogManager.getLogger(StoreController.class);
26630 amit.gupta 121
 
26628 amit.gupta 122
	private static final LocalTime CUTOFF_TIME = LocalTime.of(15, 0);
26745 amit.gupta 123
 
124
	private static final List<Integer> TAG_IDS = Arrays.asList(4);
125
 
26788 amit.gupta 126
	@Autowired
127
	CustomerAddressRepository customerAddressRepository;
28392 tejbeer 128
 
28374 amit.gupta 129
	@Autowired
130
	WebOfferRepository webOfferRepository;
26607 amit.gupta 131
 
28315 amit.gupta 132
	@Value("${new.solr.url}")
28314 amit.gupta 133
	private String solrUrl;
28345 tejbeer 134
 
26923 amit.gupta 135
	@Autowired
28322 amit.gupta 136
	private PartnerIndexService partnerIndexService;
28345 tejbeer 137
 
28322 amit.gupta 138
	@Autowired
26923 amit.gupta 139
	InventoryService inventoryService;
27045 tejbeer 140
 
27030 amit.gupta 141
	@Autowired
142
	UserAccountRepository userAccountRepository;
26923 amit.gupta 143
 
26607 amit.gupta 144
	@Value("${python.api.host}")
145
	private String host;
26833 amit.gupta 146
 
26784 amit.gupta 147
	@Autowired
148
	CustomerService customerService;
26607 amit.gupta 149
 
150
	@Value("${python.api.port}")
151
	private int port;
26923 amit.gupta 152
 
26909 amit.gupta 153
	@Autowired
154
	private SaholicInventoryService saholicInventoryService;
26607 amit.gupta 155
 
156
	@Autowired
26715 amit.gupta 157
	private PincodePartnerRepository pincodePartnerRepository;
158
 
159
	@Autowired
26718 amit.gupta 160
	private FofoStoreRepository fofoStoreRepository;
26745 amit.gupta 161
 
26718 amit.gupta 162
	@Autowired
26651 amit.gupta 163
	private RetailerService retailerService;
26861 tejbeer 164
 
26857 amit.gupta 165
	@Autowired
166
	private PendingOrderRepository pendingOrderRepository;
26861 tejbeer 167
 
26857 amit.gupta 168
	@Autowired
169
	private PendingOrderItemRepository pendingOrderItemRepository;
26652 amit.gupta 170
 
26651 amit.gupta 171
	@Autowired
26652 amit.gupta 172
	private PendingOrderService pendingOrderService;
26648 amit.gupta 173
 
174
	@Autowired
26774 amit.gupta 175
	private CustomerRepository customerRepository;
176
 
177
	@Autowired
26607 amit.gupta 178
	private SolrService commonSolrService;
179
 
180
	@Autowired
26630 amit.gupta 181
	private OtpProcessor otpProcessor;
182
 
183
	@Autowired
26607 amit.gupta 184
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
185
 
26609 amit.gupta 186
	@Autowired
26607 amit.gupta 187
	private ResponseSender<?> responseSender;
188
 
189
	@Autowired
190
	private TagListingRepository tagListingRepository;
191
 
192
	@Autowired
193
	private ItemRepository itemRepository;
26701 amit.gupta 194
 
26683 amit.gupta 195
	@Autowired
196
	private SchemeService schemeService;
26607 amit.gupta 197
 
198
	@Autowired
199
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
200
 
201
	@Autowired
26745 amit.gupta 202
	private WebListingRepository webListingRepository;
203
 
204
	@Autowired
205
	private WebProductListingRepository webProductListingRepository;
206
 
207
	@Autowired
26607 amit.gupta 208
	private RoleManager roleManagerService;
209
 
27028 tejbeer 210
	@Autowired
28304 amit.gupta 211
	EmailService emailService;
27028 tejbeer 212
 
213
	@Autowired
28290 tejbeer 214
	CsService csService;
28339 tejbeer 215
 
28377 tejbeer 216
	@Autowired
217
	private NotificationService notificationService;
218
 
219
	@Autowired
220
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
221
 
28339 tejbeer 222
	private static final List<String> offlineOrders = Arrays.asList("EMIOD", "POD");
223
 
26607 amit.gupta 224
	List<String> filterableParams = Arrays.asList("brand");
225
 
26668 amit.gupta 226
	@RequestMapping(value = "/store/entity/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
227
	@ApiImplicitParams({
228
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
229
	@ApiOperation(value = "Get unit deal object")
230
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
231
			throws ProfitMandiBusinessException {
232
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
233
		List<Integer> tagIds = Arrays.asList(4);
234
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
235
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
236
			String categoryId = "(3 OR 6)";
26745 amit.gupta 237
 
26668 amit.gupta 238
			RestClient rc = new RestClient();
239
			Map<String, String> params = new HashMap<>();
240
			List<String> mandatoryQ = new ArrayList<>();
241
			String catalogString = "catalog" + id;
26607 amit.gupta 242
 
26668 amit.gupta 243
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
244
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
245
 
246
			params.put("q", StringUtils.join(mandatoryQ, " "));
247
			params.put("fl", "*, [child parentFilter=id:catalog*]");
248
			params.put("sort", "rank_i asc, create_s desc");
249
			params.put("wt", "json");
250
			String response = null;
251
			try {
28316 amit.gupta 252
				response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
26668 amit.gupta 253
			} catch (HttpHostConnectException e) {
254
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
255
			}
256
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
257
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26909 amit.gupta 258
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
26668 amit.gupta 259
		} else {
260
			return responseSender.badRequest(
261
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
262
		}
263
		return responseSender.ok(dealResponse.get(0));
264
	}
265
 
26607 amit.gupta 266
	private Object toDealObject(JsonObject jsonObject) {
267
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
268
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
269
		}
270
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
271
	}
272
 
273
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
274
	@ApiImplicitParams({
275
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
276
	@ApiOperation(value = "Get brand list and count for category")
277
	public ResponseEntity<?> getBrands(HttpServletRequest request,
278
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
279
		logger.info("Request " + request.getParameterMap());
280
		String response = null;
281
		// TODO: move to properties
282
		String uri = ProfitMandiConstants.URL_BRANDS;
283
		RestClient rc = new RestClient();
284
		Map<String, String> params = new HashMap<>();
285
		params.put("category_id", category_id);
286
		List<DealBrands> dealBrandsResponse = null;
287
		try {
288
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
289
		} catch (HttpHostConnectException e) {
290
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
291
		}
292
 
293
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
294
		}.getType());
295
 
296
		return responseSender.ok(dealBrandsResponse);
297
	}
298
 
26745 amit.gupta 299
	@RequestMapping(value = "/store/listing/{listingUrl}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
300
	public ResponseEntity<?> bestSellers(HttpServletRequest request, @PathVariable String listingUrl) throws Exception {
26909 amit.gupta 301
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
28287 amit.gupta 302
		WebListing webListing = webListingRepository.selectByUrl(listingUrl);
303
		webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing));
26745 amit.gupta 304
		return responseSender.ok(webListing);
26654 amit.gupta 305
	}
306
 
26632 amit.gupta 307
	@RequestMapping(value = "/store/otp/generateOTP", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26783 amit.gupta 308
	public ResponseEntity<?> generateOtp(HttpServletRequest request, @RequestParam String mobile) throws Exception {
26630 amit.gupta 309
 
26857 amit.gupta 310
		return responseSender.ok(otpProcessor.generateOtp(mobile, OtpType.REGISTRATION));
26630 amit.gupta 311
 
312
	}
26652 amit.gupta 313
 
26784 amit.gupta 314
	@RequestMapping(value = "/store/checkmobile/{mobile}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26833 amit.gupta 315
	public ResponseEntity<?> checkRegistrationUsingMobile(HttpServletRequest request, @PathVariable String mobile)
316
			throws Exception {
26774 amit.gupta 317
		try {
318
			Customer customer = customerRepository.selectByMobileNumber(mobile);
26777 amit.gupta 319
			customer.setPasswordExist(StringUtils.isNotEmpty(customer.getPassword()));
26774 amit.gupta 320
			return responseSender.ok(new CustomerModel(true, customer));
321
		} catch (Exception e) {
322
			return responseSender.ok(new CustomerModel(false, null));
323
		}
324
	}
26833 amit.gupta 325
 
26784 amit.gupta 326
	@RequestMapping(value = "/store/signin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
327
	public ResponseEntity<?> signIn(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
26833 amit.gupta 328
		if (customerService.authenticate(userModel.getMobile(), userModel.getPassword())) {
26784 amit.gupta 329
			return responseSender.ok(true);
330
		} else {
331
			return responseSender.ok(false);
332
		}
333
	}
26923 amit.gupta 334
 
26841 amit.gupta 335
	@RequestMapping(value = "/store/resetPassword", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26923 amit.gupta 336
	public ResponseEntity<?> resetPassword(HttpServletRequest request, @RequestBody UserModel userModel)
337
			throws Exception {
26843 amit.gupta 338
		customerService.changePassword(userModel.getMobile(), userModel.getPassword());
26841 amit.gupta 339
		return responseSender.ok(true);
340
	}
26774 amit.gupta 341
 
26857 amit.gupta 342
	@RequestMapping(value = "/store/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
343
	public ResponseEntity<?> register(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
344
		Customer customer = new Customer();
345
		customer.setPassword(userModel.getPassword());
346
		customer.setEmailId(userModel.getEmail());
347
		customer.setFirstName(userModel.getFirstName());
348
		customer.setLastName(userModel.getLastName());
349
		customer.setMobileNumber(userModel.getMobile());
350
		return responseSender.ok(customerService.addCustomer(customer));
351
	}
352
 
26648 amit.gupta 353
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26857 amit.gupta 354
	public ResponseEntity<?> confirmOrder(HttpServletRequest request,
26652 amit.gupta 355
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 356
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
357
		Integer storeId = userInfo.getRetailerId();
358
		createPendingOrderRequest.setFofoId(storeId);
26923 amit.gupta 359
		List<CreatePendingOrderItem> pendingOrderItems = createPendingOrderRequest.getCreatePendingOrderItem();
360
		List<CartItem> cartItems = new ArrayList<>();
361
		pendingOrderItems.stream().forEach(x -> {
362
			CartItem ci = new CartItem();
363
			ci.setItemId(x.getItemId());
364
			ci.setQuantity(x.getQuantity());
365
			ci.setSellingPrice(x.getSellingPrice());
366
			cartItems.add(ci);
367
		});
368
		CartResponse cr = this.validateCart(storeId, cartItems);
369
		if (cr.getCartMessageChanged() > 0 || cr.getTotalAmount() != createPendingOrderRequest.getTotalAmount()) {
370
			return responseSender.badRequest("Invalid request");
371
		}
26652 amit.gupta 372
 
27028 tejbeer 373
		Map<String, String> returnMap = this.pendingOrderService.createPendingOrder(createPendingOrderRequest, cr);
374
 
28339 tejbeer 375
		PendingOrder pendingOrder = pendingOrderRepository.selectById(Integer.parseInt(returnMap.get("poId")));
376
		if (offlineOrders.contains(pendingOrder.getPayMethod())) {
377
 
378
			Map<String, Object> emailModel = pendingOrderService.sendCreateOrderMail(pendingOrder);
379
 
380
			CustomRetailer customRetailer = retailerService.getFofoRetailer(pendingOrder.getFofoId());
381
			Customer customer = customerRepository.selectById(pendingOrder.getCustomerId());
382
			String[] customerEmail = null;
383
			if (customer.getEmailId() != null) {
384
				customerEmail = new String[] { customer.getEmailId() };
385
			}
28377 tejbeer 386
 
28339 tejbeer 387
			List<String> bccTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com",
388
					"hemant.kaura@smartdukaan.com", "niranjan.kala@smartdukaan.com", "sm@smartdukaan.com",
389
					"tejbeer.kaur@shop2020.in", customRetailer.getEmail());
28377 tejbeer 390
 
28339 tejbeer 391
			List<String> authUserEmails = csService.getAuthUserByPartnerId(customRetailer.getPartnerId());
392
			if (authUserEmails != null) {
393
				authUserEmails = new ArrayList<>();
394
			}
395
			logger.info("authUserEmails {}", authUserEmails);
396
			authUserEmails.addAll(bccTo);
28374 amit.gupta 397
			StringBuffer itemBuffer = new StringBuffer();
398
			List<PendingOrderItem> orderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
399
			int totalItems = 0;
400
			String itemNoColor = null;
401
			float maxValue = 0;
28391 tejbeer 402
			for (PendingOrderItem orderItem : orderItems) {
403
				if (maxValue < orderItem.getSellingPrice()) {
28374 amit.gupta 404
					maxValue = orderItem.getSellingPrice();
405
					itemNoColor = itemRepository.selectById(orderItem.getItemId()).getItemDescriptionNoColor();
406
				}
407
				totalItems += orderItem.getQuantity();
408
			}
28391 tejbeer 409
			if (totalItems > 1) {
28374 amit.gupta 410
				itemBuffer.append(StringUtils.abbreviate(itemNoColor, 22));
28391 tejbeer 411
				itemBuffer.append(" +").append(totalItems - 1).append(" items");
28374 amit.gupta 412
			} else {
413
				itemBuffer.append(StringUtils.abbreviate(itemNoColor, 30));
414
			}
28391 tejbeer 415
			String message = String.format(OtpProcessor.TEMPLATE_ORDER_CREATED, pendingOrder.getId(),
416
					itemBuffer.toString(), pendingOrder.getTotalAmount());
28374 amit.gupta 417
			otpProcessor.sendSms(OtpProcessor.TEMPLATE_ORDER_CREATED_ID, message, customer.getMobileNumber());
28391 tejbeer 418
 
28339 tejbeer 419
			emailService.sendMailWithAttachments("Order Created with SmartDukaan", "order-confirm.vm", emailModel,
28377 tejbeer 420
					customerEmail, null, bccTo.toArray(new String[0]));
421
 
422
			List<String> gmailIds = csService.getAuthUserIdByPartnerId(customRetailer.getPartnerId()).stream()
423
					.map(x -> x.getGmailId()).collect(Collectors.toList());
28391 tejbeer 424
			gmailIds.add("tarunverma09@gmail.com");
28392 tejbeer 425
			gmailIds.add("tejbeerkaur27@gmail.com");
28377 tejbeer 426
			List<User> user = dtrUserRepository.selectAllByEmailIds(gmailIds);
427
			List<Integer> userIds = user.stream().map(x -> x.getId()).collect(Collectors.toList());
428
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
429
			sendNotificationModel.setCampaignName("Online Order Alert");
430
			sendNotificationModel.setTitle("Online Order Update");
28391 tejbeer 431
			sendNotificationModel.setMessage(String.format(
432
					"You have new Online Order. Please check your Dashboard. In case of an activation scheme pls ensure the handset is activated, payout will be processed as per brand's activation report."));
28377 tejbeer 433
			sendNotificationModel.setType("url");
434
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
435
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
436
			sendNotificationModel.setMessageType(MessageType.notification);
437
			int userId = userAccountRepository.selectUserIdByRetailerId(pendingOrder.getFofoId());
438
			sendNotificationModel.setUserIds(Arrays.asList(userId));
439
			notificationService.sendNotification(sendNotificationModel);
440
 
441
			sendNotificationModel = new SendNotificationModel();
442
			sendNotificationModel.setCampaignName("Online Order Alert");
443
			sendNotificationModel.setTitle("Online Order Update");
444
			sendNotificationModel.setMessage(String.format("Your Partner " + customRetailer.getBusinessName()
28393 tejbeer 445
					+ " have new Online Order. Please inform your partner. In case of an activation scheme pls ensure the handset is activated, payout will be processed as per brand's activation report."));
28377 tejbeer 446
			sendNotificationModel.setType("url");
447
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
448
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
449
			sendNotificationModel.setMessageType(MessageType.notification);
450
			sendNotificationModel.setUserIds(userIds);
28392 tejbeer 451
			notificationService.sendNotification(sendNotificationModel);
28377 tejbeer 452
 
28339 tejbeer 453
		}
27028 tejbeer 454
		return responseSender.ok(returnMap);
455
 
26648 amit.gupta 456
	}
26630 amit.gupta 457
 
26857 amit.gupta 458
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
459
	@ApiImplicitParams({
460
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
461
	@ApiOperation(value = "Get brand list and count for category")
462
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
463
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
464
		Integer storeId = userInfo.getRetailerId();
465
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
466
 
467
		return responseSender.ok(customRetailer.getAddress());
468
 
469
	}
470
 
471
	@RequestMapping(value = "/store/address/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
472
	@ApiImplicitParams({
473
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
474
	@ApiOperation(value = "Get brand list and count for category")
475
	public ResponseEntity<?> getStoresByPincode(HttpServletRequest request, @PathVariable String pincode)
476
			throws Exception {
477
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
28321 amit.gupta 478
		int fofoId = ProfitMandiConstants.DEFAULT_STORE;
26857 amit.gupta 479
		if (pincodePartners.size() > 0) {
28287 amit.gupta 480
			List<Integer> fofoIds = pincodePartners.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
28267 amit.gupta 481
			List<FofoStore> fofoStores = fofoStoreRepository.selectActivePartnersByRetailerIds(fofoIds);
28287 amit.gupta 482
			if (fofoStores.size() > 0) {
28267 amit.gupta 483
				fofoId = fofoStores.get(0).getId();
484
			}
28287 amit.gupta 485
 
26857 amit.gupta 486
		}
487
		return responseSender.ok(fofoStoreRepository.selectByRetailerId(fofoId).getCode());
488
	}
26923 amit.gupta 489
 
28298 tejbeer 490
	@RequestMapping(value = "/store/address/detail/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
491
	@ApiImplicitParams({
492
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
493
	@ApiOperation(value = "Get brand list and count for category")
494
	public ResponseEntity<?> getStoresDetailsByPincode(HttpServletRequest request, @PathVariable String pincode)
495
			throws Exception {
496
		List<CustomRetailer> customerRetailers = new ArrayList<>();
497
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
498
 
499
		if (!pincodePartners.isEmpty()) {
500
			List<Integer> fofoIds = pincodePartners.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
501
			List<Integer> activefofoIds = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
502
					.filter(x -> x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
503
			Map<Integer, CustomRetailer> customerRetailerMap = retailerService.getFofoRetailers(activefofoIds);
504
			customerRetailers.addAll(customerRetailerMap.values());
505
		}
506
 
507
		logger.info("customerRetailers" + customerRetailers);
508
		return responseSender.ok(customerRetailers);
509
	}
510
 
26855 tejbeer 511
	@RequestMapping(value = "/store/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
512
	public ResponseEntity<?> getOrderDetail(HttpServletRequest request, @RequestParam(value = "id") int id,
27049 tejbeer 513
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit) throws Exception {
26855 tejbeer 514
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
27049 tejbeer 515
		List<Integer> catalogIds = new ArrayList<>();
26855 tejbeer 516
		List<PendingOrder> pendingOrders = pendingOrderRepository.selectByCustomerId(id, offset, limit);
517
		if (!pendingOrders.isEmpty()) {
518
			for (PendingOrder po : pendingOrders) {
519
				List<PendingOrderItem> pois = pendingOrderItemRepository.selectByOrderId(po.getId());
27049 tejbeer 520
				for (PendingOrderItem pendingOrderItem : pois) {
521
					Item item = itemRepository.selectById(pendingOrderItem.getItemId());
522
					pendingOrderItem.setItemName(item.getItemDescription());
523
					catalogIds.add(item.getCatalogItemId());
524
				}
525
 
526
				Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
527
 
26855 tejbeer 528
				for (PendingOrderItem poi : pois) {
529
 
530
					CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
531
 
532
					Item item = itemRepository.selectById(poi.getItemId());
27049 tejbeer 533
					JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
534
					customerOrderDetail.setImageUrl(jsonObj.getString("imageUrl_s"));
26855 tejbeer 535
					customerOrderDetail.setBrand(item.getBrand());
536
					customerOrderDetail.setColor(item.getColor());
27056 tejbeer 537
					customerOrderDetail.setPendingOrderItemId(poi.getId());
26855 tejbeer 538
					customerOrderDetail.setId(poi.getOrderId());
539
					customerOrderDetail.setItemId(poi.getItemId());
540
					customerOrderDetail.setModelName(item.getModelName());
541
					customerOrderDetail.setModelNumber(item.getModelNumber());
542
					customerOrderDetail.setQuantity(poi.getQuantity());
27045 tejbeer 543
					customerOrderDetail.setBilledTimestamp(poi.getBilledTimestamp());
544
					customerOrderDetail.setStatus(poi.getStatus());
26855 tejbeer 545
					customerOrderDetail.setTotalPrice(poi.getSellingPrice());
546
					customerOrderDetail.setPayMethod(po.getPayMethod());
26861 tejbeer 547
					customerOrderDetail.setCreatedTimeStamp(po.getCreateTimestamp());
26855 tejbeer 548
					customerOrderDetails.add(customerOrderDetail);
549
				}
550
			}
551
		}
552
 
553
		return responseSender.ok(customerOrderDetails);
554
	}
555
 
26745 amit.gupta 556
	@RequestMapping(value = "/store/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26774 amit.gupta 557
	public ResponseEntity<?> getStoresListing(HttpServletRequest request) throws Exception {
26745 amit.gupta 558
		List<WebListing> webListings = webListingRepository.selectAllWebListing(Optional.of(true));
28287 amit.gupta 559
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
26745 amit.gupta 560
		for (WebListing webListing : webListings) {
28287 amit.gupta 561
			webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing));
26745 amit.gupta 562
		}
563
		return responseSender.ok(webListings);
564
	}
565
 
28287 amit.gupta 566
	private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing)
567
			throws ProfitMandiBusinessException {
568
		List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
569
				.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
570
		if (webProducts.size() == 0) {
571
			return new ArrayList<>();
572
		}
573
		RestClient rc = new RestClient();
574
		Map<String, String> params = new HashMap<>();
575
		List<String> mandatoryQ = new ArrayList<>();
576
		mandatoryQ.add(String.format(
577
				"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
578
				StringUtils.join(TAG_IDS, " ")));
579
		params.put("q", StringUtils.join(mandatoryQ, " "));
580
		params.put("fl", "*, [child parentFilter=id:catalog*]");
581
		// params.put("sort", "create_s desc");
582
		params.put("start", String.valueOf(0));
583
		params.put("rows", String.valueOf(100));
584
		params.put("wt", "json");
585
		String response = null;
586
		try {
587
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
588
		} catch (HttpHostConnectException e) {
589
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
590
		}
591
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
592
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
593
		List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
594
		return dealResponse;
595
	}
596
 
26652 amit.gupta 597
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
598
	@ApiImplicitParams({
26651 amit.gupta 599
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 600
	@ApiOperation(value = "Get brand list and count for category")
601
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
602
			throws Exception {
26923 amit.gupta 603
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
604
		Integer storeId = userInfo.getRetailerId();
605
		ValidateCartResponse vc = new ValidateCartResponse(this.validateCart(storeId, cartRequest.getCartItems()),
606
				"Success", "Items added to cart successfully");
607
		return responseSender.ok(vc);
608
	}
609
 
610
	// Validate Cart for B2C Customers
611
	private CartResponse validateCart(int storeId, List<CartItem> cartItems) throws Exception {
612
		cartItems = cartItems.stream().filter(x -> x.getQuantity() > 0).collect(Collectors.toList());
613
		List<Integer> itemIds = cartItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
614
		Map<Integer, AvailabilityModel> inventoryItemAvailabilityMap = inventoryService.getStoreAndOurStock(storeId,
615
				itemIds);
26607 amit.gupta 616
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 617
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
618
		cartResponse.setCartItems(cartItemResponseModels);
26607 amit.gupta 619
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
26668 amit.gupta 620
		logger.info("Store Id {}, Item Ids {}", storeId, itemsIdsSet);
26607 amit.gupta 621
 
622
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
623
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
624
 
26923 amit.gupta 625
		Map<Integer, TagListing> tagListingMap = tagListingRepository
26607 amit.gupta 626
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
627
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
628
 
629
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
630
				.collect(Collectors.toList());
631
 
632
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
633
 
634
		// cartResponse.getCartItems()
26923 amit.gupta 635
		int cartMessageChanged = 0;
636
		int cartMessageOOS = 0;
637
		int totalAmount = 0;
638
		int totalQty = 0;
639
		for (CartItem cartItem : cartItems) {
26607 amit.gupta 640
			Item item = itemsMap.get(cartItem.getItemId());
26923 amit.gupta 641
			TagListing tagListing = tagListingMap.get(cartItem.getItemId());
642
			Float cashback = schemeService.getItemSchemeCashBack().get(cartItem.getItemId());
643
			cashback = cashback == null ? 0 : cashback;
644
			float itemSellingPrice = tagListing.getMop() - cashback;
26607 amit.gupta 645
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26923 amit.gupta 646
			cartItemResponseModel.setSellingPrice(cartItem.getSellingPrice());
647
			if (itemSellingPrice != cartItem.getSellingPrice()) {
648
				cartItemResponseModel.setSellingPrice(itemSellingPrice);
649
				cartMessageChanged++;
650
			}
26628 amit.gupta 651
			int estimate = -2;
27025 tejbeer 652
			LocalDateTime promiseDeliveryTime = LocalDateTime.now();
26923 amit.gupta 653
			int qtyRequired = (int) cartItem.getQuantity();
654
			AvailabilityModel availabilityModel = inventoryItemAvailabilityMap.get(cartItem.getItemId());
655
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
656
			if (availabilityModel.getStoreAvailability() >= qtyRequired) {
657
				estimate = 0;
658
			} else if (availabilityModel.getWarehouseAvailability() >= qtyRequired) {
26628 amit.gupta 659
				estimate = 2;
26923 amit.gupta 660
			} else if (availabilityModel.getStoreAvailability() > 0) {
661
				estimate = 0;
662
				qtyRequired = availabilityModel.getStoreAvailability();
663
				cartMessageChanged++;
664
			} else if (availabilityModel.getWarehouseAvailability() > 0) {
665
				qtyRequired = availabilityModel.getWarehouseAvailability();
666
				estimate = 2;
667
				cartMessageChanged++;
26620 amit.gupta 668
			} else {
26923 amit.gupta 669
				qtyRequired = 0;
26926 amit.gupta 670
				cartMessageChanged++;
26607 amit.gupta 671
			}
26923 amit.gupta 672
			cartItemResponseModel.setQuantity(qtyRequired);
26630 amit.gupta 673
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 674
				estimate = estimate + 1;
27025 tejbeer 675
				promiseDeliveryTime = promiseDeliveryTime.plusDays(3);
26628 amit.gupta 676
			}
26923 amit.gupta 677
			totalQty += qtyRequired;
678
			totalAmount += qtyRequired * itemSellingPrice;
26628 amit.gupta 679
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 680
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 681
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 682
			cartItemResponseModel.setMinBuyQuantity(1);
26923 amit.gupta 683
			cartItemResponseModel.setQuantity(qtyRequired);
26621 amit.gupta 684
			cartItemResponseModel.setQuantityStep(1);
27025 tejbeer 685
			cartItemResponseModel.setPromiseDelivery(promiseDeliveryTime);
26923 amit.gupta 686
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
26607 amit.gupta 687
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
688
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
689
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 690
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 691
		}
26923 amit.gupta 692
		cartResponse.setCartItems(cartItemResponseModels);
693
		cartResponse.setCartMessageChanged(cartMessageChanged);
694
		cartResponse.setCartMessageOOS(cartMessageOOS);
695
		int maxEstimate = cartItemResponseModels.stream().mapToInt(x -> x.getEstimate()).max().getAsInt();
696
		cartResponse.setMaxEstimate(maxEstimate);
697
		cartResponse.setTotalAmount(totalAmount);
698
		cartResponse.setTotalQty(totalQty);
26652 amit.gupta 699
 
26923 amit.gupta 700
		return cartResponse;
701
 
26648 amit.gupta 702
	}
26607 amit.gupta 703
 
27030 amit.gupta 704
	@RequestMapping(value = "/store/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
705
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
706
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
707
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
708
			@RequestParam(value = "sort", required = false) String sort,
709
			@RequestParam(value = "brand", required = false) String brand,
710
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
711
			@RequestParam(value = "q", required = false) String queryTerm,
28287 amit.gupta 712
			@RequestParam(required = false) String listing,
713
			@RequestParam(required = false, defaultValue = "true") boolean partnerStockOnly) throws Throwable {
27030 amit.gupta 714
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
715
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
28269 amit.gupta 716
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
717
		sort = "w" + fs.getWarehouseId() + "_i desc";
27045 tejbeer 718
		dealResponse = this.getCatalogResponse(
28314 amit.gupta 719
				commonSolrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, false),
720
				false, userInfo.getRetailerId());
27030 amit.gupta 721
		return responseSender.ok(dealResponse);
722
	}
723
 
26909 amit.gupta 724
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
26607 amit.gupta 725
			throws ProfitMandiBusinessException {
26909 amit.gupta 726
		Map<Integer, Integer> ourItemAvailabilityMap = null;
727
		Map<Integer, Integer> partnerStockAvailabilityMap = null;
26607 amit.gupta 728
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
729
		List<Integer> tagIds = Arrays.asList(4);
730
		if (docs.length() > 0) {
731
			HashSet<Integer> itemsSet = new HashSet<>();
732
			for (int i = 0; i < docs.length(); i++) {
733
				JSONObject doc = docs.getJSONObject(i);
734
				if (doc.has("_childDocuments_")) {
735
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
736
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
737
						int itemId = childItem.getInt("itemId_i");
738
						itemsSet.add(itemId);
739
					}
740
				}
741
			}
742
			if (itemsSet.size() == 0) {
743
				return dealResponse;
744
			}
28269 amit.gupta 745
			if (fofoId > 0) {
26909 amit.gupta 746
				partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream()
747
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
748
			}
28287 amit.gupta 749
			ourItemAvailabilityMap = saholicInventoryService.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
26607 amit.gupta 750
		}
751
 
752
		for (int i = 0; i < docs.length(); i++) {
753
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
754
			JSONObject doc = docs.getJSONObject(i);
755
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
756
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
757
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
758
			ffdr.setTitle(doc.getString("title_s"));
28374 amit.gupta 759
			List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(ffdr.getCatalogId());
28391 tejbeer 760
			if (webOffers != null && webOffers.size() > 0) {
761
				ffdr.setOffers(webOffers.stream().map(x -> x.getSmallText()).collect(Collectors.toList()));
28374 amit.gupta 762
			}
26607 amit.gupta 763
			try {
764
				ffdr.setFeature(doc.getString("feature_s"));
765
			} catch (Exception e) {
766
				ffdr.setFeature(null);
767
			}
768
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
769
			if (doc.has("_childDocuments_")) {
770
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
771
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
772
					int itemId = childItem.getInt("itemId_i");
773
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
774
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
775
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
776
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
777
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
778
						}
779
					} else {
780
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26909 amit.gupta 781
						fdi.setSellingPrice(sellingPrice);
782
						fdi.setMrp(childItem.getDouble("mrp_f"));
26607 amit.gupta 783
						fdi.setMop((float) childItem.getDouble("mop_f"));
784
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
785
						fdi.setTagId(childItem.getInt("tagId_i"));
786
						fdi.setItem_id(itemId);
26909 amit.gupta 787
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
788
						cashBack = cashBack == null ? 0 : cashBack;
28391 tejbeer 789
						// TODO:Dont commit
790
						// fdi.setCashback(Math.min(100, fdi.getMop()));
26673 amit.gupta 791
						fdi.setMinBuyQuantity(1);
28313 amit.gupta 792
						int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0
793
								: partnerStockAvailabilityMap.get(itemId);
28287 amit.gupta 794
						int ourStockAvailability = ourItemAvailabilityMap.get(itemId) == null ? 0
795
								: Math.max(0, ourItemAvailabilityMap.get(itemId));
28313 amit.gupta 796
						fdi.setActive(partnerAvailability > 0);
28287 amit.gupta 797
						fdi.setAvailability(Math.min(5, ourStockAvailability + partnerAvailability));
26607 amit.gupta 798
						fdi.setQuantityStep(1);
28269 amit.gupta 799
						fdi.setMaxQuantity(fdi.getAvailability());
26607 amit.gupta 800
						fofoAvailabilityInfoMap.put(itemId, fdi);
801
					}
802
				}
803
			}
804
			if (fofoAvailabilityInfoMap.values().size() > 0) {
28313 amit.gupta 805
				ffdr.setItems(fofoAvailabilityInfoMap.values().stream()
806
						.sorted(Comparator.comparing(FofoAvailabilityInfo::isActive, Comparator.reverseOrder())
807
								.thenComparingInt(y -> -y.getAvailability()))
808
						.collect(Collectors.toList()));
26607 amit.gupta 809
				dealResponse.add(ffdr);
810
			}
811
		}
28314 amit.gupta 812
		return dealResponse.stream()
813
				.sorted(Comparator
814
						.comparing(FofoCatalogResponse::getItems,
815
								(s1, s2) -> (s2.get(0).isActive() ? 1 : 0) - (s1.get(0).isActive() ? 1 : 0))
816
						.thenComparing(FofoCatalogResponse::getItems,
817
								(x, y) -> y.get(0).getAvailability() - x.get(0).getAvailability()))
818
				.collect(Collectors.toList());
26607 amit.gupta 819
	}
26923 amit.gupta 820
 
821
	@GetMapping(value = "store/order-status/{pendingOrderId}")
27028 tejbeer 822
	public ResponseEntity<?> orderStatus(HttpServletRequest request, @PathVariable int pendingOrderId)
823
			throws Exception {
26923 amit.gupta 824
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
825
		List<PendingOrderItem> pendingOrderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
826
		List<Integer> catalogIds = new ArrayList<>();
27028 tejbeer 827
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 828
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
829
			pendingOrderItem.setItemName(item.getItemDescription());
830
			catalogIds.add(item.getCatalogItemId());
831
		}
832
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
27028 tejbeer 833
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 834
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
835
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
836
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
837
		}
838
		pendingOrder.setPendingOrderItems(pendingOrderItems);
27069 tejbeer 839
 
26923 amit.gupta 840
		return responseSender.ok(pendingOrder);
841
	}
842
 
26833 amit.gupta 843
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
844
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
27045 tejbeer 845
		return responseSender.ok(customerAddressRepository.selectByActiveCustomerId(customerId));
26788 amit.gupta 846
	}
26833 amit.gupta 847
 
26857 amit.gupta 848
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
849
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
850
			throws Throwable {
851
		customerAddressRepository.persist(customerAddress);
852
		return responseSender.ok(customerAddress);
853
	}
854
 
27045 tejbeer 855
	@RequestMapping(value = "/store/deactivateCustomerAddress", method = RequestMethod.POST)
856
	public ResponseEntity<?> deactivateAddresss(HttpServletRequest request, @RequestParam int id) throws Throwable {
857
		CustomerAddress cust = customerAddressRepository.selectById(id);
858
		cust.setActive(false);
859
		return responseSender.ok(cust);
860
	}
861
 
26861 tejbeer 862
	@RequestMapping(value = "/store/updateCustomer", method = RequestMethod.POST)
863
	public ResponseEntity<?> updateCustomerProfile(HttpServletRequest request, @RequestBody Customer customer)
864
			throws Throwable {
865
		Customer cust = customerRepository.selectById(customer.getId());
866
		cust.setGender(customer.getGender());
26867 tejbeer 867
		cust.setProfileImageId(customer.getProfileImageId());
26861 tejbeer 868
		cust.setDob(customer.getDob());
869
		return responseSender.ok(cust);
870
	}
28345 tejbeer 871
 
28322 amit.gupta 872
	@RequestMapping(value = "/stores/{state}/{city}/{storeCode}", method = RequestMethod.GET)
28345 tejbeer 873
	public void getStoreIndex(HttpServletResponse response, HttpServletRequest request, @PathVariable String state,
874
			@PathVariable String city, @PathVariable String storeCode) throws Throwable {
28325 amit.gupta 875
		logger.info("Store code {}", storeCode);
28345 tejbeer 876
		Map<String, Integer> map = retailerService.getStoreCodeRetailerMap();
877
		logger.info("retailer id {}", map.get(storeCode));
28336 amit.gupta 878
		String retailerName = retailerService.getAllFofoRetailers().get(map.get(storeCode)).getBusinessName();
28322 amit.gupta 879
		String html = partnerIndexService.getPartnerIndexHtml();
28332 amit.gupta 880
		logger.info("html {}", html);
28327 amit.gupta 881
		html = html.replace("Buy Mobiles and Accessories at exciting prices - SmartDukaan",
28338 amit.gupta 882
				String.format("%s is now ONLINE. Buy Mobiles, Accessories & more | SmartDukaan", retailerName));
28334 amit.gupta 883
		response.getWriter().write(html);
28322 amit.gupta 884
	}
26861 tejbeer 885
 
27048 tejbeer 886
	@RequestMapping(value = "/cancelPendingOrderItem", method = RequestMethod.POST)
887
	public ResponseEntity<?> cancelPendingOrderItem(HttpServletRequest request, @RequestParam int id,
27045 tejbeer 888
 
28354 tejbeer 889
			@RequestParam String statusDescription, @RequestParam String reason) throws Exception {
27048 tejbeer 890
 
891
		PendingOrderItem pendingOrderItem = pendingOrderItemRepository.selectById(id);
27057 tejbeer 892
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderItem.getOrderId());
28304 amit.gupta 893
		Customer customer = customerRepository.selectById(pendingOrder.getCustomerId());
27048 tejbeer 894
		if (pendingOrderItem.getBilledTimestamp() == null) {
895
			pendingOrderItem.setStatus(OrderStatus.CANCELLED);
28354 tejbeer 896
			pendingOrderItem.setRemark(reason);
897
			pendingOrderItem.setStatusDescription("cancel by self");
28304 amit.gupta 898
			pendingOrderItem.setCancelledTimestamp(LocalDateTime.now());
27048 tejbeer 899
			List<OrderStatus> status = pendingOrderItemRepository.selectByOrderId(pendingOrderItem.getOrderId())
900
					.stream().map(x -> x.getStatus()).collect(Collectors.toList());
901
 
28345 tejbeer 902
			if (!status.contains(OrderStatus.PENDING) && !status.contains(OrderStatus.PROCESSING)
903
					&& !status.contains(OrderStatus.BILLED) && !status.contains(OrderStatus.UNSETTLED)
904
					&& !status.contains(OrderStatus.CLAIMED)) {
27048 tejbeer 905
				pendingOrder.setStatus(OrderStatus.CLOSED);
906
			}
907
 
908
			pendingOrderItemRepository.persist(pendingOrderItem);
28304 amit.gupta 909
			String itemDescription = itemRepository.selectById(pendingOrderItem.getItemId()).getItemDescription();
28313 amit.gupta 910
			otpProcessor.sendSms(OtpProcessor.SELF_CANCELLED_TEMPLATE_ID,
911
					String.format(OtpProcessor.SELF_CANCELLED_TEMPLATE, pendingOrder.getId(),
28304 amit.gupta 912
							StringUtils.abbreviate(itemDescription, 30),
28313 amit.gupta 913
							FormattingUtils.format(pendingOrderItem.getCancelledTimestamp())),
28304 amit.gupta 914
					customer.getMobileNumber());
28339 tejbeer 915
 
916
			List<Integer> catalogIds = new ArrayList<>();
917
 
918
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
919
			pendingOrderItem.setItemName(item.getItemDescription());
920
			catalogIds.add(item.getCatalogItemId());
921
 
922
			Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
923
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
924
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
925
			pendingOrder.setPendingOrderItems(Arrays.asList(pendingOrderItem));
926
			CustomerAddress customerAddress = customerAddressRepository.selectById(pendingOrder.getCustomerAddressId());
927
 
928
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy h:mm a");
929
 
930
			Map<String, Object> emailModel = new HashMap<>();
931
			emailModel.put("customer", customerAddress);
932
			emailModel.put("pendingOrder", pendingOrder);
933
			emailModel.put("date", dateTimeFormatter);
934
 
935
			String[] customerEmail = null;
936
			if (customer.getEmailId() != null) {
28355 tejbeer 937
				customerEmail = new String[] { customer.getEmailId() };
28339 tejbeer 938
 
28355 tejbeer 939
				List<String> bccTo = Arrays.asList("tejbeer.kaur@smartdukaan.com");
940
 
28339 tejbeer 941
				emailService.sendMailWithAttachments("Order Cancellation", "order-cancellation.vm", emailModel,
28355 tejbeer 942
						customerEmail, null, bccTo.toArray(new String[0]));
28339 tejbeer 943
 
944
			}
27048 tejbeer 945
		}
946
 
947
		return responseSender.ok(true);
948
 
949
	}
950
 
26774 amit.gupta 951
}
952
 
26784 amit.gupta 953
class UserModel {
26857 amit.gupta 954
	@JsonProperty(required = true)
26784 amit.gupta 955
	private String mobile;
26857 amit.gupta 956
	@JsonProperty(required = true)
26784 amit.gupta 957
	private String password;
26857 amit.gupta 958
	@JsonProperty(required = false)
959
	private String firstName;
960
	@JsonProperty(required = false)
961
	private String lastName;
962
	@JsonProperty(required = false)
963
	private String email;
26833 amit.gupta 964
 
26784 amit.gupta 965
	@Override
966
	public String toString() {
967
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
968
	}
26833 amit.gupta 969
 
26784 amit.gupta 970
	public String getMobile() {
971
		return mobile;
972
	}
26833 amit.gupta 973
 
26784 amit.gupta 974
	public void setMobile(String mobile) {
975
		this.mobile = mobile;
976
	}
26833 amit.gupta 977
 
26784 amit.gupta 978
	public String getPassword() {
979
		return password;
980
	}
26833 amit.gupta 981
 
26784 amit.gupta 982
	public void setPassword(String password) {
983
		this.password = password;
984
	}
26857 amit.gupta 985
 
986
	public String getFirstName() {
987
		return firstName;
988
	}
989
 
990
	public void setFirstName(String firstName) {
991
		this.firstName = firstName;
992
	}
993
 
994
	public String getLastName() {
995
		return lastName;
996
	}
997
 
998
	public void setLastName(String lastName) {
999
		this.lastName = lastName;
1000
	}
1001
 
1002
	public String getEmail() {
1003
		return email;
1004
	}
1005
 
1006
	public void setEmail(String email) {
1007
		this.email = email;
1008
	}
1009
 
26784 amit.gupta 1010
}
1011
 
26774 amit.gupta 1012
class CustomerModel {
26783 amit.gupta 1013
 
26774 amit.gupta 1014
	@JsonProperty(required = false)
1015
	private Customer customer;
1016
	@JsonProperty(required = true)
1017
	private boolean exists;
1018
 
1019
	public CustomerModel(boolean exists, Customer customer) {
1020
		super();
1021
		this.customer = customer;
1022
		this.exists = exists;
1023
	}
1024
 
1025
	@Override
1026
	public String toString() {
1027
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
1028
	}
1029
 
1030
	public Customer getCustomer() {
1031
		return customer;
1032
	}
1033
 
1034
	public void setCustomer(Customer customer) {
1035
		this.customer = customer;
1036
	}
1037
 
1038
	public boolean isExists() {
1039
		return exists;
1040
	}
1041
 
1042
	public void setExists(boolean exists) {
1043
		this.exists = exists;
1044
	}
26607 amit.gupta 1045
}