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