Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21612 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
21689 ashik.ali 3
import java.io.ByteArrayInputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.InputStream;
22217 ashik.ali 6
import java.time.DateTimeException;
7
import java.time.LocalDate;
22244 ashik.ali 8
import java.time.LocalDateTime;
21680 ashik.ali 9
import java.util.ArrayList;
21985 kshitij.so 10
import java.util.Collection;
21680 ashik.ali 11
import java.util.HashMap;
21612 ashik.ali 12
import java.util.HashSet;
21985 kshitij.so 13
import java.util.Iterator;
21680 ashik.ali 14
import java.util.List;
15
import java.util.Map;
21612 ashik.ali 16
import java.util.Set;
17
 
18
import javax.servlet.http.HttpServletRequest;
21689 ashik.ali 19
import javax.servlet.http.HttpServletResponse;
21612 ashik.ali 20
 
21985 kshitij.so 21
import org.json.JSONObject;
21612 ashik.ali 22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24
import org.springframework.beans.factory.annotation.Autowired;
21689 ashik.ali 25
import org.springframework.core.io.InputStreamResource;
26
import org.springframework.http.HttpHeaders;
27
import org.springframework.http.HttpStatus;
28
import org.springframework.http.MediaType;
29
import org.springframework.http.ResponseEntity;
21612 ashik.ali 30
import org.springframework.stereotype.Controller;
22064 ashik.ali 31
import org.springframework.transaction.annotation.Transactional;
21985 kshitij.so 32
import org.springframework.ui.Model;
21612 ashik.ali 33
import org.springframework.web.bind.annotation.RequestBody;
34
import org.springframework.web.bind.annotation.RequestMapping;
35
import org.springframework.web.bind.annotation.RequestMethod;
21689 ashik.ali 36
import org.springframework.web.bind.annotation.RequestParam;
21612 ashik.ali 37
 
38
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
21985 kshitij.so 39
import com.spice.profitmandi.common.model.CartFofo;
21680 ashik.ali 40
import com.spice.profitmandi.common.model.CustomAddress;
21689 ashik.ali 41
import com.spice.profitmandi.common.model.CustomCustomer;
42
import com.spice.profitmandi.common.model.CustomFofoLineItem;
43
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
22217 ashik.ali 44
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
21689 ashik.ali 45
import com.spice.profitmandi.common.model.CustomRetailer;
22217 ashik.ali 46
import com.spice.profitmandi.common.model.GadgetCopsInsuranceModel;
21896 ashik.ali 47
import com.spice.profitmandi.common.model.GstRate;
21689 ashik.ali 48
import com.spice.profitmandi.common.model.PdfModel;
21612 ashik.ali 49
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22217 ashik.ali 50
import com.spice.profitmandi.common.model.SerialNumberDetail;
51
import com.spice.profitmandi.common.util.InsuranceUtils;
21689 ashik.ali 52
import com.spice.profitmandi.common.util.PdfUtils;
21680 ashik.ali 53
import com.spice.profitmandi.common.util.StringUtils;
21896 ashik.ali 54
import com.spice.profitmandi.common.util.Utils;
22244 ashik.ali 55
import com.spice.profitmandi.common.web.util.ResponseSender;
21728 ashik.ali 56
import com.spice.profitmandi.dao.entity.catalog.Item;
22217 ashik.ali 57
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
58
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
59
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
60
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
21728 ashik.ali 61
import com.spice.profitmandi.dao.entity.dtr.Retailer;
62
import com.spice.profitmandi.dao.entity.dtr.User;
63
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
64
import com.spice.profitmandi.dao.entity.fofo.Customer;
65
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
21896 ashik.ali 66
import com.spice.profitmandi.dao.entity.fofo.FofoItemId;
21728 ashik.ali 67
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
68
import com.spice.profitmandi.dao.entity.fofo.FofoLineItemSerialNumber;
69
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
70
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
71
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
72
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
73
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
74
import com.spice.profitmandi.dao.entity.user.Address;
22354 ashik.ali 75
import com.spice.profitmandi.dao.entity.user.Counter;
76
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
21728 ashik.ali 77
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
21883 kshitij.so 78
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22217 ashik.ali 79
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
80
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
81
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
21728 ashik.ali 82
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
83
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
84
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
85
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
86
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
87
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
88
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
89
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
90
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemSerialNumberRepository;
91
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
92
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
93
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
94
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
95
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
96
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
97
import com.spice.profitmandi.dao.repository.user.AddressRepository;
22354 ashik.ali 98
import com.spice.profitmandi.dao.repository.user.CounterRepository;
99
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
22069 ashik.ali 100
import com.spice.profitmandi.service.pricing.PricingService;
22139 amit.gupta 101
import com.spice.profitmandi.web.model.LoginDetails;
21612 ashik.ali 102
import com.spice.profitmandi.web.request.CreateOrderRequest;
103
import com.spice.profitmandi.web.request.CustomPaymentOption;
21680 ashik.ali 104
import com.spice.profitmandi.web.response.ItemIdQuantityAvailability;
105
import com.spice.profitmandi.web.response.Quantity;
22069 ashik.ali 106
import com.spice.profitmandi.web.util.CookiesProcessor;
21612 ashik.ali 107
import com.spice.profitmandi.web.util.MVCResponseSender;
108
 
21985 kshitij.so 109
import in.shop2020.model.v1.catalog.ItemType;
110
 
