Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

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