Subversion Repositories SmartDukaan

Rev

Rev 22217 | Rev 22250 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 22217 Rev 22244
Line 3... Line 3...
3
import java.io.ByteArrayInputStream;
3
import java.io.ByteArrayInputStream;
4
import java.io.ByteArrayOutputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.InputStream;
5
import java.io.InputStream;
6
import java.time.DateTimeException;
6
import java.time.DateTimeException;
7
import java.time.LocalDate;
7
import java.time.LocalDate;
-
 
8
import java.time.LocalDateTime;
8
import java.util.ArrayList;
9
import java.util.ArrayList;
9
import java.util.Collection;
10
import java.util.Collection;
10
import java.util.HashMap;
11
import java.util.HashMap;
11
import java.util.HashSet;
12
import java.util.HashSet;
12
import java.util.Iterator;
13
import java.util.Iterator;
Line 49... Line 50...
49
import com.spice.profitmandi.common.model.SerialNumberDetail;
50
import com.spice.profitmandi.common.model.SerialNumberDetail;
50
import com.spice.profitmandi.common.util.InsuranceUtils;
51
import com.spice.profitmandi.common.util.InsuranceUtils;
51
import com.spice.profitmandi.common.util.PdfUtils;
52
import com.spice.profitmandi.common.util.PdfUtils;
52
import com.spice.profitmandi.common.util.StringUtils;
53
import com.spice.profitmandi.common.util.StringUtils;
53
import com.spice.profitmandi.common.util.Utils;
54
import com.spice.profitmandi.common.util.Utils;
-
 
55
import com.spice.profitmandi.common.web.util.ResponseSender;
54
import com.spice.profitmandi.dao.entity.catalog.Item;
56
import com.spice.profitmandi.dao.entity.catalog.Item;
55
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
57
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
56
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
58
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
57
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
59
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
58
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
60
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
Line 174... Line 176...
174
	@Autowired
176
	@Autowired
175
	CookiesProcessor cookiesProcessor;
177
	CookiesProcessor cookiesProcessor;
176
	
178
	
177
	@Autowired
179
	@Autowired
178
	PricingService pricingService;
180
	PricingService pricingService;
-
 
181
	
-
 
182
	
-
 
183
	@Autowired
-
 
184
	ResponseSender<?> responseSender;
179
 
185
 
180
	@RequestMapping(value = "/order")
186
	@RequestMapping(value = "/order")
181
	public String orderIndex(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model) throws Exception{
187
	public String orderIndex(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model) throws Exception{
-
 
188
		LoginDetails loginDetails = null;
182
		try {
189
		try {
183
			cookiesProcessor.getCookiesObject(request);
190
			loginDetails = cookiesProcessor.getCookiesObject(request);
184
		} catch (ProfitMandiBusinessException e) {
191
		} catch (ProfitMandiBusinessException e) {
185
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
192
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
186
			return "response";
193
			return "response";
187
		}
194
		}
188
		JSONObject cartObject = new JSONObject(cartData);
195
		JSONObject cartObject = new JSONObject(cartData);
Line 205... Line 212...
205
			}
212
			}
206
			cartItems.add(cf);
213
			cartItems.add(cf);
207
			itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
214
			itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
208
		}
215
		}
209
		Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
216
		Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
210
		Set<Float> prices = new HashSet<>();
-
 
211
		Map<Float, GadgetCopsInsuranceCalc> insurancePriceMap = new HashMap<>();
-
 
212
		Map<Integer, GadgetCopsInsuranceCalc> itemIdInsurancePrice = new HashMap<>();
-
 
213
		if (itemIds.size() > 0){
217
		if (itemIds.size() > 0){
214
			List<Item> items = itemRepository.selectByIds(itemIds);
218
			List<Item> items = itemRepository.selectByIds(itemIds);
215
			for (Item i : items){
219
			for (Item i : items){
216
				itemMap.put(i.getId(), i);
220
				itemMap.put(i.getId(), i);
217
				prices.add(i.getSellingPrice());
-
 
218
			}
-
 
219
			try{
-
 
220
				insurancePriceMap = pricingService.getInsurancePrices(prices, ProfitMandiConstants.GADGET_COPS);
-
 
221
			}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
222
				LOGGER.error("Insurance Provider not found : ", profitMandiBusinessException);
-
 
223
				return "error";
-
 
224
			}
-
 
225
			for(Item item : items){
-
 
226
				itemIdInsurancePrice.put(item.getId(), insurancePriceMap.get(item.getSellingPrice()));
-
 
227
			}
221
			}
-
 
222
			
228
		}
223
		}
229
		for (CartFofo cf : cartItems){
224
		for (CartFofo cf : cartItems){
230
			Item i = itemMap.get(cf.getItemId());
225
			Item i = itemMap.get(cf.getItemId());
231
			if (i == null){
226
			if (i == null){
232
				continue;
227
				continue;
233
			}
228
			}
234
			cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
229
			cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
235
			cf.setItemType(i.getType());
230
			cf.setItemType(i.getType());
236
		}
231
		}
237
		
-
 
238
		
-
 
239
		
-
 
240
		
-
 
-
 
232
		Map<Integer, Float> mopPriceMap = pricingService.getPrivateDealPriceMopPriceNotFound(itemIds, loginDetails.getFofoId());
241
		model.addAttribute("cartObj", cartItems);
233
		model.addAttribute("cartObj", cartItems);
242
		model.addAttribute("itemIdInsurancePrice", itemIdInsurancePrice);
234
		model.addAttribute("mopPriceMap", mopPriceMap);
243
		return "order-index";
235
		return "order-index";
244
	}
236
	}
245
 
237
 
246
	private String getValidName(String name){
238
	private String getValidName(String name){
247
		return name!=null?name:"";
239
		return name!=null?name:"";
248
	}
240
	}
249
	
241
	
-
 
242
	@RequestMapping(value = "/insurancePrices", method = RequestMethod.GET)
-
 
243
	public ResponseEntity<?> getInsurancePrices(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.PRICE) float price){
-
 
244
		LOGGER.info("Request received at url : {}", request.getRequestURI());
-
 
245
		try{
-
 
246
			Set<Float> prices = new HashSet<>();
-
 
247
			prices.add(price);
-
 
248
			return responseSender.ok(pricingService.getInsurancePrices(prices, ProfitMandiConstants.GADGET_COPS));
-
 
249
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
250
			return responseSender.notFound(profitMandiBusinessException);
-
 
251
		}
-
 
252
	}
-
 
253
	
-
 
254
	
250
	@RequestMapping(value = "/get-order", method = RequestMethod.GET)
255
	@RequestMapping(value = "/get-order", method = RequestMethod.GET)