21612 ashik.ali 111
@Controller
22037 amit.gupta 112
@Transactional(rollbackFor=Throwable.class)
21612 ashik.ali 113
public class OrderController {
114
 
115
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
21985 kshitij.so 116
 
21612 ashik.ali 117
	@Autowired
118
	OrderRepository orderRepository;
21985 kshitij.so 119
 
21612 ashik.ali 120
	@Autowired
121
	InventoryItemRepository inventoryItemRepository;
21985 kshitij.so 122
 
21612 ashik.ali 123
	@Autowired
21680 ashik.ali 124
	CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
21985 kshitij.so 125
 
21680 ashik.ali 126
	@Autowired
127
	InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
21985 kshitij.so 128
 
21680 ashik.ali 129
	@Autowired
130
	CustomerRepository customerRepository;
21985 kshitij.so 131
 
21680 ashik.ali 132
	@Autowired
133
	AddressRepository addressRepository;
21985 kshitij.so 134
 
21680 ashik.ali 135
	@Autowired
136
	FofoLineItemSerialNumberRepository fofoLineItemSerialNumberRepository;
21985 kshitij.so 137
 
21680 ashik.ali 138
	@Autowired
139
	FofoLineItemRepository fofoLineItemRepository;
21985 kshitij.so 140
 
21680 ashik.ali 141
	@Autowired
142
	PaymentOptionRepository paymentOptionRepository;
21985 kshitij.so 143
 
21680 ashik.ali 144
	@Autowired
145
	ScanRecordRepository scanRecordRepository;
21985 kshitij.so 146
 
21680 ashik.ali 147
	@Autowired
148
	FofoOrderRepository fofoOrderRepository;
21985 kshitij.so 149
 
21680 ashik.ali 150
	@Autowired
21689 ashik.ali 151
	RetailerRepository retailerRepository;
21985 kshitij.so 152
 
21689 ashik.ali 153
	@Autowired
154
	UserRepository userRepository;
21985 kshitij.so 155
 
21689 ashik.ali 156
	@Autowired
157
	UserAccountRepository userAccountRepository;
21985 kshitij.so 158
 
21689 ashik.ali 159
	@Autowired
160
	RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
21985 kshitij.so 161
 
21689 ashik.ali 162
	@Autowired
21711 ashik.ali 163
	CustomerAddressRepository customerAddressRepository;
21985 kshitij.so 164
 
21711 ashik.ali 165
	@Autowired
21896 ashik.ali 166
	ItemRepository itemRepository;
22217 ashik.ali 167
 
168
	@Autowired
169
	InsuranceProviderRepository insuranceProviderRepository;
170
 
171
	@Autowired
172
	InsurancePolicyRepository insurancePolicyRepository;
173
 
174
	@Autowired
175
	PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
21985 kshitij.so 176
 
21896 ashik.ali 177
	@Autowired
21612 ashik.ali 178
	MVCResponseSender mvcResponseSender;
21985 kshitij.so 179
 
21612 ashik.ali 180
	@Autowired
22069 ashik.ali 181
	CookiesProcessor cookiesProcessor;
182
 
183
	@Autowired
184
	PricingService pricingService;
22244 ashik.ali 185
 
22354 ashik.ali 186
	@Autowired
187
	PrivateDealUserRepository privateDealUserRepository;
22244 ashik.ali 188
 
189
	@Autowired
22354 ashik.ali 190
	CounterRepository counterRepository;
191
 
192
 
193
	@Autowired
22244 ashik.ali 194
	ResponseSender<?> responseSender;
21985 kshitij.so 195
 
196
	@RequestMapping(value = "/order")
197
	public String orderIndex(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model) throws Exception{
22244 ashik.ali 198
		LoginDetails loginDetails = null;
21985 kshitij.so 199
		try {
22244 ashik.ali 200
			loginDetails = cookiesProcessor.getCookiesObject(request);
21985 kshitij.so 201
		} catch (ProfitMandiBusinessException e) {
202
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
203
			return "response";
204
		}
22275 ashik.ali 205
		try{
206
			JSONObject cartObject = new JSONObject(cartData);
207
			Iterator<?> keys = cartObject.keys();
208
 
209
			Set<Integer> itemIds = new HashSet<>();
210
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
211
 
212
			while( keys.hasNext() ) {
213
				String key = (String)keys.next();
214
				if ( cartObject.get(key) instanceof JSONObject ) {
215
					System.out.println(cartObject.get(key));
216
				}
217
				CartFofo cf = new CartFofo();
218
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
219
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
220
 
221
				if (cf.getQuantity() <= 0){
222
					continue;
223
				}
224
				cartItems.add(cf);
225
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
21985 kshitij.so 226
			}
22275 ashik.ali 227
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
228
			if (itemIds.size() > 0){
229
				List<Item> items = itemRepository.selectByIds(itemIds);
230
				for (Item i : items){
231
					itemMap.put(i.getId(), i);
232
				}
233
 
21985 kshitij.so 234
			}
22275 ashik.ali 235
			for (CartFofo cf : cartItems){
236
				Item i = itemMap.get(cf.getItemId());
237
				if (i == null){
238
					continue;
239
				}
240
				cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
241
				cf.setItemType(i.getType());
21985 kshitij.so 242
			}
22275 ashik.ali 243
			Map<Integer, Float> mopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, loginDetails.getFofoId());
244
			LOGGER.info("mopPriceMap {}", mopPriceMap);
245
			model.addAttribute("cartObj", cartItems);
246
			model.addAttribute("mopPriceMap", mopPriceMap);
247
			return "order-index";
248
		}catch (Exception e) {
249
			LOGGER.error("Unable to Prepare cart to place order...", e);
250
			return "error";
21985 kshitij.so 251
		}
252
	}
253
 
254
	private String getValidName(String name){
255
		return name!=null?name:"";
256
	}
21612 ashik.ali 257
 
22244 ashik.ali 258
	@RequestMapping(value = "/insurancePrices", method = RequestMethod.GET)
259
	public ResponseEntity<?> getInsurancePrices(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.PRICE) float price){
260
		LOGGER.info("Request received at url : {}", request.getRequestURI());
261
		try{
262
			Set<Float> prices = new HashSet<>();
263
			prices.add(price);
264
			return responseSender.ok(pricingService.getInsurancePrices(prices, ProfitMandiConstants.GADGET_COPS));
265
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
266
			return responseSender.notFound(profitMandiBusinessException);
267
		}
268
	}
269
 
270
 
21985 kshitij.so 271
	@RequestMapping(value = "/get-order", method = RequestMethod.GET)
