Subversion Repositories SmartDukaan

Rev

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

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