251
	public String getOrder(HttpServletRequest request, @RequestParam(name = "orderId") int orderId, Model model) throws ProfitMandiBusinessException, Exception{
256
	public String getOrder(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException, Exception{
252
		LoginDetails fofoDetails;
257
		LoginDetails fofoDetails;
253
		try {
258
		try {
254
			fofoDetails = cookiesProcessor.getCookiesObject(request);
259
			fofoDetails = cookiesProcessor.getCookiesObject(request);
255
		} catch (ProfitMandiBusinessException e) {
260
		} catch (ProfitMandiBusinessException e) {
256
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
261
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
Line 258... Line 263...
258
		}
263
		}
259
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
264
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
260
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
265
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
261
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
266
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
262
		List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
267
		List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
-
 
268
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
263
		model.addAttribute("fofoOrder", fofoOrder);
269
		model.addAttribute("fofoOrder", fofoOrder);
264
		model.addAttribute("fofoLineItems", fofoLineItems);
270
		model.addAttribute("fofoLineItems", fofoLineItems);
265
		model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
271
		model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
266
		model.addAttribute("customerBillingAddressObj", customerAddress);
272
		model.addAttribute("customerBillingAddressObj", customerAddress);
267
		model.addAttribute("paymentOptions", paymentOptions);
273
		model.addAttribute("paymentOptions", paymentOptions);
-
 
274
		model.addAttribute("insurancePolicies", insurancePolicies);
268
		return "order-details";
275
		return "order-details";
269
	}
276
	}
-
 
277
	
-
 
278
	
-
 
279
	@RequestMapping(value = "/saleDetails", method = RequestMethod.GET)
-
 
280
	public String getSaleDetails(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException, Exception{
-
 
281
		LoginDetails fofoDetails;
-
 
282
		try {
-
 
283
			fofoDetails = cookiesProcessor.getCookiesObject(request);
-
 
284
		} catch (ProfitMandiBusinessException e) {
-
 
285
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
-
 
286
			return "response";
-
 
287
		}
-
 
288
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
-
 
289
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
-
 
290
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
-
 
291
		List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
-
 
292
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
-
 
293
		model.addAttribute("fofoOrder", fofoOrder);
-
 
294
		model.addAttribute("fofoLineItems", fofoLineItems);
-
 
295
		model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
-
 
296
		model.addAttribute("customerBillingAddressObj", customerAddress);
-
 
297
		model.addAttribute("paymentOptions", paymentOptions);
-
 
298
		model.addAttribute("insurancePolicies", insurancePolicies);
-
 
299
		return "sale-details";
-
 
300
	}
-
 
301
	
-
 
302
	
270
 
303
 
271
	private String getBillingAddress(CustomerAddress customerAddress) {
304
	private String getBillingAddress(CustomerAddress customerAddress) {
272
		String address = "";
305
		String address = "";
273
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
306
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
274
			address = address + customerAddress.getLine1();
307
			address = address + customerAddress.getLine1();
Line 309... Line 342...
309
			fofoDetails = cookiesProcessor.getCookiesObject(request);
342
			fofoDetails = cookiesProcessor.getCookiesObject(request);
310
		} catch (ProfitMandiBusinessException e) {
343
		} catch (ProfitMandiBusinessException e) {
311
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
344
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
312
			return "response";
345
			return "response";
313
		}
346
		}
-
 
347
		try{
314
		Set<Integer> itemIds = new HashSet<>();
348
			Set<Integer> itemIds = new HashSet<>();
315
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
349
			Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
316
		Map<Integer, CustomFofoLineItem> customFofoLineItemMap = new HashMap<>();
350
			Map<Integer, CustomFofoLineItem> customFofoLineItemMap = new HashMap<>();
317
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
351
			Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
318
		float totalAmount = 0;
352
			float totalAmount = 0;
319
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
353
			for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
320
			itemIds.add(customFofoLineItem.getItemId());
354
				itemIds.add(customFofoLineItem.getItemId());
321
			if(!customFofoLineItem.getSerialNumberDetails().isEmpty() && customFofoLineItem.getQuantity() != customFofoLineItem.getSerialNumberDetails().size()){
355
				if(!customFofoLineItem.getSerialNumberDetails().isEmpty() && customFofoLineItem.getQuantity() != customFofoLineItem.getSerialNumberDetails().size()){
322
				itemIdQuantity.put(customFofoLineItem.getItemId(), customFofoLineItem.getQuantity());
356
					itemIdQuantity.put(customFofoLineItem.getItemId(), customFofoLineItem.getQuantity());
323
			}
357
				}
324
			if(!(customFofoLineItem.getSellingPrice() > 0)){
358
				if(!(customFofoLineItem.getSellingPrice() > 0)){
325
				lineItemPrice.put(customFofoLineItem.getItemId(), customFofoLineItem.getSellingPrice());
359
					lineItemPrice.put(customFofoLineItem.getItemId(), customFofoLineItem.getSellingPrice());
326
			}else{
360
				}else{
327
				totalAmount = totalAmount + customFofoLineItem.getSellingPrice() * customFofoLineItem.getQuantity();
361
					totalAmount = totalAmount + customFofoLineItem.getSellingPrice() * customFofoLineItem.getQuantity();
328
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
362
					for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
329
					if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
363
						if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
330
						totalAmount = totalAmount + serialNumberDetail.getAmount();
364
							totalAmount = totalAmount + serialNumberDetail.getAmount();
-
 
365
						}
331
					}
366
					}
332
				}
367
				}
-
 
368
				customFofoLineItemMap.put(customFofoLineItem.getItemId(), customFofoLineItem);
333
			}
369
			}
334
			customFofoLineItemMap.put(customFofoLineItem.getItemId(), customFofoLineItem);
-
 
335
		}
-
 
336
		if(!itemIdQuantity.isEmpty()){
370
			if(!itemIdQuantity.isEmpty()){
337
			// if item quantity does not match with given serialnumbers size
371
				// if item quantity does not match with given serialnumbers size
338
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
372
				LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
339
			return "error";
-
 
340
		}
-
 
341
		try{
-
 
342
			this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
-
 
343
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
344
			LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
-
 
345
			return "error";
-
 
346
		}
-
 
347
		if(!lineItemPrice.isEmpty()){
-
 
348
			// given fofo line item price must be greater than zero
-
 
349
			LOGGER.error("requested itemId's selling price must greater than 0");
-
 
350
			return "error";
373
				return "error";
351
		}
-
 
352
 
-
 
353
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
-
 
354
		if(itemIds.size() != currentInventorySnapshots.size()){
-
 
355
			// error
-
 
356
		}
-
 
357
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
-
 
358
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
-
 
359
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
-
 
360
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(currentInventorySnapshot.getId().getItemId());
-
 
361
			LOGGER.info("customFofoLineItem "+customFofoLineItem);
-
 
362
			if(customFofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
-
 
363
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
-
 
364
				itemIdQuantityAvailability.setItemId(customFofoLineItem.getItemId());
-
 
365
				Quantity quantity = new Quantity();
-
 
366
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
-
 
367
				quantity.setRequested(customFofoLineItem.getQuantity());
-
 
368
				itemIdQuantityAvailability.setQuantity(quantity);
-
 
369
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
-
 
370
			}
374
			}
371
 
-
 
372
		}
375
			try{
373
 
-
 
374
 
-
 
375
 
-
 
376
		if(!itemIdQuantityAvailabilities.isEmpty()){
376
				this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
377
			// itemIdQuantity request is not valid
377
			}catch(ProfitMandiBusinessException profitMandiBusinessException){
378
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
378
				LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
379
			return "error";
379
				return "error";
380
		}
380
			}
381
 
-
 
382
 
-
 
383
 
-
 
384
		//		Set<Integer> invalidItemIdSerialNumbers = new HashSet<>();
-
 
385
		//		Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>();
-
 
386
		//		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), itemIds); //change it
-
 
387
		//		
-
 
388
		//		Map<Integer, Float> itemIdPriceDropAmount = new HashMap<>();
-
 
389
		//		
-
 
390
		//		for(InventoryItem inventoryItem : inventoryItems){
-
 
391
		//			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(inventoryItem.getItemId());
-
 
392
		//			if(customFofoLineItem.getSerialNumbers().isEmpty()){
381
			if(!lineItemPrice.isEmpty()){
393
		//				if(!(inventoryItem.getSerialNumber() == null && inventoryItem.getSerialNumber().equals(""))){
-
 
394
		//					invalidItemIdSerialNumbers.add(inventoryItem.getItemId());
-
 
395
		//				}
-
 
396
		//			}
-
 
397
		//			if(!customFofoLineItem.getSerialNumbers().isEmpty()){
382
				// given fofo line item price must be greater than zero
398
		//				if(!customFofoLineItem.getSerialNumbers().contains(inventoryItem.getSerialNumber())){
-
 
399
		//					if(!itemIdSerialNumbers.containsKey(customFofoLineItem.getItemId())){
-
 
400
		//						Set<String> serialNumbers = new HashSet<>();
-
 
401
		//						serialNumbers.add(inventoryItem.getSerialNumber());
383
				LOGGER.error("requested itemId's selling price must greater than 0");
402
		//						itemIdSerialNumbers.put(customFofoLineItem.getItemId(), serialNumbers);
-
 
403
		//					}else{
384
				return "error";
404
		//						itemIdSerialNumbers.get(customFofoLineItem.getItemId()).add(inventoryItem.getSerialNumber());
-
 
405
		//				}
-
 
406
		//			}
-
 
407
		//			itemIdPriceDropAmount.put(inventoryItem.getItemId(), inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
-
 
408
		//		}
385
			}