22244 ashik.ali 272
	public String getOrder(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException, Exception{
22139 amit.gupta 273
		LoginDetails fofoDetails;
21985 kshitij.so 274
		try {
22069 ashik.ali 275
			fofoDetails = cookiesProcessor.getCookiesObject(request);
21985 kshitij.so 276
		} catch (ProfitMandiBusinessException e) {
277
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
278
			return "response";
279
		}
22277 ashik.ali 280
		try{
281
			FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
282
			List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
283
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
284
			List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
285
			List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
286
			model.addAttribute("fofoOrder", fofoOrder);
287
			model.addAttribute("fofoLineItems", fofoLineItems);
288
			model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
289
			model.addAttribute("customerBillingAddressObj", customerAddress);
290
			model.addAttribute("paymentOptions", paymentOptions);
291
			model.addAttribute("insurancePolicies", insurancePolicies);
292
			return "order-details";
293
		}catch (Exception e) {
294
			LOGGER.error("Unable to get Order details...", e);
295
			return "error";
296
		}
21985 kshitij.so 297
	}
22244 ashik.ali 298
 
299
 
300
	@RequestMapping(value = "/saleDetails", method = RequestMethod.GET)
301
	public String getSaleDetails(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException, Exception{
302
		LoginDetails fofoDetails;
303
		try {
304
			fofoDetails = cookiesProcessor.getCookiesObject(request);
305
		} catch (ProfitMandiBusinessException e) {
306
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
307
			return "response";
308
		}
22279 ashik.ali 309
		try{
310
			FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
311
			List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
312
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
313
			List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
314
			List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
315
			model.addAttribute("fofoOrder", fofoOrder);
316
			model.addAttribute("fofoLineItems", fofoLineItems);
317
			model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
318
			model.addAttribute("customerBillingAddressObj", customerAddress);
319
			model.addAttribute("paymentOptions", paymentOptions);
320
			model.addAttribute("insurancePolicies", insurancePolicies);
321
			return "sale-details";
322
		}catch (Exception e) {
323
			LOGGER.error("Unble to fetch sale details... ", e);
324
			return "error";
325
		}
22244 ashik.ali 326
	}
327
 
328
 
21985 kshitij.so 329
 
22098 kshitij.so 330
	private String getBillingAddress(CustomerAddress customerAddress) {
331
		String address = "";
332
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
333
			address = address + customerAddress.getLine1();
334
			address = address + ", ";
335
		}
336
 
337
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
338
			address = address + customerAddress.getLine2();
339
			address = address + ", ";
340
		}
341
 
342
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
343
			address = address + customerAddress.getLandmark();
344
			address = address + ", ";
345
		}
346
 
347
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
348
			address = address + customerAddress.getCity();
349
			address = address + ", ";
350
		}
351
 
352
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
353
			address = address + customerAddress.getState();
354
		}
355
 
356
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
357
			address = address + "- " + customerAddress.getPinCode();
358
		}
359
 
360
		return address;
361
	}
362
 
21985 kshitij.so 363
	@RequestMapping(value = "/create-order", method = RequestMethod.POST)
364
	public String createOrder(HttpServletRequest request, @RequestBody CreateOrderRequest createOrderRequest, Model model)  throws Throwable{
22064 ashik.ali 365
		LOGGER.info("request at uri {} body {}", request.getRequestURI(), createOrderRequest);
22139 amit.gupta 366
		LoginDetails fofoDetails;
21985 kshitij.so 367
		try {
22069 ashik.ali 368
			fofoDetails = cookiesProcessor.getCookiesObject(request);
21985 kshitij.so 369
		} catch (ProfitMandiBusinessException e) {
370
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
371
			return "response";
372
		}
22280 ashik.ali 373
		Set<Integer> itemIds = new HashSet<>();
374
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
375
		Map<Integer, CustomFofoLineItem> customFofoLineItemMap = new HashMap<>();
376
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
377
		float totalAmount = 0;
378
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
379
			itemIds.add(customFofoLineItem.getItemId());
380
			if(!customFofoLineItem.getSerialNumberDetails().isEmpty() && customFofoLineItem.getQuantity() != customFofoLineItem.getSerialNumberDetails().size()){
381
				itemIdQuantity.put(customFofoLineItem.getItemId(), customFofoLineItem.getQuantity());
382
			}
383
			if(!(customFofoLineItem.getSellingPrice() > 0)){
384
				lineItemPrice.put(customFofoLineItem.getItemId(), customFofoLineItem.getSellingPrice());
385
			}else{
386
				totalAmount = totalAmount + customFofoLineItem.getSellingPrice() * customFofoLineItem.getQuantity();
387
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
388
					if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
389
						totalAmount = totalAmount + serialNumberDetail.getAmount();
22217 ashik.ali 390
					}
391
				}
21680 ashik.ali 392
			}
22280 ashik.ali 393
			customFofoLineItemMap.put(customFofoLineItem.getItemId(), customFofoLineItem);
394
		}
395
		if(!itemIdQuantity.isEmpty()){
396
			// if item quantity does not match with given serialnumbers size
397
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
398
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "");
399
			//return "error";
400
		}
401
		try{
402
			this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
403
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
404
			LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
405
			throw profitMandiBusinessException;
406
		}
407
		if(!lineItemPrice.isEmpty()){
408
			// given fofo line item price must be greater than zero
409
			LOGGER.error("requested itemId's selling price must greater than 0");
410
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "");
411
		}
412
 
413
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
414
		if(itemIds.size() != currentInventorySnapshots.size()){
415
			// error
416
		}
417
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
418
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
419
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
420
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(currentInventorySnapshot.getId().getItemId());
421
			LOGGER.info("customFofoLineItem "+customFofoLineItem);
422
			if(customFofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
423
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
424
				itemIdQuantityAvailability.setItemId(customFofoLineItem.getItemId());
425
				Quantity quantity = new Quantity();
426
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
427
				quantity.setRequested(customFofoLineItem.getQuantity());
428
				itemIdQuantityAvailability.setQuantity(quantity);
429
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
21896 ashik.ali 430
			}
22280 ashik.ali 431
 
432
		}
433
 
434
 
435
 
436
		if(!itemIdQuantityAvailabilities.isEmpty()){
437
			// itemIdQuantity request is not valid
438
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
439
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "");
440
		}
441
 
442
 
443
 
444
		//		Set<Integer> invalidItemIdSerialNumbers = new HashSet<>();
445
		//		Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>();
446
		//		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), itemIds); //change it
447
		//		
448
		//		Map<Integer, Float> itemIdPriceDropAmount = new HashMap<>();
449
		//		
450
		//		for(InventoryItem inventoryItem : inventoryItems){
451
		//			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(inventoryItem.getItemId());
452
		//			if(customFofoLineItem.getSerialNumbers().isEmpty()){
453
		//				if(!(inventoryItem.getSerialNumber() == null && inventoryItem.getSerialNumber().equals(""))){
454
		//					invalidItemIdSerialNumbers.add(inventoryItem.getItemId());
455
		//				}
456
		//			}
457
		//			if(!customFofoLineItem.getSerialNumbers().isEmpty()){
458
		//				if(!customFofoLineItem.getSerialNumbers().contains(inventoryItem.getSerialNumber())){
