Subversion Repositories SmartDukaan

Rev

Rev 36539 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
29707 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.CustomAddress;
5
import com.spice.profitmandi.common.model.CustomCustomer;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
7
import com.spice.profitmandi.common.solr.SolrService;
8
import com.spice.profitmandi.common.web.util.ResponseSender;
31147 tejbeer 9
import com.spice.profitmandi.dao.entity.catalog.CustomerOffer;
29707 tejbeer 10
import com.spice.profitmandi.dao.entity.catalog.CustomerOfferItem;
11
import com.spice.profitmandi.dao.entity.catalog.Item;
31048 amit.gupta 12
import com.spice.profitmandi.dao.entity.fofo.*;
29707 tejbeer 13
import com.spice.profitmandi.dao.model.CustomerOrderDetail;
14
import com.spice.profitmandi.dao.model.UserCart;
15
import com.spice.profitmandi.dao.repository.catalog.CustomerOfferItemRepository;
16
import com.spice.profitmandi.dao.repository.catalog.CustomerOfferRepository;
17
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
18
import com.spice.profitmandi.dao.repository.catalog.SamsungUpgradeOfferRepository;
19
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
31048 amit.gupta 20
import com.spice.profitmandi.dao.repository.fofo.*;
29707 tejbeer 21
import com.spice.profitmandi.service.CustomerService;
22
import com.spice.profitmandi.service.inventory.InventoryService;
23
import io.swagger.annotations.ApiImplicitParam;
24
import io.swagger.annotations.ApiImplicitParams;
31048 amit.gupta 25
import org.apache.logging.log4j.LogManager;
26
import org.apache.logging.log4j.Logger;
27
import org.springframework.beans.factory.annotation.Autowired;
28
import org.springframework.http.MediaType;
29
import org.springframework.http.ResponseEntity;
30
import org.springframework.stereotype.Controller;
31
import org.springframework.transaction.annotation.Transactional;
32
import org.springframework.util.StringUtils;
33
import org.springframework.web.bind.annotation.RequestBody;
34
import org.springframework.web.bind.annotation.RequestMapping;
35
import org.springframework.web.bind.annotation.RequestMethod;
36
import org.springframework.web.bind.annotation.RequestParam;
29707 tejbeer 37
 
31048 amit.gupta 38
import javax.servlet.http.HttpServletRequest;
39
import java.time.LocalDate;
40
import java.time.LocalDateTime;
41
import java.util.ArrayList;
37381 amit 42
import java.util.HashMap;
31048 amit.gupta 43
import java.util.List;
35415 amit 44
import java.util.Map;
45
import java.util.Set;
46
import java.util.HashSet;
47
import java.util.function.Function;
31048 amit.gupta 48
import java.util.stream.Collectors;
49
 