409
 
386
	
410
		Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
387
			List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
411
		List<Item> items = itemRepository.selectByIds(itemIds);
388
			if(itemIds.size() != currentInventorySnapshots.size()){
412
		for (Item i : items){
389
				// error
413
			itemMap.put(i.getId(), i);
-
 
414
		}
390
			}
415
 
-
 
416
		Set<Integer> nonSerializedItemIds = new HashSet<>();
391
			List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
417
		Set<String> serialNumbers = new HashSet<>();
-
 
418
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
392
			LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
419
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
393
			for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
420
		Map<String, String> serialNumberModelName = new HashMap<>();
-
 
421
		Map<String, String> serialNumberBrand = new HashMap<>();
-
 
422
		Collection<CustomFofoLineItem> lineItemsValues = customFofoLineItemMap.values();
394
				CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(currentInventorySnapshot.getId().getItemId());
423
		for (CustomFofoLineItem cli : lineItemsValues){
395
				LOGGER.info("customFofoLineItem "+customFofoLineItem);
424
 
-
 
425
			Item item = itemMap.get(cli.getItemId());
-
 
426
			if (item.getType().equals(ItemType.SERIALIZED)){
396
				if(customFofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
427
				for (SerialNumberDetail serialNumberDetail : cli.getSerialNumberDetails()){
397
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
428
					serialNumbers.add(serialNumberDetail.getSerialNumber());
398
					itemIdQuantityAvailability.setItemId(customFofoLineItem.getItemId());
429
					if(serialNumberDetail.isInsurance()){
399
					Quantity quantity = new Quantity();
430
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), cli.getSellingPrice());
400
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
431
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
401
					quantity.setRequested(customFofoLineItem.getQuantity());
432
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(), item.getModelName());
402
					itemIdQuantityAvailability.setQuantity(quantity);
433
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
403
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
434
					}
-
 
435
				}
404
				}
-
 
405
	
436
			}
406
			}
-
 
407
	
-
 
408
	
437
			else{
409
	
438
				nonSerializedItemIds.add(cli.getItemId());
410
			if(!itemIdQuantityAvailabilities.isEmpty()){
-
 
411
				// itemIdQuantity request is not valid
-
 
412
				LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
-
 
413
				return "error";
439
			}
414
			}
440
 
415
	
441
		}
-
 
442
 
416
	
443
 
417
	
-
 
418
			//		Set<Integer> invalidItemIdSerialNumbers = new HashSet<>();
444
		Map<Integer, List<InventoryItem>> serializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
419
			//		Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>();
445
		Map<Integer, List<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
420
			//		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), itemIds); //change it
-
 
421
			//		
446
		Map<Integer, List<Float>> itemIdPriceDropAmount = new HashMap<>();
422
			//		Map<Integer, Float> itemIdPriceDropAmount = new HashMap<>();
447
 
423
			//		
-
 
424
			//		for(InventoryItem inventoryItem : inventoryItems){
-
 
425
			//			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(inventoryItem.getItemId());
448
		if (!serialNumbers.isEmpty()){
426
			//			if(customFofoLineItem.getSerialNumbers().isEmpty()){
449
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoDetails.getFofoId(), serialNumbers);
427
			//				if(!(inventoryItem.getSerialNumber() == null && inventoryItem.getSerialNumber().equals(""))){
450
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
428
			//					invalidItemIdSerialNumbers.add(inventoryItem.getItemId());
-
 
429
			//				}
-
 
430
			//			}
451
			for (InventoryItem it : serializedInventoryItems){
431
			//			if(!customFofoLineItem.getSerialNumbers().isEmpty()){
-
 
432
			//				if(!customFofoLineItem.getSerialNumbers().contains(inventoryItem.getSerialNumber())){
-
 
433
			//					if(!itemIdSerialNumbers.containsKey(customFofoLineItem.getItemId())){
452
				if (it.getGoodQuantity() == 1){
434
			//						Set<String> serialNumbers = new HashSet<>();
453
					if (serializedInventoryItemMap.containsKey(it.getItemId())){
435
			//						serialNumbers.add(inventoryItem.getSerialNumber());
454
						serializedInventoryItemMap.get(it.getItemId()).add(it);
436
			//						itemIdSerialNumbers.put(customFofoLineItem.getItemId(), serialNumbers);
-
 
437
			//					}else{
455
						itemIdPriceDropAmount.get(it.getItemId()).add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
438
			//						itemIdSerialNumbers.get(customFofoLineItem.getItemId()).add(inventoryItem.getSerialNumber());
-
 
439
			//				}
456
					}
440
			//			}
-
 
441
			//			itemIdPriceDropAmount.put(inventoryItem.getItemId(), inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
457
					else{
442
			//		}
-
 
443
	
458
						ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
444
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
-
 
445
			List<Item> items = itemRepository.selectByIds(itemIds);
-
 
446
			for (Item i : items){
459
						tmp.add(it);
447
				itemMap.put(i.getId(), i);
-
 
448
			}
-
 
449
	
-
 
450
			Set<Integer> nonSerializedItemIds = new HashSet<>();
-
 
451
			Set<String> serialNumbers = new HashSet<>();
-
 
452
			Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
-
 
453
			Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
-
 
454
			Map<String, String> serialNumberModelName = new HashMap<>();
-
 
455
			Map<String, String> serialNumberBrand = new HashMap<>();
-
 
456
			Collection<CustomFofoLineItem> lineItemsValues = customFofoLineItemMap.values();
-
 
457
			for (CustomFofoLineItem cli : lineItemsValues){
-
 
458
	
460
						serializedInventoryItemMap.put(it.getItemId(), tmp);
459
				Item item = itemMap.get(cli.getItemId());
-
 
460
				if (item.getType().equals(ItemType.SERIALIZED)){
-
 
461
					for (SerialNumberDetail serialNumberDetail : cli.getSerialNumberDetails()){
461
						ArrayList<Float> priceDropAmouts = new ArrayList<>();
462
						serialNumbers.add(serialNumberDetail.getSerialNumber());
-
 
463
						if(serialNumberDetail.isInsurance()){
-
 
464
							insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), cli.getSellingPrice());
462
						priceDropAmouts.add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
465
							insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
463
						itemIdPriceDropAmount.put(it.getItemId(), priceDropAmouts);
466
							serialNumberModelName.put(serialNumberDetail.getSerialNumber(), item.getModelName());
-
 
467
							serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
-
 
468
						}
464
					}
469
					}
465
				}
470
				}
-
 
471
				else{
-
 
472
					nonSerializedItemIds.add(cli.getItemId());
-
 
473
				}
-
 
474
	
466
			}
475
			}
467
		}
476
	
468
 
477
	
-
 
478
			Map<Integer, List<InventoryItem>> serializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
-
 
479
			Map<Integer, List<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
-
 
480
			Map<Integer, List<Float>> itemIdPriceDropAmount = new HashMap<>();
-
 
481
	
469
		if (!nonSerializedItemIds.isEmpty()){
482
			if (!serialNumbers.isEmpty()){
470
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), nonSerializedItemIds);
483
				List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoDetails.getFofoId(), serialNumbers);
-
 
484
				LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
471
			for (InventoryItem it : nonSerializedInventoryItems){
485
				for (InventoryItem it : serializedInventoryItems){
472
				if (it.getGoodQuantity() > 0){
486
					if (it.getGoodQuantity() == 1){
473
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
487
						if (serializedInventoryItemMap.containsKey(it.getItemId())){
474
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
488
							serializedInventoryItemMap.get(it.getItemId()).add(it);
-
 
489
							itemIdPriceDropAmount.get(it.getItemId()).
-
 
490
							add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
475
					}
491
						}
476
					else{
492
						else{
477
						ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
493
							ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
478
						tmp.add(it);
494
							tmp.add(it);
479
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
495
							serializedInventoryItemMap.put(it.getItemId(), tmp);
-
 
496
							ArrayList<Float> priceDropAmouts = new ArrayList<>();
-
 
497
							priceDropAmouts.add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
-
 
498
							itemIdPriceDropAmount.put(it.getItemId(), priceDropAmouts);
-
 
499
						}
480
					}
500
					}
481
				}
501
				}