459
		//					if(!itemIdSerialNumbers.containsKey(customFofoLineItem.getItemId())){
460
		//						Set<String> serialNumbers = new HashSet<>();
461
		//						serialNumbers.add(inventoryItem.getSerialNumber());
462
		//						itemIdSerialNumbers.put(customFofoLineItem.getItemId(), serialNumbers);
463
		//					}else{
464
		//						itemIdSerialNumbers.get(customFofoLineItem.getItemId()).add(inventoryItem.getSerialNumber());
465
		//				}
466
		//			}
467
		//			itemIdPriceDropAmount.put(inventoryItem.getItemId(), inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
468
		//		}
469
 
470
		Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
471
		List<Item> items = itemRepository.selectByIds(itemIds);
472
		for (Item i : items){
473
			itemMap.put(i.getId(), i);
474
		}
475
 
476
		Set<Integer> nonSerializedItemIds = new HashSet<>();
477
		Set<String> serialNumbers = new HashSet<>();
478
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
479
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
480
		Map<String, String> serialNumberModelName = new HashMap<>();
481
		Map<String, String> serialNumberBrand = new HashMap<>();
482
		Collection<CustomFofoLineItem> lineItemsValues = customFofoLineItemMap.values();
483
		for (CustomFofoLineItem cli : lineItemsValues){
484
 
485
			Item item = itemMap.get(cli.getItemId());
486
			if (item.getType().equals(ItemType.SERIALIZED)){
487
				for (SerialNumberDetail serialNumberDetail : cli.getSerialNumberDetails()){
488
					serialNumbers.add(serialNumberDetail.getSerialNumber());
489
					if(serialNumberDetail.isInsurance()){
490
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), cli.getSellingPrice());
491
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
492
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(), item.getModelName());
493
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
494
					}
21680 ashik.ali 495
				}
496
			}
22280 ashik.ali 497
			else{
498
				nonSerializedItemIds.add(cli.getItemId());
22244 ashik.ali 499
			}
22280 ashik.ali 500
 
501
		}
502
 
503
 
504
		Map<Integer, List<InventoryItem>> serializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
505
		Map<Integer, List<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
506
		Map<Integer, List<Float>> itemIdPriceDropAmount = new HashMap<>();
507
 
508
		if (!serialNumbers.isEmpty()){
509
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoDetails.getFofoId(), serialNumbers);
510
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
511
			for (InventoryItem it : serializedInventoryItems){
512
				if (it.getGoodQuantity() == 1){
513
					if (serializedInventoryItemMap.containsKey(it.getItemId())){
514
						serializedInventoryItemMap.get(it.getItemId()).add(it);
515
						itemIdPriceDropAmount.get(it.getItemId()).
516
						add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
21985 kshitij.so 517
					}
22280 ashik.ali 518
					else{
519
						ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
520
						tmp.add(it);
521
						serializedInventoryItemMap.put(it.getItemId(), tmp);
522
						ArrayList<Float> priceDropAmouts = new ArrayList<>();
523
						priceDropAmouts.add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
524
						itemIdPriceDropAmount.put(it.getItemId(), priceDropAmouts);
525
					}
21985 kshitij.so 526
				}
527
			}
22280 ashik.ali 528
		}
529
 
530
		if (!nonSerializedItemIds.isEmpty()){
531
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), nonSerializedItemIds);
532
			for (InventoryItem it : nonSerializedInventoryItems){
533
				if (it.getGoodQuantity() > 0){
534
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
535
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
22244 ashik.ali 536
					}
22280 ashik.ali 537
					else{
538
						ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
539
						tmp.add(it);
540
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
541
					}
21985 kshitij.so 542
				}
543
			}
22280 ashik.ali 544
		}
545
 
546
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
547
		List<Integer> itemIdSerialNumbers = new ArrayList<Integer>();
548
 
549
		for (Item i : items){
550
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(i.getId());
551
			if (i.getType().equals(ItemType.SERIALIZED)){
552
				if (customFofoLineItem ==null || customFofoLineItem.getSerialNumberDetails().isEmpty()){
553
					invalidItemIdSerialNumbers.add(i.getId());
21985 kshitij.so 554
				}
555
			}
22280 ashik.ali 556
			else{
557
				if (customFofoLineItem == null || !customFofoLineItem.getSerialNumberDetails().isEmpty()){
558
					itemIdSerialNumbers.add(i.getId());
21985 kshitij.so 559
				}
22280 ashik.ali 560
			}
561
		}
562
 
563
		if(!invalidItemIdSerialNumbers.isEmpty()){
564
			LOGGER.error("Invalid itemId's serialNumbers {}", invalidItemIdSerialNumbers);
565
			// itemId's are serialized you are saying these are not serialized
566
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "");
567
		}
568
 
569
		if(!itemIdSerialNumbers.isEmpty()){
570
			LOGGER.error("Invalid itemId's serialNumbers {}", itemIdSerialNumbers);
571
			// itemId's are non serialized you are saying these are serialized
572
			throw new ProfitMandiBusinessException("itemIdSerialNumbers", itemIdSerialNumbers, "");
573
		}
574
 
575
		if(items.size() != itemIds.size()){
576
			LOGGER.error("Requested ItemIds not found in catalog");
577
			// invalid itemIds 
578
			throw new ProfitMandiBusinessException("invalidItemIds", "", "");
579
		}
580
 
581
		Map<Integer, List<InventoryItem>> inventoryItemsToBill = new HashMap<Integer,List<InventoryItem>>();
582
		Map<Integer, Integer> inventoryItemQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
583
 
584
		LOGGER.info("itemMap keys {}", itemMap.keySet());
585
		//Lets reduce quantity and decide what inventory items to use.