29707 tejbeer 50
@Controller
51
@Transactional(rollbackFor = Throwable.class)
52
public class CustomerController {
53
 
54
	private static final Logger LOGGER = LogManager.getLogger(CustomerController.class);
55
 
56
	@Autowired
57
	private ResponseSender<?> responseSender;
58
 
59
	@Autowired
60
	private UserAccountRepository userAccountRepository;
61
 
62
	@Autowired
63
	private CustomerRepository customerRepository;
64
 
65
	@Autowired
66
	private InventoryService inventoryService;
67
 
68
	@Autowired
69
	private CustomerService customerService;
70
 
71
	@Autowired
72
	private CustomerAddressRepository customerAddressRepository;
73
 
74
	@Autowired
75
	private FofoOrderItemRepository fofoOrderItemRepository;
76
 
77
	@Autowired
78
	private SolrService commonSolrService;
79
 
80
	@Autowired
81
	private FofoLineItemRepository fofoLineItemRepository;
82
 
83
	@Autowired
84
	private ItemRepository itemRepository;
85
 
86
	@Autowired
87
	private FofoOrderRepository fofoOrderRepository;
88
 
89
	@Autowired
90
	private CustomerOfferRepository customerOfferRepository;
91
 
92
	@Autowired
93
	private CustomerOfferItemRepository customerOfferItemRepository;
94
 
95
	@Autowired
96
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
97
 
98
	@RequestMapping(value = "/customer/mobileNumber", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
99
	@ApiImplicitParams({
100
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
101
	public ResponseEntity<?> getCustomerByMobileNumber(HttpServletRequest request,
102
			@RequestParam(name = ProfitMandiConstants.MOBILE_NUMBER) String mobileNumber)
103
			throws ProfitMandiBusinessException {
104
		CustomCustomer customCustomer = null;
105
		LOGGER.info("Request Received at url {}", request.getRequestURI());
106
		try {
107
			Customer customer = customerRepository.selectByMobileNumber(mobileNumber);
108
			customCustomer = new CustomCustomer();
109
			customCustomer.setCustomerId(customer.getId());
110
			customCustomer.setEmailId(customer.getEmailId());
111
			customCustomer.setFirstName(customer.getFirstName());
112
			customCustomer.setLastName(customer.getLastName());
113
			customCustomer.setMobileNumber(customer.getMobileNumber());
114
			LOGGER.info(customer.getCustomerAddress());
35196 aman 115
			List<CustomerAddress> customerAddresses = customer.getCustomerAddress().stream().filter(c -> Boolean.TRUE.equals(c.getActive())).collect(Collectors.toList());
29707 tejbeer 116
			LOGGER.info(customerAddresses);
117
			if (!customerAddresses.isEmpty()) {
118
				List<CustomAddress> customAddresses = new ArrayList<>();
119
				for (CustomerAddress customerAddress : customerAddresses) {
120
					customAddresses.add(this.toCustomAddress(customerAddress));
121
				}
122
				customCustomer.setAddresses(customAddresses);
123
			}
124
		} catch (Exception e) {
125
			e.printStackTrace();
126
		}
127
		return responseSender.ok(customCustomer);
128
	}
129
 
130
	private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
131
		CustomAddress customAddress = new CustomAddress();
132
		customAddress.setCity(customerAddress.getCity());
133
		customAddress.setCountry(customerAddress.getCountry());
134
		customAddress.setLandmark(customerAddress.getLandmark());
135
		customAddress.setLine1(customerAddress.getLine1());
136
		customAddress.setLine2(customerAddress.getLine2());
137
		customAddress.setName(customerAddress.getName());
138
		customAddress.setLastName(customerAddress.getLastName());
139
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
140
		customAddress.setPinCode(customerAddress.getPinCode());
141
		customAddress.setState(customerAddress.getState());
142
		customAddress.setId(customerAddress.getId());
35196 aman 143
		customAddress.setDefaultAddress(customerAddress.getDefault());
29707 tejbeer 144
		return customAddress;
145
	}
146
 
147
	@RequestMapping(value = "/customer/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
148
	@ApiImplicitParams({
149
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
150
	public ResponseEntity<?> addCustomer(HttpServletRequest request, @RequestBody CustomCustomer customCustomer)
151
			throws ProfitMandiBusinessException {
152
		Customer customer = new Customer();
153
		if (StringUtils.isEmpty(customCustomer.getFirstName())) {
154
			throw new ProfitMandiBusinessException("First Name", "Empty", "First Name required");
155
		}
156
		customer.setEmailId(customCustomer.getEmailId());
157
		customer.setFirstName(customCustomer.getFirstName());
158
		customer.setLastName(customCustomer.getLastName());
159
		customer.setMobileNumber(customCustomer.getMobileNumber());
160
		customer = customerService.addCustomer(customer);
161
		customCustomer.setCustomerId(customer.getId());
162
		return responseSender.ok(customCustomer);
163
 
164
	}
165
 
166
	@RequestMapping(value = "/customer/address", method = RequestMethod.POST)
167
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
168
			@RequestBody CustomAddress customAddress) {
169
		CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
35196 aman 170
		customerAddress.setActive(true);
29707 tejbeer 171
		customerAddressRepository.persist(customerAddress);
172
		return responseSender.ok(this.toCustomAddress(customerAddress));
173
 
174
	}
175
 
36539 aman 176
	@RequestMapping(value = "/customer/address/update", method = RequestMethod.PUT)
177
	public ResponseEntity<?> updateAddress(HttpServletRequest request, @RequestParam int addressId,
178
			@RequestBody CustomAddress customAddress) {
179
		try {
180
			CustomerAddress customerAddress = customerAddressRepository.selectById(addressId);
181
			if (customAddress.getName() != null) customerAddress.setName(customAddress.getName());
182
			if (customAddress.getLastName() != null) customerAddress.setLastName(customAddress.getLastName());
183
			if (customAddress.getLine1() != null) customerAddress.setLine1(customAddress.getLine1());
184
			if (customAddress.getLine2() != null) customerAddress.setLine2(customAddress.getLine2());
185
			if (customAddress.getLandmark() != null) customerAddress.setLandmark(customAddress.getLandmark());
186
			if (customAddress.getCity() != null) customerAddress.setCity(customAddress.getCity());
187
			if (customAddress.getPinCode() != null) customerAddress.setPinCode(customAddress.getPinCode());
188
			if (customAddress.getState() != null) customerAddress.setState(customAddress.getState());
189
			if (customAddress.getCountry() != null) customerAddress.setCountry(customAddress.getCountry());
190
			if (customAddress.getPhoneNumber() != null) customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
191
			return responseSender.ok(this.toCustomAddress(customerAddress));
192
		} catch (ProfitMandiBusinessException e) {
193
			return responseSender.badRequest(e);
194
		}
195
	}
196
 
29707 tejbeer 197
	private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
198
		CustomerAddress customerAddress = new CustomerAddress();
199
		customerAddress.setCustomerId(customerId);
200
		customerAddress.setName(customAddress.getName());
201
		customerAddress.setLastName(customAddress.getLastName());
202
		customerAddress.setLine1(customAddress.getLine1());
203
		customerAddress.setLine2(customAddress.getLine2());
204
		customerAddress.setLandmark(customAddress.getLandmark());
205
		customerAddress.setCity(customAddress.getCity());
206
		customerAddress.setPinCode(customAddress.getPinCode());
207
		customerAddress.setState(customAddress.getState());
208
		customerAddress.setCountry(customAddress.getCountry());
209
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
210
 
211
		return customerAddress;
212
	}
213
 
214
	@RequestMapping(value = "/customer/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
215
	@ApiImplicitParams({
216
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
217
	public ResponseEntity<?> getOrderInvoiceDetail(HttpServletRequest request,
218
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit) throws Exception {
219
 
220
		int userId = (int) request.getAttribute("userId");
221
		UserCart uc = userAccountRepository.getUserCart(userId);
222
 
223
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
224
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectOrderByFofoId(uc.getUserId(), offset, limit);
225
 
35415 amit 226
		if (fofoOrders.isEmpty()) {
227
			return responseSender.ok(customerOrderDetails);
228
		}
29707 tejbeer 229
 
35415 amit 230
		// Filter out cancelled orders
231
		List<FofoOrder> activeOrders = fofoOrders.stream()
232
				.filter(fo -> fo.getCancelledTimestamp() == null)
233
				.collect(Collectors.toList());
29707 tejbeer 234
 
35415 amit 235
		if (activeOrders.isEmpty()) {
236
			return responseSender.ok(customerOrderDetails);
237
		}
29707 tejbeer 238
 
35415 amit 239
		// Batch fetch all order items for all orders at once
240
		List<Integer> orderIds = activeOrders.stream().map(FofoOrder::getId).collect(Collectors.toList());
241
		List<FofoOrderItem> allOrderItems = fofoOrderItemRepository.selectByOrderIds(orderIds);
242
		Map<Integer, List<FofoOrderItem>> orderItemsByOrderId = allOrderItems.stream()
243
				.collect(Collectors.groupingBy(FofoOrderItem::getOrderId));
29707 tejbeer 244
 
35415 amit 245
		// Batch fetch all customers
246
		List<Integer> customerIds = activeOrders.stream().map(FofoOrder::getCustomerId).distinct().collect(Collectors.toList());
247
		Map<Integer, Customer> customerMap = customerRepository.selectAllByIds(customerIds).stream()
248
				.collect(Collectors.toMap(Customer::getId, Function.identity()));
29707 tejbeer 249
 
35415 amit 250
		// Batch fetch all customer addresses
251
		List<Integer> addressIds = activeOrders.stream().map(FofoOrder::getCustomerAddressId).distinct().collect(Collectors.toList());
252
		Map<Integer, CustomerAddress> addressMap = customerAddressRepository.selectAllByIds(addressIds).stream()
253
				.collect(Collectors.toMap(CustomerAddress::getId, Function.identity()));
29707 tejbeer 254
 
35415 amit 255
		// Batch fetch all items
256
		Set<Integer> itemIds = allOrderItems.stream().map(FofoOrderItem::getItemId).collect(Collectors.toSet());
37381 amit 257
		// A customer whose only order is an insurance-only sale has no fofo_order_item rows, so
258
		// itemIds is empty and selectByIds would throw "List should not be empty" on the empty IN.
259
		Map<Integer, Item> itemMap = itemIds.isEmpty()
260
				? new HashMap<>()
261
				: itemRepository.selectByIds(new ArrayList<>(itemIds)).stream()
262
						.collect(Collectors.toMap(Item::getId, Function.identity()));
29707 tejbeer 263
 
35415 amit 264
		// Batch fetch all line items
265
		Set<Integer> orderItemIds = allOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
266
		List<FofoLineItem> allLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(orderItemIds);
267
		Map<Integer, List<FofoLineItem>> lineItemsByOrderItemId = allLineItems.stream()
268
				.collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
29707 tejbeer 269
 
35415 amit 270
		// Fetch customer offers once outside the loops
271
		Map<Integer, List<CustomerOffer>> customerOffersMap = customerOfferRepository.getCustomerOffer(LocalDate.now().atStartOfDay());
272
		List<CustomerOffer> customerOffers = customerOffersMap.get(uc.getUserId());
273
		List<Integer> offerIds = (customerOffers != null && !customerOffers.isEmpty())
274
				? customerOffers.stream().map(CustomerOffer::getId).collect(Collectors.toList())
275
				: new ArrayList<>();
29707 tejbeer 276
 
35415 amit 277
		// Process orders using pre-fetched data
278
		for (FofoOrder fo : activeOrders) {
279
			List<FofoOrderItem> fofoOrderItems = orderItemsByOrderId.getOrDefault(fo.getId(), new ArrayList<>());
280
			Customer customer = customerMap.get(fo.getCustomerId());
281
			CustomerAddress customerAddress = addressMap.get(fo.getCustomerAddressId());
29707 tejbeer 282
 
35415 amit 283
			for (FofoOrderItem foi : fofoOrderItems) {
284
				Item item = itemMap.get(foi.getItemId());
285
				if (item != null) {
286
					foi.setItemName(item.getItemDescription());
287
				}
29707 tejbeer 288
 
35415 amit 289
				List<FofoLineItem> fofoLineItems = lineItemsByOrderItemId.getOrDefault(foi.getId(), new ArrayList<>());
29707 tejbeer 290
 
35415 amit 291
				CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
29707 tejbeer 292
 
35415 amit 293
				List<String> serialNumbers = fofoLineItems.stream()
294
						.map(FofoLineItem::getSerialNumber)
295
						.filter(x -> x != null)
296
						.collect(Collectors.toList());
29707 tejbeer 297
 
35415 amit 298
				customerOrderDetail.setSerialNumber(serialNumbers);
29707 tejbeer 299
 
35415 amit 300
				if (customerAddress != null) {
301
					customerOrderDetail.setCustomerName(customerAddress.getName());
302
					customerOrderDetail.setCustomerMobile(customerAddress.getPhoneNumber());
303
					customerOrderDetail.setCustomerEmail(customer != null ? customer.getEmailId() : null);
304
					customerOrderDetail.setCustomerCity(customerAddress.getCity());
305
					customerOrderDetail.setCustomerState(customerAddress.getState());
306
				}
29707 tejbeer 307
 
35415 amit 308
				if (item != null) {
309
					customerOrderDetail.setBrand(item.getBrand());
310
					customerOrderDetail.setColor(item.getColor());
311
					customerOrderDetail.setModelName(item.getModelName());
312
					customerOrderDetail.setModelNumber(item.getModelNumber());
313
				}
314
				customerOrderDetail.setFofoOrderItemId(foi.getId());
315
				customerOrderDetail.setFofoOrderId(foi.getOrderId());
316
				customerOrderDetail.setItemId(foi.getItemId());
317
				customerOrderDetail.setQuantity(foi.getQuantity());
318
				customerOrderDetail.setTotalPrice(foi.getSellingPrice());
319
				customerOrderDetail.setCreatedTimeStamp(foi.getCreateTimestamp());
320
				customerOrderDetail.setInvoiceNumber(fo.getInvoiceNumber());
321
				customerOrderDetail.setCancelledTimestamp(fo.getCancelledTimestamp());
322
				customerOrderDetail.setInsurance(false);
29707 tejbeer 323
 
35415 amit 324
				if (!serialNumbers.isEmpty() && item != null) {
325
					if ("85171300".equals(item.getHsnCode())) {
326
						customerOrderDetail.setInsurance(true);
29707 tejbeer 327
					}
328
				}
35415 amit 329
 
330
				long offerCount = 0;
331
				if (!offerIds.isEmpty() && item != null) {
332
					List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
333
							.selectByOfferIds(offerIds, item.getCatalogItemId(), LocalDate.now());
334
					offerCount = customerOfferItems.size();
335
				}
336
 
337
				customerOrderDetail.setOfferCount(offerCount);
338
				customerOrderDetails.add(customerOrderDetail);
29707 tejbeer 339
			}
35415 amit 340
		}
29707 tejbeer 341
 
342
		return responseSender.ok(customerOrderDetails);
343
	}
344
 
345
}