482
			}
502
			}
483
		}
-
 
484
 
503
	
485
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
504
			if (!nonSerializedItemIds.isEmpty()){
-
 
505
				List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), nonSerializedItemIds);
486
		List<Integer> itemIdSerialNumbers = new ArrayList<Integer>();
506
				for (InventoryItem it : nonSerializedInventoryItems){
487
 
-
 
488
		for (Item i : items){
507
					if (it.getGoodQuantity() > 0){
489
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(i.getId());
508
						if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
490
			if (i.getType().equals(ItemType.SERIALIZED)){
509
							nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
-
 
510
						}
-
 
511
						else{
491
				if (customFofoLineItem ==null || customFofoLineItem.getSerialNumberDetails().isEmpty()){
512
							ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
-
 
513
							tmp.add(it);
492
					invalidItemIdSerialNumbers.add(i.getId());
514
							nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
-
 
515
						}
-
 
516
					}
493
				}
517
				}
494
			}
518
			}
-
 
519
	
-
 
520
			List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
-
 
521
			List<Integer> itemIdSerialNumbers = new ArrayList<Integer>();
-
 
522
	
-
 
523
			for (Item i : items){
-
 
524
				CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(i.getId());
-
 
525
				if (i.getType().equals(ItemType.SERIALIZED)){
-
 
526
					if (customFofoLineItem ==null || customFofoLineItem.getSerialNumberDetails().isEmpty()){
-
 
527
						invalidItemIdSerialNumbers.add(i.getId());
-
 
528
					}
-
 
529
				}
495
			else{
530
				else{
496
				if (customFofoLineItem == null || !customFofoLineItem.getSerialNumberDetails().isEmpty()){
531
					if (customFofoLineItem == null || !customFofoLineItem.getSerialNumberDetails().isEmpty()){
497
					itemIdSerialNumbers.add(i.getId());
532
						itemIdSerialNumbers.add(i.getId());
-
 
533
					}
498
				}
534
				}
499
			}
535
			}
500
		}
-
 
501
 
536
	
502
		if(!invalidItemIdSerialNumbers.isEmpty()){
537
			if(!invalidItemIdSerialNumbers.isEmpty()){
503
			LOGGER.error("Invalid itemId's serialNumbers {}", invalidItemIdSerialNumbers);
538
				LOGGER.error("Invalid itemId's serialNumbers {}", invalidItemIdSerialNumbers);
504
			// itemId's are serialized you are saying these are not serialized
539
				// itemId's are serialized you are saying these are not serialized
505
			return "error";
540
				return "error";
506
		}
541
			}
507
 
542
	
508
		if(!itemIdSerialNumbers.isEmpty()){
543
			if(!itemIdSerialNumbers.isEmpty()){
509
			LOGGER.error("Invalid itemId's serialNumbers {}", itemIdSerialNumbers);
544
				LOGGER.error("Invalid itemId's serialNumbers {}", itemIdSerialNumbers);
510
			// itemId's are non serialized you are saying these are serialized
545
				// itemId's are non serialized you are saying these are serialized
511
			return "error";
546
				return "error";
512
		}
547
			}
513
 
548
	
514
		if(items.size() != itemIds.size()){
549
			if(items.size() != itemIds.size()){
515
			LOGGER.error("Requested ItemIds not found in catalog");
550
				LOGGER.error("Requested ItemIds not found in catalog");
516
			// invalid itemIds 
551
				// invalid itemIds 
517
			return "error";
552
				return "error";
518
		}
553
			}
519
 
554
	
520
		Map<Integer, List<InventoryItem>> inventoryItemsToBill = new HashMap<Integer,List<InventoryItem>>();
555
			Map<Integer, List<InventoryItem>> inventoryItemsToBill = new HashMap<Integer,List<InventoryItem>>();
521
		Map<Integer, Integer> inventoryItemQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
556
			Map<Integer, Integer> inventoryItemQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
522
 
557
	
-
 
558
			LOGGER.info("itemMap keys {}", itemMap.keySet());
523
		//Lets reduce quantity and decide what inventory items to use.
559
			//Lets reduce quantity and decide what inventory items to use.
524
		for (Item i : items){
560
			for (Item i : items){
525
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(i.getId());
561
				CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(i.getId());
526
			if (i.getType().equals(ItemType.SERIALIZED)){
562
				if (i.getType().equals(ItemType.SERIALIZED)){
527
				//TODO:handle null
563
					//TODO:handle null
528
				if (serializedInventoryItemMap.get(i.getId()) == null || customFofoLineItem.getSerialNumberDetails().size() != serializedInventoryItemMap.get(i.getId()).size()){
564
					if (serializedInventoryItemMap.get(i.getId()) == null || customFofoLineItem.getSerialNumberDetails().size() != serializedInventoryItemMap.get(i.getId()).size()){
529
					//not enough serial numbers
565
						//not enough serial numbers
530
					LOGGER.info("serialNumbers {}", serialNumbers);
566
						//LOGGER.info("serialNumbers {}", serialNumbers);
531
					LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
567
						LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
532
					LOGGER.info("itemId {}", i.getId());
568
						LOGGER.info("itemId {}", i.getId());
533
					LOGGER.error("not enough serial numbers");
569
						LOGGER.error("not enough serial numbers");
534
					return "error";
570
						return "error";
-
 
571
					}
-
 
572
					List<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(i.getId());
-
 
573
					for (InventoryItem it : inventoryItemsSerializedserialized){
-
 
574
						it.setGoodQuantity(0);
-
 
575
						inventoryItemQuantityUsed.put(it.getId(), 1);
-
 
576
					}
-
 
577
					inventoryItemsToBill.put(i.getId(), inventoryItemsSerializedserialized);
535
				}
578
				}
536
				List<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(i.getId());
-
 
537
				for (InventoryItem it : inventoryItemsSerializedserialized){
-
 
538
					it.setGoodQuantity(0);
-
 
539
					inventoryItemQuantityUsed.put(it.getId(), 1);
-
 
540
				}
-
 
541
				inventoryItemsToBill.put(i.getId(), inventoryItemsSerializedserialized);
-
 
542
			}
-
 
543
			else{
579
				else{
544
				List<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(i.getId());
580
					List<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(i.getId());
545
				int quantityToBill = customFofoLineItem.getQuantity();
581
					int quantityToBill = customFofoLineItem.getQuantity();
546
				int totalLeft = quantityToBill;
582
					int totalLeft = quantityToBill;
547
				List<InventoryItem> inventoryItemsNonSerializedUsed = new ArrayList<InventoryItem>();
583
					List<InventoryItem> inventoryItemsNonSerializedUsed = new ArrayList<InventoryItem>();
548
				if (inventoryItemsNonSerialized!=null){
584
					if (inventoryItemsNonSerialized!=null){
549
					for (InventoryItem it : inventoryItemsNonSerialized){
585
						for (InventoryItem it : inventoryItemsNonSerialized){
550
						if (totalLeft > 0){
586
							if (totalLeft > 0){
551
							int toUse = Math.min(totalLeft, it.getGoodQuantity());
587
								int toUse = Math.min(totalLeft, it.getGoodQuantity());
552
							inventoryItemQuantityUsed.put(it.getId(), toUse);
588
								inventoryItemQuantityUsed.put(it.getId(), toUse);
553
							it.setGoodQuantity(it.getGoodQuantity()  - toUse);
589
								it.setGoodQuantity(it.getGoodQuantity()  - toUse);
554
							totalLeft = totalLeft - toUse;
590
								totalLeft = totalLeft - toUse;
555
							inventoryItemsNonSerializedUsed.add(it);
591
								inventoryItemsNonSerializedUsed.add(it);
-
 
592
							}
556
						}
593
						}
557
					}
594
					}
-
 
595
					
-
 
596
					if (totalLeft > 0){
-
 
597
						//not enough quanity for non-serialized
-
 
598
						System.out.println("not enough quanity for non-serialized");
-
 
599
						return "error";
-
 
600
					}
-
 
601
					inventoryItemsToBill.put(i.getId(), inventoryItemsNonSerializedUsed);
558
				}
602
				}
559
				
603
			}
-
 
604
			
560
				if (totalLeft > 0){
605
			// mop price validation
561
					//not enough quanity for non-serialized
606
			Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
-
 
607
			Map<Integer, Float> itemIdMopPriceMap = pricingService.getPrivateDealPriceMopPriceNotFound(itemIds, fofoDetails.getFofoId());
562
					System.out.println("not enough quanity for non-serialized");
608
			for(Map.Entry<Integer, Float> entry : itemIdMopPriceMap.entrySet()){
-
 
609
				CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(entry.getKey());
563
					return "error";
610
				if(customFofoLineItem.getSellingPrice() < entry.getValue()){
-
 
611
					invalidMopItemIdPriceMap.put(entry.getKey(), customFofoLineItem.getSellingPrice());
564
				}
612
				}
565
				inventoryItemsToBill.put(i.getId(), inventoryItemsNonSerializedUsed);
-
 
566
			}
613
			}
567
		}