586
		for (Item i : items){
587
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(i.getId());
588
			if (i.getType().equals(ItemType.SERIALIZED)){
589
				//TODO:handle null
590
				if (serializedInventoryItemMap.get(i.getId()) == null || customFofoLineItem.getSerialNumberDetails().size() != serializedInventoryItemMap.get(i.getId()).size()){
591
					//not enough serial numbers
592
					//LOGGER.info("serialNumbers {}", serialNumbers);
593
					LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
594
					LOGGER.info("itemId {}", i.getId());
595
					LOGGER.error("not enough serial numbers");
596
					throw new ProfitMandiBusinessException("notEnoughSerialNumbers", "", "");
21985 kshitij.so 597
				}
22280 ashik.ali 598
				List<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(i.getId());
599
				for (InventoryItem it : inventoryItemsSerializedserialized){
600
					it.setGoodQuantity(0);
601
					inventoryItemQuantityUsed.put(it.getId(), 1);
602
				}
603
				inventoryItemsToBill.put(i.getId(), inventoryItemsSerializedserialized);
21985 kshitij.so 604
			}
22280 ashik.ali 605
			else{
606
				List<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(i.getId());
607
				int quantityToBill = customFofoLineItem.getQuantity();
608
				int totalLeft = quantityToBill;
609
				List<InventoryItem> inventoryItemsNonSerializedUsed = new ArrayList<InventoryItem>();
610
				if (inventoryItemsNonSerialized!=null){
611
					for (InventoryItem it : inventoryItemsNonSerialized){
612
						if (totalLeft > 0){
613
							int toUse = Math.min(totalLeft, it.getGoodQuantity());
614
							inventoryItemQuantityUsed.put(it.getId(), toUse);
615
							it.setGoodQuantity(it.getGoodQuantity()  - toUse);
616
							totalLeft = totalLeft - toUse;
617
							inventoryItemsNonSerializedUsed.add(it);
22244 ashik.ali 618
						}
619
					}
21896 ashik.ali 620
				}
22280 ashik.ali 621
 
622
				if (totalLeft > 0){
623
					//not enough quanity for non-serialized
624
					System.out.println("not enough quanity for non-serialized");
625
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", "", "");
626
				}
627
				inventoryItemsToBill.put(i.getId(), inventoryItemsNonSerializedUsed);
21896 ashik.ali 628
			}
22280 ashik.ali 629
		}
630
 
631
		// mop price validation
632
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
633
		Map<Integer, Float> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoDetails.getFofoId());
634
		for(Map.Entry<Integer, Float> entry : itemIdMopPriceMap.entrySet()){
635
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(entry.getKey());
636
			if(entry.getValue() < Float.MAX_VALUE && customFofoLineItem.getSellingPrice() < entry.getValue()){
637
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoLineItem.getSellingPrice());
638
			}
639
		}
640
 
641
		if(!invalidMopItemIdPriceMap.isEmpty()){
642
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
643
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "");
644
		}
645
 
646
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
647
		try{
648
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoDetails.getFofoId());
649
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
650
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
651
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
652
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
653
			invoiceNumberGenerationSequence.setFofoId(fofoDetails.getFofoId());
654
			invoiceNumberGenerationSequence.setPrefix("INVOICE");
655
			invoiceNumberGenerationSequence.setSequence(1);
656
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
657
		}
658
 
659
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
660
 
661
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
662
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
663
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "");
664
		}
665
 
666
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
667
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
668
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "");
669
		}
670
 
671
		boolean insurance = false;
672
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
673
			for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
674
				if(serialNumberDetail.getAmount() > 0){
675
					insurance = true;
676
					break;
22217 ashik.ali 677
				}
678
			}
22280 ashik.ali 679
		}
680
		LOGGER.info("insurance [{}] processing ....", insurance);
681
 
682
		LocalDate customerDateOfBirth = null;
683
		if(insurance){
22244 ashik.ali 684
			try{
22280 ashik.ali 685
				customerDateOfBirth = StringUtils.toDate(createOrderRequest.getCustomerDateOfBirth());
686
			}catch(DateTimeException dateTimeException){
687
				LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
688
				throw new ProfitMandiBusinessException("dateOfBirth", createOrderRequest.getCustomerDateOfBirth(), "");
22244 ashik.ali 689
			}
22280 ashik.ali 690
		}
691
 
692
		Customer customer = null;
693
		try{
694
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
695
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
696
			LOGGER.error("Error : ", profitMandiBusinessException);
697
			customer = new Customer();
698
			customer.setFirstName(customCustomer.getFirstName());
699
			customer.setLastName(customCustomer.getLastName());
700
			customer.setEmailId(customCustomer.getEmailId());
701
			customer.setMobileNumber(customCustomer.getMobileNumber());
702
			customerRepository.persist(customer);
703
		}
704
		//TODO:Check if createOrderRequest contains addressId
705
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress());
706
		customerAddress.setCustomerId(customer.getId());
707
		customerAddressRepository.persist(customerAddress);
708
 
709
		FofoOrder fofoOrder = new FofoOrder();
710
		fofoOrder.setCustomerId(customer.getId());
711
		fofoOrder.setFofoId(fofoDetails.getFofoId());
712
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
713
		fofoOrder.setTotalAmount(totalAmount);
714
		fofoOrder.setCustomerAddressId(customerAddress.getId());
715
		fofoOrderRepository.persist(fofoOrder);
716
 
717
		for(CustomPaymentOption customPaymentOption : createOrderRequest.getPaymentOptions()){
718
			PaymentOption paymentOption = new PaymentOption();
719
			paymentOption.setOrderId(fofoOrder.getId());
720
			paymentOption.setAmount(customPaymentOption.getAmount());
721
			paymentOption.setType(customPaymentOption.getType());
722
			paymentOptionRepository.persist(paymentOption);
723
		}
724
 
725
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoDetails.getFofoId()));
726
		Map<String, GstRate> gstRateMap = null;
727
		if(retailerAddress.getState().equals(customerAddress.getState())){
728
			gstRateMap = Utils.getGstRates(retailerAddress.getState());
729
		}else{
730
			LOGGER.info("inter gstRate = true");
731
			gstRateMap = Utils.getInterGstRates();
732
		}
733
		LOGGER.info("gstRateMap {}", gstRateMap);
734
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
735
			FofoLineItem fofoLineItem = new FofoLineItem();
736
			fofoLineItem.setItemId(customFofoLineItem.getItemId());
737
			fofoLineItem.setQuantity(customFofoLineItem.getQuantity());
738
			fofoLineItem.setSellingPrice(customFofoLineItem.getSellingPrice());
739
			fofoLineItem.setOrderId(fofoOrder.getId());
740
			fofoLineItem.setDp(customFofoLineItem.getSellingPrice());
741
			Item item = itemMap.get(customFofoLineItem.getItemId());
742
			GstRate gstRate = gstRateMap.get(item.getHsnCode());
743
			fofoLineItem.setIgstRate(gstRate.getIgstRate());
744
			fofoLineItem.setCgstRate(gstRate.getCgstRate());
745
			fofoLineItem.setSgstRate(gstRate.getSgstRate());
