Subversion Repositories SmartDukaan

Rev

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