614
			
568
		
-
 
569
		// mop price validation
-
 
570
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
615
			if(!invalidMopItemIdPriceMap.isEmpty()){
571
		Map<Integer, Float> itemIdPriceMap = pricingService.getPrices(itemIds, fofoDetails.getFofoId());
616
				LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
572
		//LOGGER.info("itemIdPriceMap = {}", itemIdPriceMap);
617
				return "error";
573
		for(Map.Entry<Integer, Float> entry : itemIdPriceMap.entrySet()){
-
 
574
			CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(entry.getKey());
-
 
575
			if(customFofoLineItem.getSellingPrice() < entry.getValue()){
-
 
576
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoLineItem.getSellingPrice());
-
 
577
			}
618
			}
578
		}
-
 
579
		
619
	
580
		if(!invalidMopItemIdPriceMap.isEmpty()){
-
 
581
			LOGGER.error("Invalid itemIds mop prices should be greater than mop prices {}", invalidMopItemIdPriceMap);
-
 
582
			return "error";
-
 
583
		}
-
 
584
 
-
 
585
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
620
			InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
586
		try{
621
			try{
587
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoDetails.getFofoId());
622
				invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoDetails.getFofoId());
588
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
623
				invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
589
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
624
				invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
590
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
625
			}catch(ProfitMandiBusinessException profitMandiBusinessException){
591
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
626
				invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
592
			invoiceNumberGenerationSequence.setFofoId(fofoDetails.getFofoId());
627
				invoiceNumberGenerationSequence.setFofoId(fofoDetails.getFofoId());
593
			invoiceNumberGenerationSequence.setPrefix("INVOICE");
628
				invoiceNumberGenerationSequence.setPrefix("INVOICE");
594
			invoiceNumberGenerationSequence.setSequence(1);
629
				invoiceNumberGenerationSequence.setSequence(1);
595
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
630
				invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
596
		}
-
 
597
 
-
 
598
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
-
 
599
 
-
 
600
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
-
 
601
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
-
 
602
			return "error";
-
 
603
		}
-
 
604
 
-
 
605
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
-
 
606
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
-
 
607
			return "error";
-
 
608
		}
-
 
609
		
-
 
610
		LocalDate dateOfBirth = null;
-
 
611
		try{
-
 
612
			dateOfBirth = StringUtils.toDate(customCustomer.getDateOfBirth());
-
 
613
		}catch(DateTimeException dateTimeException){
-
 
614
			LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
-
 
615
			return "error";
-
 
616
		}
-
 
617
		
-
 
618
		Customer customer = null;
-
 
619
		try{
-
 
620
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
-
 
621
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
622
			LOGGER.error("Error : ", profitMandiBusinessException);
-
 
623
			customer = new Customer();
-
 
624
			customer.setFirstName(customCustomer.getFirstName());
-
 
625
			customer.setLastName(customCustomer.getLastName());
-
 
626
			customer.setDateOfBirth(dateOfBirth);
-
 
627
			customer.setEmailId(customCustomer.getEmailId());
-
 
628
			customer.setMobileNumber(customCustomer.getMobileNumber());
-
 
629
			customerRepository.persist(customer);
-
 
630
		}
-
 
631
		//TODO:Check if createOrderRequest contains addressId
-
 
632
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress());
-
 
633
		customerAddress.setCustomerId(customer.getId());
-
 
634
		customerAddressRepository.persist(customerAddress);
-
 
635
 
-
 
636
		FofoOrder fofoOrder = new FofoOrder();
-
 
637
		fofoOrder.setCustomerId(customer.getId());
-
 
638
		fofoOrder.setFofoId(fofoDetails.getFofoId());
-
 
639
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
-
 
640
		fofoOrder.setTotalAmount(totalAmount);
-
 
641
		fofoOrder.setCustomerAddressId(customerAddress.getId());
-
 
642
		fofoOrderRepository.persist(fofoOrder);
-
 
643
 
-
 
644
		for(CustomPaymentOption customPaymentOption : createOrderRequest.getPaymentOptions()){
-
 
645
			PaymentOption paymentOption = new PaymentOption();
-
 
646
			paymentOption.setOrderId(fofoOrder.getId());
-
 
647
			paymentOption.setAmount(customPaymentOption.getAmount());
-
 
648
			paymentOption.setType(customPaymentOption.getType());
-
 
649
			paymentOptionRepository.persist(paymentOption);
-
 
650
		}
-
 
651
 
-
 
652
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoDetails.getFofoId()));
-
 
653
		Map<String, GstRate> gstRateMap = null;
-
 
654
		if(retailerAddress.getState().equals(customerAddress.getState())){
-
 
655
			gstRateMap = Utils.getGstRates(retailerAddress.getState());
-
 
656
		}else{
-
 
657
			LOGGER.info("inter gstRate = true");
-
 
658
			gstRateMap = Utils.getInterGstRates();
-
 
659
		}
-
 
660
		LOGGER.info("gstRateMap {}", gstRateMap);
-
 
661
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
-
 
662
			FofoLineItem fofoLineItem = new FofoLineItem();
-
 
663
			fofoLineItem.setItemId(customFofoLineItem.getItemId());
-
 
664
			fofoLineItem.setQuantity(customFofoLineItem.getQuantity());
-
 
665
			fofoLineItem.setSellingPrice(customFofoLineItem.getSellingPrice());
-
 
666
			fofoLineItem.setOrderId(fofoOrder.getId());
-
 
667
			fofoLineItem.setDp(customFofoLineItem.getSellingPrice());
-
 
668
			Item item = itemMap.get(customFofoLineItem.getItemId());
-
 
669
			GstRate gstRate = gstRateMap.get(item.getHsnCode());
-
 
670
			fofoLineItem.setIgstRate(gstRate.getIgstRate());
-
 
671
			fofoLineItem.setCgstRate(gstRate.getCgstRate());
-
 
672
			fofoLineItem.setSgstRate(gstRate.getSgstRate());
-
 
673
			fofoLineItem.setHsnCode(gstRate.getHsnCode());
-
 
674
			List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoLineItem.getItemId());
-
 
675
			float cost = 0;
-
 
676
			if (priceDropAmounts!=null){
-
 
677
				for (Float pda : priceDropAmounts){
-
 
678
					cost = cost + pda;
-
 
679
				}
-
 
680
			}
-
 
681
			else{
-
 
682
				cost = customFofoLineItem.getSellingPrice()* customFofoLineItem.getQuantity();
-
 
683
			}
-
 
684
			fofoLineItem.setCost(cost);
-
 
685
			fofoLineItem.setBrand(item.getBrand());
-
 
686
			fofoLineItem.setModelName(item.getModelName());
-
 
687
			fofoLineItem.setModelNumber(item.getModelNumber());
-
 
688
			fofoLineItem.setColor(item.getColor());
-
 