746
			fofoLineItem.setHsnCode(gstRate.getHsnCode());
747
			List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoLineItem.getItemId());
748
			float cost = 0;
749
			if (priceDropAmounts!=null){
750
				for (Float pda : priceDropAmounts){
751
					cost = cost + pda;
752
				}
22217 ashik.ali 753
			}
22280 ashik.ali 754
			else{
755
				cost = customFofoLineItem.getSellingPrice()* customFofoLineItem.getQuantity();
22244 ashik.ali 756
			}
22280 ashik.ali 757
			fofoLineItem.setCost(cost);
758
			fofoLineItem.setBrand(item.getBrand());
759
			fofoLineItem.setModelName(item.getModelName());
760
			fofoLineItem.setModelNumber(item.getModelNumber());
761
			fofoLineItem.setColor(item.getColor());
762
			fofoLineItemRepository.persist(fofoLineItem);
763
			LOGGER.info("\n\n");
764
			if(!customFofoLineItem.getSerialNumberDetails().isEmpty()){
22244 ashik.ali 765
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
22280 ashik.ali 766
					FofoLineItemSerialNumber fofoLineItemSerialNumber = new FofoLineItemSerialNumber();
767
					fofoLineItemSerialNumber.setFofoLineItemId(fofoLineItem.getId());
768
					fofoLineItemSerialNumber.setSerialNumber(serialNumberDetail.getSerialNumber());
769
					fofoLineItemSerialNumberRepository.persist(fofoLineItemSerialNumber);
22244 ashik.ali 770
				}
771
			}
22280 ashik.ali 772
 
773
			for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
774
				FofoItemId fofoItemId = new FofoItemId();
775
				fofoItemId.setFofoId(fofoDetails.getFofoId());
776
				fofoItemId.setItemId(fofoLineItem.getItemId());
777
				if(currentInventorySnapshot.getId().equals(fofoItemId)){
778
					currentInventorySnapshotRepository.updateAvailabilityByFofoItemId(fofoItemId, currentInventorySnapshot.getAvailability() - customFofoLineItem.getQuantity());
22217 ashik.ali 779
				}
780
			}
22280 ashik.ali 781
			List<InventoryItem> inventoryItems = inventoryItemsToBill.get(fofoLineItem.getItemId());
782
			for(InventoryItem inventoryItem : inventoryItems){
783
				inventoryItem.setLastScanType(ScanType.SALE);
784
				inventoryItemRepository.persist(inventoryItem);
785
				ScanRecord scanRecord = new ScanRecord();
786
				scanRecord.setInventoryItemId(inventoryItem.getId());
787
				scanRecord.setFofoId(fofoDetails.getFofoId());
788
				//correct this
789
				scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
790
				scanRecord.setType(ScanType.SALE);
791
				scanRecordRepository.persist(scanRecord);
792
			}
793
		}
794
 
795
		// insurance calculation is insurance flag is enabled
796
		if(!insuranceSerialNumberItemPrice.isEmpty()){
797
			LOGGER.info("Processing for insurence for serialNumbers");
798
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
799
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
22244 ashik.ali 800
 
22280 ashik.ali 801
 
802
			Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
803
			Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
804
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
805
				if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
806
					invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
22244 ashik.ali 807
				}
22280 ashik.ali 808
 
809
				if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
810
					invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
22244 ashik.ali 811
				}
812
			}
813
 
22280 ashik.ali 814
			// insurance sale amount can not be lesser than insurance purchase amount
815
			if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
816
				LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
817
				return "error";
818
			}
819
 
820
			if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
821
				LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
822
				return "error";
823
			}
824
 
825
 
826
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
827
				PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
828
				try{
829
					policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
830
					policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
831
					policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
832
				}catch(ProfitMandiBusinessException profitMandiBusinessException){
833
					policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
834
					policyNumberGenerationSequence.setSequence(1);
835
					policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
22244 ashik.ali 836
				}
837
 
22280 ashik.ali 838
				InsurancePolicy insurancePolicy = new InsurancePolicy();
839
				insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
840
				insurancePolicy.setRetailerId(fofoDetails.getFofoId());
841
				insurancePolicy.setPurchaseAmount(insurancePricesMap.get(entry.getValue()).getDealerPrice());
842
				insurancePolicy.setSaleAmount(insuranceSerialNumberSaleAmount.get(entry.getKey()));
843
				insurancePolicy.setSellingPrice(entry.getValue());
844
				insurancePolicy.setSerialNumber(entry.getKey());
845
				insurancePolicy.setModelName(serialNumberModelName.get(entry.getKey()));
846
				insurancePolicy.setBrand(serialNumberBrand.get(entry.getKey()));
847
				insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence.getSequence()));
848
				insurancePolicy.setProviderId(insuranceProvider.getId());
849
				insurancePolicy.setCustomerFirstName(customer.getFirstName());
850
				insurancePolicy.setCustomerLastName(customer.getLastName());
851
				insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
852
				insurancePolicy.setCustomerEmailId(customer.getEmailId());
853
				insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
854
				insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
855
				insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
856
				insurancePolicy.setCustomerCity(customerAddress.getCity());
857
				insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
858
				insurancePolicy.setCustomerState(customerAddress.getState());
22244 ashik.ali 859
 
22280 ashik.ali 860
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
861
				gadgetCopsInsuranceModel.setBrand(serialNumberBrand.get(entry.getKey()));
862
				gadgetCopsInsuranceModel.setModelName(serialNumberModelName.get(entry.getKey()));
863
				gadgetCopsInsuranceModel.setSerialNumber(entry.getKey());
864
				gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
865
				gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
866
				gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
867
				gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
868
				gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
869
				gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
870
				gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
871
				gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
872
				gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
873
				gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
874
				gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
875
				gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
876
				gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
22244 ashik.ali 877
 
22280 ashik.ali 878
				try{
879
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
880
					insurancePolicy.setPosted(true);
881
				}catch (ProfitMandiBusinessException profitMandiBusinessException) {
882
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
22244 ashik.ali 883
				}
22280 ashik.ali 884
				insurancePolicyRepository.persist(insurancePolicy);
22244 ashik.ali 885
			}
22217 ashik.ali 886
		}
22280 ashik.ali 887
		LOGGER.info("Order has been created successfully...");
888
		return "redirect:/get-order/?orderId="+fofoOrder.getId();
21612 ashik.ali 889
	}
21985 kshitij.so 890
 
21711 ashik.ali 891
	private CustomerAddress createCustomerAddress(CustomAddress customAddress){
892
		CustomerAddress customerAddress = new CustomerAddress();
893
		customerAddress.setName(customAddress.getName());
894
		customerAddress.setLine1(customAddress.getLine1());
895
		customerAddress.setLine2(customAddress.getLine2());
896
		customerAddress.setLandmark(customAddress.getLandmark());
897
		customerAddress.setCity(customAddress.getCity());
898
		customerAddress.setPinCode(customAddress.getPinCode());
899
		customerAddress.setState(customAddress.getState());
900
		customerAddress.setCountry(customAddress.getCountry());
901
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
902
		return customerAddress;
21680 ashik.ali 903
	}
21985 kshitij.so 904
 
21689 ashik.ali 905
	private CustomAddress createCustomAddress(Address address){
906
		CustomAddress customAddress = new CustomAddress();
907
		customAddress.setName(address.getName());
908
		customAddress.setLine1(address.getLine1());
909
		customAddress.setLine2(address.getLine2());
910
		customAddress.setLandmark(address.getLandmark());
911
		customAddress.setCity(address.getCity());
912
		customAddress.setPinCode(address.getPinCode());
913
		customAddress.setState(address.getState());
914
		customAddress.setCountry(address.getCountry());
915
		customAddress.setPhoneNumber(address.getPhoneNumber());
916
		return customAddress;
21680 ashik.ali 917
	}
21985 kshitij.so 918
 
21711 ashik.ali 919
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
920
		CustomAddress customAddress = new CustomAddress();
921
		customAddress.setName(customerAddress.getName());
922
		customAddress.setLine1(customerAddress.getLine1());
923
		customAddress.setLine2(customerAddress.getLine2());
924
		customAddress.setLandmark(customerAddress.getLandmark());
925
		customAddress.setCity(customerAddress.getCity());
926
		customAddress.setPinCode(customerAddress.getPinCode());
927
		customAddress.setState(customerAddress.getState());
928
		customAddress.setCountry(customerAddress.getCountry());
929
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
930
		return customAddress;
931
	}
21985 kshitij.so 932
 
21680 ashik.ali 933
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
21612 ashik.ali 934
	{
935
		float calculatedAmount = 0;
936
		Set<String> paymentOptionTypes = new HashSet<>();
937
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
21680 ashik.ali 938
			if(paymentOptionTypes.contains(customPaymentOption.getType().name())){
21612 ashik.ali 939
				throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType().name(), "");
21680 ashik.ali 940
			}else{
941
				paymentOptionTypes.add(customPaymentOption.getType().name());
942
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
21612 ashik.ali 943
			}
944
		}
945
		if(calculatedAmount != totalAmount){
22244 ashik.ali 946
			LOGGER.error("PaymentOptionCalculatedAmount [{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
21612 ashik.ali 947
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "");
948
		}
949
	}
21985 kshitij.so 950
 
951
 
21689 ashik.ali 952
	@RequestMapping(value = "/generateInvoice")
21896 ashik.ali 953
	public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws Throwable{
22064 ashik.ali 954
		LOGGER.info("Request received at url {} with params [{}={}] ", request.getRequestURI(), ProfitMandiConstants.ORDER_ID, orderId);
22139 amit.gupta 955
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
22217 ashik.ali 956
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
22026 ashik.ali 957
 
21689 ashik.ali 958
		PdfModel pdfModel = new PdfModel();
959
		pdfModel.setAuther("profitmandi");
960
		pdfModel.setTitle("Retailer Invoice");
22217 ashik.ali 961
 
962
		// insurance calculation
963
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
964
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
965
		final float totalInsuranceTaxRate = 18;
966
		for(InsurancePolicy insurancePolicy : insurancePolicies){
967
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
968
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
22244 ashik.ali 969
			customInsurancePolicy.setDescription(insurancePolicy.getInsuranceProvider().getName() + " Protection (" + insurancePolicy.getSerialNumber() + ")");
22217 ashik.ali 970
			customInsurancePolicy.setHsnCode("");
971
			customInsurancePolicy.setRate(taxableInsurancePrice);
972
			customInsurancePolicy.setIgstRate(18);
973
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
974
			customInsurancePolicy.setCgstRate(18);
975
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 /100);
976
			customInsurancePolicy.setSgstRate(9);
977
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 /100);
978
			customInsurancePolicies.add(customInsurancePolicy);
979
		}
980
		pdfModel.setInsurancePolicies(customInsurancePolicies);
21689 ashik.ali 981
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
982
		CustomCustomer customCustomer = new CustomCustomer();
22217 ashik.ali 983
		customCustomer.setFirstName(customer.getFirstName());
984
		customCustomer.setLastName(customer.getLastName());
21689 ashik.ali 985
		customCustomer.setEmailId(customer.getEmailId());
986
		customCustomer.setMobileNumber(customer.getMobileNumber());
21711 ashik.ali 987
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
21689 ashik.ali 988
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
989
		pdfModel.setCustomer(customCustomer);
990
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
22244 ashik.ali 991
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
22026 ashik.ali 992
 
21689 ashik.ali 993
		Retailer retailer = retailerRepository.selectById(fofoDetails.getFofoId());
22354 ashik.ali 994
		PrivateDealUser privateDealUser = privateDealUserRepository.selectById(retailer.getId());
995
 
21689 ashik.ali 996
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
997
		CustomRetailer customRetailer = new CustomRetailer();
998
		customRetailer.setBusinessName(retailer.getName());
999
		customRetailer.setMobileNumber(user.getMobileNumber());
1000
		customRetailer.setTinNumber(retailer.getNumber());
22354 ashik.ali 1001
		if(privateDealUser.getCounterId() != null){
1002
			Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
1003
			customRetailer.setGstNumber(counter.getGstin());
1004
		}
21689 ashik.ali 1005
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
1006
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
1007
		pdfModel.setRetailer(customRetailer);
1008
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
22026 ashik.ali 1009
 
21689 ashik.ali 1010
		Set<CustomFofoOrderItem> customerFofoOrderItems = new HashSet<>();