689
			fofoLineItemRepository.persist(fofoLineItem);
-
 
690
			LOGGER.info("\n\n");
-
 
691
			if(!customFofoLineItem.getSerialNumberDetails().isEmpty()){
-
 
692
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
-
 
693
					FofoLineItemSerialNumber fofoLineItemSerialNumber = new FofoLineItemSerialNumber();
-
 
694
					fofoLineItemSerialNumber.setFofoLineItemId(fofoLineItem.getId());
-
 
695
					fofoLineItemSerialNumber.setSerialNumber(serialNumberDetail.getSerialNumber());
-
 
696
					fofoLineItemSerialNumberRepository.persist(fofoLineItemSerialNumber);
-
 
697
				}
-
 
698
			}
631
			}
699
 
632
	
700
			for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
-
 
701
				FofoItemId fofoItemId = new FofoItemId();
633
			CustomCustomer customCustomer = createOrderRequest.getCustomer();
-
 
634
	
702
				fofoItemId.setFofoId(fofoDetails.getFofoId());
635
			if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
703
				fofoItemId.setItemId(fofoLineItem.getItemId());
636
				LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
704
				if(currentInventorySnapshot.getId().equals(fofoItemId)){
637
				return "error";
705
					currentInventorySnapshotRepository.updateAvailabilityByFofoItemId(fofoItemId, currentInventorySnapshot.getAvailability() - customFofoLineItem.getQuantity());
-
 
706
				}
638
			}
707
			}
639
	
708
			List<InventoryItem> inventoryItems = inventoryItemsToBill.get(fofoLineItem.getItemId());
640
			if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
709
			for(InventoryItem inventoryItem : inventoryItems){
-
 
710
				inventoryItem.setLastScanType(ScanType.SALE);
-
 
711
				inventoryItemRepository.persist(inventoryItem);
-
 
712
				ScanRecord scanRecord = new ScanRecord();
-
 
713
				scanRecord.setInventoryItemId(inventoryItem.getId());
641
				LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
714
				scanRecord.setFofoId(fofoDetails.getFofoId());
-
 
715
				//correct this
642
				return "error";
716
				scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
-
 
717
				scanRecord.setType(ScanType.SALE);
-
 
718
				scanRecordRepository.persist(scanRecord);
-
 
719
			}
643
			}
720
		}
-
 
721
		
-
 
722
		// insurance calculation is insurance flag is enabled
-
 
723
		if(!insuranceSerialNumberItemPrice.isEmpty()){
-
 
724
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
-
 
725
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
-
 
726
			
-
 
727
			
644
			
728
			Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
645
			boolean insurance = false;
729
			Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
646
			for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
730
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
647
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
731
				if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
648
					if(serialNumberDetail.getAmount() > 0){
732
					invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
649
						insurance = true;
733
				}
650
						break;
734
				
651
					}
735
				if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
-
 
736
					invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
-
 
737
				}
652
				}
738
			}
653
			}
-
 
654
			LOGGER.info("insurance [{}] processing ....", insurance);
739
			
655
			
-
 
656
			LocalDate customerDateOfBirth = null;
-
 
657
			if(insurance){
-
 
658
				try{
740
			// insurance sale amount can not be lesser than insurance purchase amount
659
					customerDateOfBirth = StringUtils.toDate(createOrderRequest.getCustomerDateOfBirth());
741
			if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
660
				}catch(DateTimeException dateTimeException){
742
				LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
661
					LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
743
				return "error";
662
					return "error";
-
 
663
				}
744
			}
664
			}
745
			
665
			
-
 
666
			Customer customer = null;
-
 
667
			try{
-
 
668
				customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
-
 
669
			}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
670
				LOGGER.error("Error : ", profitMandiBusinessException);
-
 
671
				customer = new Customer();
-
 
672
				customer.setFirstName(customCustomer.getFirstName());
-
 
673
				customer.setLastName(customCustomer.getLastName());
-
 
674
				customer.setEmailId(customCustomer.getEmailId());
-
 
675
				customer.setMobileNumber(customCustomer.getMobileNumber());
-
 
676
				customerRepository.persist(customer);
-
 
677
			}
-
 
678
			//TODO:Check if createOrderRequest contains addressId
-
 
679
			CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress());
-
 
680
			customerAddress.setCustomerId(customer.getId());
-
 
681
			customerAddressRepository.persist(customerAddress);
-
 
682
	
-
 
683
			FofoOrder fofoOrder = new FofoOrder();
-
 
684
			fofoOrder.setCustomerId(customer.getId());
-
 
685
			fofoOrder.setFofoId(fofoDetails.getFofoId());
-
 
686
			fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
-
 
687
			fofoOrder.setTotalAmount(totalAmount);
-
 
688
			fofoOrder.setCustomerAddressId(customerAddress.getId());
-
 
689
			fofoOrderRepository.persist(fofoOrder);
-
 
690
	
-
 
691
			for(CustomPaymentOption customPaymentOption : createOrderRequest.getPaymentOptions()){
-
 
692
				PaymentOption paymentOption = new PaymentOption();
-
 
693
				paymentOption.setOrderId(fofoOrder.getId());
-
 
694
				paymentOption.setAmount(customPaymentOption.getAmount());
-
 
695
				paymentOption.setType(customPaymentOption.getType());
-
 
696
				paymentOptionRepository.persist(paymentOption);
-
 
697
			}
-
 
698
	
-
 
699
			Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoDetails.getFofoId()));
-
 
700
			Map<String, GstRate> gstRateMap = null;
-
 
701
			if(retailerAddress.getState().equals(customerAddress.getState())){
-
 
702
				gstRateMap = Utils.getGstRates(retailerAddress.getState());
-
 
703
			}else{
-
 
704
				LOGGER.info("inter gstRate = true");
-
 
705
				gstRateMap = Utils.getInterGstRates();
-
 
706
			}
-
 
707
			LOGGER.info("gstRateMap {}", gstRateMap);
-
 
708
			for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
-
 
709
				FofoLineItem fofoLineItem = new FofoLineItem();
-
 
710
				fofoLineItem.setItemId(customFofoLineItem.getItemId());
-
 
711
				fofoLineItem.setQuantity(customFofoLineItem.getQuantity());
-
 
712
				fofoLineItem.setSellingPrice(customFofoLineItem.getSellingPrice());
-
 
713
				fofoLineItem.setOrderId(fofoOrder.getId());
-
 
714
				fofoLineItem.setDp(customFofoLineItem.getSellingPrice());
-
 
715
				Item item = itemMap.get(customFofoLineItem.getItemId());
-
 
716
				GstRate gstRate = gstRateMap.get(item.getHsnCode());
-
 
717
				fofoLineItem.setIgstRate(gstRate.getIgstRate());
-
 
718
				fofoLineItem.setCgstRate(gstRate.getCgstRate());
-
 
719
				fofoLineItem.setSgstRate(gstRate.getSgstRate());
-
 
720
				fofoLineItem.setHsnCode(gstRate.getHsnCode());
-
 
721
				List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoLineItem.getItemId());
-
 
722
				float cost = 0;
-
 
723
				if (priceDropAmounts!=null){
-
 
724
					for (Float pda : priceDropAmounts){
-
 
725
						cost = cost + pda;
-
 
726
					}
-
 
727
				}
-
 
728
				else{
-
 
729
					cost = customFofoLineItem.getSellingPrice()* customFofoLineItem.getQuantity();
-
 
730
				}
-
 
731
				fofoLineItem.setCost(cost);
-
 
732
				fofoLineItem.setBrand(item.getBrand());
-
 
733
				fofoLineItem.setModelName(item.getModelName());
-
 
734
				fofoLineItem.setModelNumber(item.getModelNumber());
-
 
735
				fofoLineItem.setColor(item.getColor());
-
 
736
				fofoLineItemRepository.persist(fofoLineItem);
-
 
737
				LOGGER.info("\n\n");
746
			if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
738
				if(!customFofoLineItem.getSerialNumberDetails().isEmpty()){
-
 
739
					for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
-
 
740
						FofoLineItemSerialNumber fofoLineItemSerialNumber = new FofoLineItemSerialNumber();
-
 
741
						fofoLineItemSerialNumber.setFofoLineItemId(fofoLineItem.getId());
-
 
742
						fofoLineItemSerialNumber.setSerialNumber(serialNumberDetail.getSerialNumber());
-
 
743
						fofoLineItemSerialNumberRepository.persist(fofoLineItemSerialNumber);
-
 
744
					}
-
 
745
				}
-
 
746
	
-
 
747
				for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
-
 
748
					FofoItemId fofoItemId = new FofoItemId();
-
 
749
					fofoItemId.setFofoId(fofoDetails.getFofoId());
-
 
750
					fofoItemId.setItemId(fofoLineItem.getItemId());
-
 
751
					if(currentInventorySnapshot.getId().equals(fofoItemId)){
747
				LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
752
						currentInventorySnapshotRepository.updateAvailabilityByFofoItemId(fofoItemId, currentInventorySnapshot.getAvailability() - customFofoLineItem.getQuantity());
-
 
753
					}
-
 
754
				}
-
 
755
				List<InventoryItem> inventoryItems = inventoryItemsToBill.get(fofoLineItem.getItemId());
-
 
756
				for(InventoryItem inventoryItem : inventoryItems){
-
 
757
					inventoryItem.setLastScanType(ScanType.SALE);
-
 
758
					try{
-
 
759
						inventoryItemRepository.persist(inventoryItem);
-
 
760
					}catch (Exception e) {
-
 
761
						LOGGER.error("Unable to persist InventoryItem : ", e);
-
 
762
					}
-
 
763
						ScanRecord scanRecord = new ScanRecord();
-
 
764
					scanRecord.setInventoryItemId(inventoryItem.getId());
-
 
765
					scanRecord.setFofoId(fofoDetails.getFofoId());
748
				return "error";
766
					//correct this
-
 
767
					scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
-
 
768
					scanRecord.setType(ScanType.SALE);
-
 
769
					try{
-
 
770
						scanRecordRepository.persist(scanRecord);
-
 
771
					}catch(Exception exception){
-
 
772
						LOGGER.error("Unable to persist scanRecord", exception);
-
 
773
					}
-
 
774
				}
749
			}
775
			}
750
			
776
			
-
 
777
			// insurance calculation is insurance flag is enabled
-
 
778
			if(!insuranceSerialNumberItemPrice.isEmpty()){
-
 
779
				LOGGER.info("Processing for insurence for serialNumbers");
-
 
780
				Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
-
 
781
				InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
-
 
782
				
751
			
783
				
-
 
784
				Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
-
 
785
				Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
-
 
786
				for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
-
 
787
					if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
-
 
788
						invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
-
 
789
					}
-
 
790
					
-
 
791
					if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
-
 
792
						invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
-
 
793
					}
-
 
794
				}
-
 
795
				
-
 
796
				// insurance sale amount can not be lesser than insurance purchase amount
-
 
797
				if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
-
 
798
					LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
-
 
799
					return "error";
-
 
800
				}
-
 
801
				
-
 
802
				if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
-
 
803
					LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
-
 
804
					return "error";
-
 
805
				}
-
 
806
				
-
 
807
				
752
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
808
				for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
753
				PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
809
					PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
754
				try{
810
					try{
755
					policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
811
						policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
756
					policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
812
						policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
757
					policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
813
						policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
758
				}catch(ProfitMandiBusinessException profitMandiBusinessException){
814
					}catch(ProfitMandiBusinessException profitMandiBusinessException){
759
					policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
815
						policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
760
					policyNumberGenerationSequence.setSequence(1);
816
						policyNumberGenerationSequence.setSequence(1);
761
					policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
817
						policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
762
				}
818
					}
-
 
819
					
763
				InsurancePolicy insurancePolicy = new InsurancePolicy();
820
					InsurancePolicy insurancePolicy = new InsurancePolicy();
764
				insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
821
					insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
765
				insurancePolicy.setRetailerId(fofoDetails.getFofoId());
822
					insurancePolicy.setRetailerId(fofoDetails.getFofoId());
766
				insurancePolicy.setPurchaseAmount(insurancePricesMap.get(entry.getValue()).getDealerPrice());
823
					insurancePolicy.setPurchaseAmount(insurancePricesMap.get(entry.getValue()).getDealerPrice());
767
				insurancePolicy.setSaleAmount(insuranceSerialNumberSaleAmount.get(entry.getKey()));
824
					insurancePolicy.setSaleAmount(insuranceSerialNumberSaleAmount.get(entry.getKey()));
768
				insurancePolicy.setSellingPrice(entry.getValue());
825
					insurancePolicy.setSellingPrice(entry.getValue());
769
				insurancePolicy.setSerialNumber(entry.getKey());
826
					insurancePolicy.setSerialNumber(entry.getKey());
770
				insurancePolicy.setModelName(serialNumberModelName.get(entry.getKey()));
827
					insurancePolicy.setModelName(serialNumberModelName.get(entry.getKey()));
771
				insurancePolicy.setBrand(serialNumberBrand.get(entry.getKey()));
828
					insurancePolicy.setBrand(serialNumberBrand.get(entry.getKey()));
772
				insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence.getSequence()));
829
					insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence.getSequence()));
773
				insurancePolicy.setProviderId(insuranceProvider.getId());
830
					insurancePolicy.setProviderId(insuranceProvider.getId());
-
 
831
					insurancePolicy.setCustomerFirstName(customer.getFirstName());
-
 
832
					insurancePolicy.setCustomerLastName(customer.getLastName());
-
 
833
					insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
-
 
834
					insurancePolicy.setCustomerEmailId(customer.getEmailId());
774
				insurancePolicyRepository.persist(insurancePolicy);
835
					insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
-
 
836
					insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
-
 
837
					insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
-
 
838
					insurancePolicy.setCustomerCity(customerAddress.getCity());
-
 
839
					insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
-
 
840
					insurancePolicy.setCustomerState(customerAddress.getState());
-
 
841
					
775
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
842
					GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
776
				gadgetCopsInsuranceModel.setBrand(serialNumberBrand.get(entry.getKey()));
843
					gadgetCopsInsuranceModel.setBrand(serialNumberBrand.get(entry.getKey()));
777
				gadgetCopsInsuranceModel.setModelName(serialNumberModelName.get(entry.getKey()));
844
					gadgetCopsInsuranceModel.setModelName(serialNumberModelName.get(entry.getKey()));
778
				gadgetCopsInsuranceModel.setSerialNumber(entry.getKey());
845
					gadgetCopsInsuranceModel.setSerialNumber(entry.getKey());
779
				gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
846
					gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
780
				gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
847
					gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
781
				gadgetCopsInsuranceModel.setCustomerDateOfBirth(customer.getDateOfBirth());
848
					gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
782
				gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
849
					gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
783
				gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
850
					gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
784
				gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
851
					gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
785
				gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
852
					gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
786
				gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
853
					gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
787
				gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
854
					gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
788
				gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
855
					gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
789
				gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
856
					gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
790
				gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
857
					gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
791
				gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
858
					gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
-
 
859
					
-
 
860
					try{
792
				InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
861
						InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
-
 
862
						insurancePolicy.setPosted(true);
-
 
863
					}catch (ProfitMandiBusinessException profitMandiBusinessException) {
-
 
864
						LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
-
 
865
					}
-
 
866
					insurancePolicyRepository.persist(insurancePolicy);
-
 
867
				}
793
			}
868
			}
-
 
869
			LOGGER.info("Order has been created successfully...");
-
 
870
			return "redirect:/get-order/?orderId="+fofoOrder.getId();
-
 
871
		}catch (Exception e) {
-
 
872
			LOGGER.error("Unable to create order : ", e);
-
 
873
			return "error";
794
		}
874
		}
795
		return "redirect:/get-order/?orderId="+fofoOrder.getId();
-
 
796
	}
875
	}
797
 
876
 