1011
		for(FofoLineItem fofoLineItem : fofoLineItems){
1012
			CustomFofoOrderItem customFofoOrderItem = new CustomFofoOrderItem();
22026 ashik.ali 1013
			float totalTaxRate = fofoLineItem.getIgstRate() + fofoLineItem.getSgstRate() + fofoLineItem.getCgstRate();
1014
			float taxableSellingPrice = fofoLineItem.getSellingPrice() / (1 + totalTaxRate / 100);
1015
 
1016
			customFofoOrderItem.setAmount(fofoLineItem.getQuantity() * taxableSellingPrice);
22354 ashik.ali 1017
			customFofoOrderItem.setDescription(fofoLineItem.getBrand() + " " + fofoLineItem.getModelName() + " " + fofoLineItem.getModelNumber() + " " + fofoLineItem.getColor() + " (" + String.join(", ",this.toSerialNumbers(fofoLineItem.getFofoLineItemSerialNumbers())) + ")");
22026 ashik.ali 1018
			customFofoOrderItem.setRate(taxableSellingPrice);
21689 ashik.ali 1019
			customFofoOrderItem.setQuantity(fofoLineItem.getQuantity());
22026 ashik.ali 1020
			float igstAmount = (customFofoOrderItem.getAmount() * fofoLineItem.getIgstRate()) / 100;
1021
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoLineItem.getCgstRate()) / 100;
1022
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoLineItem.getSgstRate()) / 100;
21896 ashik.ali 1023
			customFofoOrderItem.setIgstRate(fofoLineItem.getIgstRate());
22026 ashik.ali 1024
			customFofoOrderItem.setIgstAmount(igstAmount);
1025
			customFofoOrderItem.setCgstRate(fofoLineItem.getCgstRate());
1026
			customFofoOrderItem.setCgstAmount(cgstAmount);
1027
			customFofoOrderItem.setSgstRate(fofoLineItem.getSgstRate());
1028
			customFofoOrderItem.setSgstAmount(sgstAmount);
21896 ashik.ali 1029
			customFofoOrderItem.setHsnCode(fofoLineItem.getHsnCode());
21689 ashik.ali 1030
			customerFofoOrderItems.add(customFofoOrderItem);
1031
		}
1032
		pdfModel.setOrderItems(customerFofoOrderItems);
1033
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1034
		PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
1035
		//final MediaType mediaType=MediaType.parseMediaType(profilePhotoModel.getContentType().getValue());
1036
		LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
22026 ashik.ali 1037
        final HttpHeaders headers=new HttpHeaders();
1038
        headers.setContentType(MediaType.APPLICATION_PDF);
22099 kshitij.so 1039
        headers.set("Content-disposition", "inline; filename=invoice-" + fofoOrder.getInvoiceNumber() + ".pdf");
22026 ashik.ali 1040
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1041
        final InputStream inputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1042
        final InputStreamResource inputStreamResource=new InputStreamResource(inputStream);
1043
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
21689 ashik.ali 1044
	}
21985 kshitij.so 1045
 
21689 ashik.ali 1046
	private Set<String> toSerialNumbers(Set<FofoLineItemSerialNumber> fofoLineItemSerialNumbers){
1047
		Set<String> serialNumbers = new HashSet<>(fofoLineItemSerialNumbers.size());
1048
		for(FofoLineItemSerialNumber fofoLineItemSerialNumber : fofoLineItemSerialNumbers){
1049
			serialNumbers.add(fofoLineItemSerialNumber.getSerialNumber());
1050
		}
1051
		return serialNumbers;
1052
	}
22244 ashik.ali 1053
 
1054
	@RequestMapping(value = "/saleHistory")
1055
	public String saleHistory(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = ProfitMandiConstants.INVOICE_NUMBER, defaultValue = "") String invoiceNumber, @RequestParam(name = "searchType",defaultValue="") String searchType, Model model) throws Exception{
1056
		LoginDetails loginDetails = null;
1057
		try {
1058
			loginDetails = cookiesProcessor.getCookiesObject(request);
1059
		} catch (ProfitMandiBusinessException e) {
1060
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
1061
			return "response";
1062
		}
1063
 
1064
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
1065
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
1066
		long countItems = 0;
1067
		List<FofoOrder> fofoOrders = new ArrayList<>();
22284 ashik.ali 1068
		if(searchType.equalsIgnoreCase(ProfitMandiConstants.INVOICE_NUMBER) && !invoiceNumber.isEmpty()){
22244 ashik.ali 1069
			try {
1070
				FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndInvoiceNumber(loginDetails.getFofoId(), invoiceNumber);
1071
				fofoOrders.add(fofoOrder);
1072
			} catch (ProfitMandiBusinessException e) {
1073
				LOGGER.info("Sale history not found : ", e);
1074
			}
1075
		}else{
1076
			fofoOrders = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(),startDateTime, endDateTime, offset, limit);
1077
			countItems = fofoOrderRepository.selectCount(loginDetails.getFofoId(), startDateTime, endDateTime, invoiceNumber, searchType);
1078
		}
1079
 
1080
		model.addAttribute("saleHistories", fofoOrders);
1081
		model.addAttribute("start",offset+1);
1082
		model.addAttribute("size",countItems);
1083
		model.addAttribute("searchType",searchType);
1084
		model.addAttribute(ProfitMandiConstants.START_TIME, startTimeString);
1085
		model.addAttribute(ProfitMandiConstants.END_TIME, endTimeString);
1086
		if (fofoOrders.size() < limit){
1087
			model.addAttribute("end",offset + fofoOrders.size());
1088
		}
1089
		else{
1090
			model.addAttribute("end",offset+limit);
1091
		}
1092
 
1093
		return "sale-history";
1094
	}
22291 ashik.ali 1095
 
1096
 
1097
	@RequestMapping(value = "/getPaginatedSaleHistory")
1098
	public String getSaleHistoryPaginated(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue="10") int limit, @RequestParam(name = ProfitMandiConstants.INVOICE_NUMBER, defaultValue="") String invoiceNumber, @RequestParam(name = "searchType", defaultValue = "") String searchType, Model model) throws Exception{
1099
		LoginDetails loginDetails;
1100
		try {
1101
			loginDetails = cookiesProcessor.getCookiesObject(request);
1102
		} catch (ProfitMandiBusinessException e) {
1103
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
1104
			return "response";
1105
		}
1106
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
1107
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
21985 kshitij.so 1108
 
22291 ashik.ali 1109
		List<FofoOrder> saleHistories = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
1110
		model.addAttribute("saleHistories", saleHistories);
1111
		return "sale-history-paginated";
1112
	}
1113
 
21612 ashik.ali 1114
}