798
	private CustomerAddress createCustomerAddress(CustomAddress customAddress){
877
	private CustomerAddress createCustomerAddress(CustomAddress customAddress){
799
		CustomerAddress customerAddress = new CustomerAddress();
878
		CustomerAddress customerAddress = new CustomerAddress();
800
		customerAddress.setName(customAddress.getName());
879
		customerAddress.setName(customAddress.getName());
Line 848... Line 927...
848
				paymentOptionTypes.add(customPaymentOption.getType().name());
927
				paymentOptionTypes.add(customPaymentOption.getType().name());
849
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
928
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
850
			}
929
			}
851
		}
930
		}
852
		if(calculatedAmount != totalAmount){
931
		if(calculatedAmount != totalAmount){
-
 
932
			LOGGER.error("PaymentOptionCalculatedAmount [{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
853
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "");
933
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "");
854
		}
934
		}
855
	}
935
	}
856
 
936
 
857
 
937
 
Line 864... Line 944...
864
		PdfModel pdfModel = new PdfModel();
944
		PdfModel pdfModel = new PdfModel();
865
		pdfModel.setAuther("profitmandi");
945
		pdfModel.setAuther("profitmandi");
866
		pdfModel.setTitle("Retailer Invoice");
946
		pdfModel.setTitle("Retailer Invoice");
867
		
947
		
868
		// insurance calculation
948
		// insurance calculation
869
		float insuranceTotalAmount = 0;
-
 
870
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
949
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByInvoiceNumber(fofoOrder.getInvoiceNumber());
871
		Set<Integer> insuranceProviderIds = new HashSet<>(insurancePolicies.size());
-
 
872
		for(InsurancePolicy insurancePolicy : insurancePolicies){
-
 
873
			insuranceProviderIds.add(insurancePolicy.getProviderId());
-
 
874
			insuranceTotalAmount = insuranceTotalAmount + insurancePolicy.getSaleAmount();
-
 
875
		}
-
 
876
		List<InsuranceProvider> insuranceProviders = insuranceProviderRepository.selectByIds(insuranceProviderIds);
-
 
877
		Map<Integer, String> insuranceProviderIdNameMap = new HashMap<>(insuranceProviders.size());
-
 
878
		for(InsuranceProvider insuranceProvider : insuranceProviders){
-
 
879
			insuranceProviderIdNameMap.put(insuranceProvider.getId(), insuranceProvider.getName());
-
 
880
		}
-
 
881
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
950
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
882
		final float totalInsuranceTaxRate = 18;
951
		final float totalInsuranceTaxRate = 18;
883
		for(InsurancePolicy insurancePolicy : insurancePolicies){
952
		for(InsurancePolicy insurancePolicy : insurancePolicies){
884
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
953
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
885
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
954
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
886
			customInsurancePolicy.setDescription(insuranceProviderIdNameMap.get(insurancePolicy.getProviderId()) + " Protection (" + insurancePolicy.getSerialNumber() + ")");
955
			customInsurancePolicy.setDescription(insurancePolicy.getInsuranceProvider().getName() + " Protection (" + insurancePolicy.getSerialNumber() + ")");
887
			customInsurancePolicy.setHsnCode("");
956
			customInsurancePolicy.setHsnCode("");
888
			customInsurancePolicy.setRate(taxableInsurancePrice);
957
			customInsurancePolicy.setRate(taxableInsurancePrice);
889
			customInsurancePolicy.setIgstRate(18);
958
			customInsurancePolicy.setIgstRate(18);
890
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
959
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
891
			customInsurancePolicy.setCgstRate(18);
960
			customInsurancePolicy.setCgstRate(18);
Line 897... Line 966...
897
		pdfModel.setInsurancePolicies(customInsurancePolicies);
966
		pdfModel.setInsurancePolicies(customInsurancePolicies);
898
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
967
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
899
		CustomCustomer customCustomer = new CustomCustomer();
968
		CustomCustomer customCustomer = new CustomCustomer();
900
		customCustomer.setFirstName(customer.getFirstName());
969
		customCustomer.setFirstName(customer.getFirstName());
901
		customCustomer.setLastName(customer.getLastName());
970
		customCustomer.setLastName(customer.getLastName());
902
		customCustomer.setDateOfBirth(StringUtils.toString(customer.getDateOfBirth()));
-
 
903
		customCustomer.setEmailId(customer.getEmailId());
971
		customCustomer.setEmailId(customer.getEmailId());
904
		customCustomer.setMobileNumber(customer.getMobileNumber());
972
		customCustomer.setMobileNumber(customer.getMobileNumber());
905
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
973
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
906
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
974
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
907
		pdfModel.setCustomer(customCustomer);
975
		pdfModel.setCustomer(customCustomer);
908
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
976
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
909
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount() + insuranceTotalAmount);
977
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
910
		
978
		
911
		Retailer retailer = retailerRepository.selectById(fofoDetails.getFofoId());
979
		Retailer retailer = retailerRepository.selectById(fofoDetails.getFofoId());
912
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
980
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
913
		CustomRetailer customRetailer = new CustomRetailer();
981
		CustomRetailer customRetailer = new CustomRetailer();
914
		customRetailer.setBusinessName(retailer.getName());
982
		customRetailer.setBusinessName(retailer.getName());
Line 961... Line 1029...
961
		for(FofoLineItemSerialNumber fofoLineItemSerialNumber : fofoLineItemSerialNumbers){
1029
		for(FofoLineItemSerialNumber fofoLineItemSerialNumber : fofoLineItemSerialNumbers){
962
			serialNumbers.add(fofoLineItemSerialNumber.getSerialNumber());
1030
			serialNumbers.add(fofoLineItemSerialNumber.getSerialNumber());
963
		}
1031
		}
964
		return serialNumbers;
1032
		return serialNumbers;
965
	}
1033
	}
-
 
1034
	
-
 
1035
	@RequestMapping(value = "/saleHistory")
-
 
1036
	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{
-
 
1037
		LoginDetails loginDetails = null;
-
 
1038
		try {
-
 
1039
			loginDetails = cookiesProcessor.getCookiesObject(request);
-
 
1040
		} catch (ProfitMandiBusinessException e) {
-
 
1041
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
-
 
1042
			return "response";
-
 
1043
		}
-
 
1044
		
-
 
1045
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
-
 
1046
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
-
 
1047
		long countItems = 0;
-
 
1048
		List<FofoOrder> fofoOrders = new ArrayList<>();
-
 
1049
		if(searchType.equalsIgnoreCase("purchaseReference") && !invoiceNumber.isEmpty()){
-
 
1050
			try {
-
 
1051
				FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndInvoiceNumber(loginDetails.getFofoId(), invoiceNumber);
-
 
1052
				fofoOrders.add(fofoOrder);
-
 
1053
			} catch (ProfitMandiBusinessException e) {
-
 
1054
				LOGGER.info("Sale history not found : ", e);
-
 
1055
			}
-
 
1056
		}else{
-
 
1057
			fofoOrders = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(),startDateTime, endDateTime, offset, limit);
-
 
1058
			countItems = fofoOrderRepository.selectCount(loginDetails.getFofoId(), startDateTime, endDateTime, invoiceNumber, searchType);
-
 
1059
		}
-
 
1060
		
-
 
1061
		model.addAttribute("saleHistories", fofoOrders);
-
 
1062
		model.addAttribute("start",offset+1);
-
 
1063
		model.addAttribute("size",countItems);
-
 
1064
		model.addAttribute("searchType",searchType);
-
 
1065
		model.addAttribute(ProfitMandiConstants.START_TIME, startTimeString);
-
 
1066
		model.addAttribute(ProfitMandiConstants.END_TIME, endTimeString);
-
 
1067
		if (fofoOrders.size() < limit){
-
 
1068
			model.addAttribute("end",offset + fofoOrders.size());
-
 
1069
		}
-
 
1070
		else{
-
 
1071
			model.addAttribute("end",offset+limit);
-
 
1072
		}
-
 
1073
		
-
 
1074
		return "sale-history";
-
 
1075
	}
-
 
1076
	
966
 
1077
 
967
 
1078
 
968
}
1079
}