Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23365 ashik.ali 1
package com.spice.profitmandi.service.order;
22859 ashik.ali 2
 
23418 ashik.ali 3
import java.io.IOException;
4
import java.net.URISyntaxException;
22859 ashik.ali 5
import java.time.DateTimeException;
6
import java.time.LocalDate;
23202 ashik.ali 7
import java.time.LocalDateTime;
22859 ashik.ali 8
import java.util.ArrayList;
9
import java.util.HashMap;
10
import java.util.HashSet;
11
import java.util.Iterator;
12
import java.util.List;
13
import java.util.Map;
23418 ashik.ali 14
import java.util.Random;
22859 ashik.ali 15
import java.util.Set;
22955 ashik.ali 16
import java.util.function.Function;
17
import java.util.stream.Collectors;
22859 ashik.ali 18
 
19
import org.json.JSONObject;
23568 govind 20
import org.apache.logging.log4j.Logger;
21
import org.apache.logging.log4j.LogManager;
22859 ashik.ali 22
import org.springframework.beans.factory.annotation.Autowired;
23
import org.springframework.stereotype.Component;
24
 
23418 ashik.ali 25
import com.spice.profitmandi.common.ResponseCodeHolder;
23202 ashik.ali 26
import com.spice.profitmandi.common.enumuration.SearchType;
22859 ashik.ali 27
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
28
import com.spice.profitmandi.common.model.CartFofo;
29
import com.spice.profitmandi.common.model.CreateOrderRequest;
30
import com.spice.profitmandi.common.model.CustomAddress;
31
import com.spice.profitmandi.common.model.CustomCustomer;
32
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
33
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
34
import com.spice.profitmandi.common.model.CustomOrderItem;
35
import com.spice.profitmandi.common.model.CustomPaymentOption;
36
import com.spice.profitmandi.common.model.CustomRetailer;
37
import com.spice.profitmandi.common.model.GadgetCopsInsuranceModel;
23172 ashik.ali 38
import com.spice.profitmandi.common.model.GstRate;
22859 ashik.ali 39
import com.spice.profitmandi.common.model.ItemIdQuantityAvailability;
40
import com.spice.profitmandi.common.model.PdfModel;
41
import com.spice.profitmandi.common.model.PriceModel;
42
import com.spice.profitmandi.common.model.ProfitMandiConstants;
43
import com.spice.profitmandi.common.model.Quantity;
44
import com.spice.profitmandi.common.model.SerialNumberDetail;
45
import com.spice.profitmandi.common.util.InsuranceUtils;
46
import com.spice.profitmandi.common.util.StringUtils;
23172 ashik.ali 47
import com.spice.profitmandi.common.util.Utils;
22859 ashik.ali 48
import com.spice.profitmandi.dao.entity.catalog.Item;
49
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
50
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
51
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
23418 ashik.ali 52
import com.spice.profitmandi.dao.entity.dtr.Otp;
23546 ashik.ali 53
import com.spice.profitmandi.dao.entity.dtr.PaymentOptionTransaction;
22859 ashik.ali 54
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
55
import com.spice.profitmandi.dao.entity.dtr.Retailer;
56
import com.spice.profitmandi.dao.entity.dtr.User;
57
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
58
import com.spice.profitmandi.dao.entity.fofo.Customer;
59
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
60
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
61
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
62
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23202 ashik.ali 63
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
22859 ashik.ali 64
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
65
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
23418 ashik.ali 66
import com.spice.profitmandi.dao.entity.fofo.PrebookingListing;
67
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;
68
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrderItem;
23566 amit.gupta 69
import com.spice.profitmandi.dao.entity.fofo.PurchaseReturnItem;
22859 ashik.ali 70
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
71
import com.spice.profitmandi.dao.entity.user.Address;
72
import com.spice.profitmandi.dao.entity.user.Counter;
73
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
23418 ashik.ali 74
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
23546 ashik.ali 75
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
22859 ashik.ali 76
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
77
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23202 ashik.ali 78
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22859 ashik.ali 79
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
80
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
23418 ashik.ali 81
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
23552 amit.gupta 82
import com.spice.profitmandi.dao.repository.dtr.PaymentOptionTransactionRepository;
22859 ashik.ali 83
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
84
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
85
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
86
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
87
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
88
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
89
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
90
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
91
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
92
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
93
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
94
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
95
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
96
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
23418 ashik.ali 97
import com.spice.profitmandi.dao.repository.fofo.PrebookingListingRepository;
98
import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderItemRepository;
99
import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderRepository;
23566 amit.gupta 100
import com.spice.profitmandi.dao.repository.fofo.PurchaseReturnItemRepository;
22859 ashik.ali 101
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
102
import com.spice.profitmandi.dao.repository.user.AddressRepository;
103
import com.spice.profitmandi.dao.repository.user.CounterRepository;
104
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
23418 ashik.ali 105
import com.spice.profitmandi.service.inventory.InventoryService;
22859 ashik.ali 106
import com.spice.profitmandi.service.pricing.PricingService;
107
import com.spice.profitmandi.service.scheme.SchemeService;
23395 amit.gupta 108
import com.spice.profitmandi.service.wallet.WalletService;
22859 ashik.ali 109
 
110
import in.shop2020.model.v1.catalog.ItemType;
23395 amit.gupta 111
import in.shop2020.model.v1.order.WalletReferenceType;
22859 ashik.ali 112
 
113
@Component
114
public class OrderServiceImpl implements OrderService {
115
 
23568 govind 116
	private static final Logger LOGGER = LogManager.getLogger(OrderServiceImpl.class);
22859 ashik.ali 117
 
118
	@Autowired
119
	private InventoryItemRepository inventoryItemRepository;
23395 amit.gupta 120
 
121
	@Autowired
122
	private WalletService walletService;
22859 ashik.ali 123
 
124
	@Autowired
125
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
126
 
127
	@Autowired
128
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
129
 
130
	@Autowired
131
	private CustomerRepository customerRepository;
23566 amit.gupta 132
 
133
	@Autowired
134
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
22859 ashik.ali 135
 
136
	@Autowired
137
	private AddressRepository addressRepository;
138
 
139
	@Autowired
140
	private FofoLineItemRepository fofoLineItemRepository;
141
 
142
	@Autowired
143
	private FofoOrderItemRepository fofoOrderItemRepository;
144
 
145
	@Autowired
146
	private PaymentOptionRepository paymentOptionRepository;
147
 
148
	@Autowired
149
	private ScanRecordRepository scanRecordRepository;
150
 
151
	@Autowired
152
	private FofoOrderRepository fofoOrderRepository;
153
 
154
	@Autowired
155
	private RetailerRepository retailerRepository;
156
 
157
	@Autowired
158
	private UserRepository userRepository;
159
 
160
	@Autowired
161
	private UserAccountRepository userAccountRepository;
162
 
163
	@Autowired
164
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
165
 
166
	@Autowired
167
	private CustomerAddressRepository customerAddressRepository;
168
 
169
	@Autowired
170
	private ItemRepository itemRepository;
171
 
172
	@Autowired
173
	private InsuranceProviderRepository insuranceProviderRepository;
174
 
175
	@Autowired
176
	private InsurancePolicyRepository insurancePolicyRepository;
177
 
178
	@Autowired
179
	private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
180
 
181
	@Autowired
182
	private PricingService pricingService;
183
 
184
	@Autowired
185
	private PrivateDealUserRepository privateDealUserRepository;
186
 
187
	@Autowired
188
	private CounterRepository counterRepository;
189
 
190
	@Autowired
23202 ashik.ali 191
	private FofoStoreRepository fofoStoreRepository;
192
 
193
	@Autowired
23546 ashik.ali 194
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
23365 ashik.ali 195
 
196
	@Autowired
23418 ashik.ali 197
	private PrebookingListingRepository prebookingListingRepository;
198
 
199
	@Autowired
200
	private PrebookingOrderRepository prebookingOrderRepository;
201
 
202
	@Autowired
203
	private PrebookingOrderItemRepository prebookingOrderItemRepository;
204
 
205
	@Autowired
22859 ashik.ali 206
	private SchemeService schemeService;
207
 
23418 ashik.ali 208
	@Autowired
209
	private InventoryService inventoryService;
210
 
211
	@Autowired
212
	private OtpRepository otpRepository;
213
 
22859 ashik.ali 214
	@Override
215
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) throws ProfitMandiBusinessException {
216
 
22872 ashik.ali 217
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
218
 
219
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
220
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
22925 ashik.ali 221
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "VE_1016");
22872 ashik.ali 222
		}
223
 
224
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
225
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
22925 ashik.ali 226
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "VE_1071");
22872 ashik.ali 227
		}
228
 
23370 ashik.ali 229
		if(!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
23369 ashik.ali 230
			LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
231
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER, customCustomer.getGstNumber(), "VE_1072");
232
		}
233
 
22859 ashik.ali 234
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
22872 ashik.ali 235
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
22859 ashik.ali 236
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
237
 
23418 ashik.ali 238
		Map<Integer, Integer> prebookingOrderItemIdQuantityMap = new HashMap<>(); // for prebooking order adjustment
23377 ashik.ali 239
 
22859 ashik.ali 240
		float totalAmount = 0;
241
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
22872 ashik.ali 242
			//itemIds.add(customFofoOrderItem.getItemId());
23418 ashik.ali 243
			if(customFofoOrderItem.isPrebookingOrder()) {
244
				prebookingOrderItemIdQuantityMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
245
			}
23377 ashik.ali 246
			Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
247
			if(!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.size()){
22859 ashik.ali 248
				itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
249
			}
250
			if(!(customFofoOrderItem.getSellingPrice() > 0)){
251
				lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
252
			}else{
22863 ashik.ali 253
				totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
254
				totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
22859 ashik.ali 255
				for(SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
256
					if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
257
						totalAmount = totalAmount + serialNumberDetail.getAmount();
258
					}
259
				}
260
			}
261
 
22872 ashik.ali 262
			itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
22859 ashik.ali 263
		}
264
		if(!itemIdQuantity.isEmpty()){
265
			// if item quantity does not match with given serialnumbers size
266
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
22925 ashik.ali 267
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
22859 ashik.ali 268
			//return "error";
269
		}
270
 
23427 amit.gupta 271
		List<PrebookingListing> prebookingListings = new ArrayList<>();
272
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap  = new HashMap<>();
273
		List<PrebookingOrder> prebookingOrders = new ArrayList<>();
274
		float prebookingOrdersTotalAmount = 0;
275
		if(!prebookingOrderItemIdQuantityMap.isEmpty()) {
276
			prebookingListings = prebookingListingRepository.selectAllByItemIds(prebookingOrderItemIdQuantityMap.keySet());
277
			itemIdPrebookingListingMap = this.prebookingListingsToItemIdPrebookingListingMap(prebookingListings);
278
			prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId, customCustomer.getMobileNumber(), prebookingOrderItemIdQuantityMap.keySet());
279
			prebookingOrdersTotalAmount = this.calculatePrebookingOrdersAmount(prebookingOrders, prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);
280
		}
22859 ashik.ali 281
 
23418 ashik.ali 282
		this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount - prebookingOrdersTotalAmount);
283
 
22859 ashik.ali 284
		if(!lineItemPrice.isEmpty()){
285
			// given fofo line item price must be greater than zero
286
			LOGGER.error("requested itemId's selling price must greater than 0");
22925 ashik.ali 287
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
22859 ashik.ali 288
		}
289
 
22872 ashik.ali 290
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
22859 ashik.ali 291
 
22872 ashik.ali 292
		this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 293
 
294
 
22872 ashik.ali 295
		List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
296
		if(items.size() != itemIdCustomFofoOrderItemMap.keySet().size()){
297
			LOGGER.error("Requested ItemIds not found in catalog");
298
			// invalid itemIds 
22925 ashik.ali 299
			throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(), "FFORDR_1003");
22872 ashik.ali 300
		}
301
 
22859 ashik.ali 302
		Map<Integer, Item>  itemMap = this.toItemMap(items);
23418 ashik.ali 303
 
22859 ashik.ali 304
		Set<Integer> nonSerializedItemIds = new HashSet<>();
305
		Set<String> serialNumbers = new HashSet<>();
306
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
307
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
308
		Map<String, String> serialNumberModelName = new HashMap<>();
309
		Map<String, String> serialNumberBrand = new HashMap<>();
22872 ashik.ali 310
		for (CustomFofoOrderItem customFofoOrderItem: createOrderRequest.getFofoOrderItems()){
311
			Item item = itemMap.get(customFofoOrderItem.getItemId());
22859 ashik.ali 312
			if (item.getType().equals(ItemType.SERIALIZED)){
22872 ashik.ali 313
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
22859 ashik.ali 314
					serialNumbers.add(serialNumberDetail.getSerialNumber());
315
					if(serialNumberDetail.isInsurance()){
22872 ashik.ali 316
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 317
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
23393 amit.gupta 318
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(), (item.getModelName() + item.getModelNumber()).trim());
22859 ashik.ali 319
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
320
					}
321
				}
322
			}
323
			else{
22872 ashik.ali 324
				nonSerializedItemIds.add(customFofoOrderItem.getItemId());
22859 ashik.ali 325
			}
326
		}
23418 ashik.ali 327
 
22859 ashik.ali 328
		Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
329
		Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
23382 amit.gupta 330
		//Map<String, Float> serialNumberItemPrice = new HashMap<>();
23418 ashik.ali 331
 
23397 amit.gupta 332
		if (!serialNumbers.isEmpty()){
333
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, serialNumbers);
334
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
335
			for (InventoryItem inventoryItem : serializedInventoryItems){
336
				if (inventoryItem.getGoodQuantity() == 1){
337
					if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())){
338
						serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
23418 ashik.ali 339
					}else{
23397 amit.gupta 340
						Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
341
						itemIdInventoryItems.add(inventoryItem);
342
						serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
343
					}
344
				}
345
			}
346
		}
23418 ashik.ali 347
 
22859 ashik.ali 348
		if (!nonSerializedItemIds.isEmpty()){
349
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId, nonSerializedItemIds);
22872 ashik.ali 350
			LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
22859 ashik.ali 351
			for (InventoryItem it : nonSerializedInventoryItems){
352
				if (it.getGoodQuantity() > 0){
353
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
354
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
23383 ashik.ali 355
					}else{
22859 ashik.ali 356
						Set<InventoryItem> tmp = new HashSet<>();
357
						tmp.add(it);
358
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
359
					}
360
				}
361
			}
362
		}
363
 
22872 ashik.ali 364
		this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 365
 
366
		Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
367
		Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
368
 
369
		LOGGER.info("itemMap keys {}", itemMap.keySet());
370
		//Lets reduce quantity and decide what inventory items to use.
371
		for (Item item : items){
372
			if (item.getType().equals(ItemType.SERIALIZED)){
373
				//TODO:handle null
22872 ashik.ali 374
				if (serializedInventoryItemMap.get(item.getId()) == null || itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().size() != serializedInventoryItemMap.get(item.getId()).size()){
22859 ashik.ali 375
					//not enough serial numbers
376
					//LOGGER.info("serialNumbers {}", serialNumbers);
22872 ashik.ali 377
					//LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
378
					LOGGER.error("itemId {} => mismatch size of requested serial numbers", item.getId());
22955 ashik.ali 379
					Function<SerialNumberDetail, String> serialNumberDetailToSerialNumberFunction = new Function<SerialNumberDetail, String>() {
380
						@Override
381
						public String apply(SerialNumberDetail serialNumberDetail) {
382
							return serialNumberDetail.getSerialNumber();
383
						}
384
					};
385
					throw new ProfitMandiBusinessException("invalidSerialNumbers", itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream().map(serialNumberDetailToSerialNumberFunction).collect(Collectors.toList()), "FFORDR_1004");
22872 ashik.ali 386
				}
22859 ashik.ali 387
				Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
22872 ashik.ali 388
				for (InventoryItem inventoryItem : inventoryItemsSerializedserialized){
389
					inventoryItem.setGoodQuantity(0);
390
					inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
22859 ashik.ali 391
				}
392
				inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
393
			}
394
			else{
395
				Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
22872 ashik.ali 396
				int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
22859 ashik.ali 397
				int totalLeft = quantityToBill;
398
				Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
399
				if (inventoryItemsNonSerialized!=null){
400
					for (InventoryItem inventoryItem : inventoryItemsNonSerialized){
401
						if (totalLeft > 0){
402
							int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
403
							inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
404
							inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity()  - toUse);
405
							totalLeft = totalLeft - toUse;
406
							inventoryItemsNonSerializedUsed.add(inventoryItem);
407
						}
408
					}
409
				}
410
 
411
				if (totalLeft > 0){
412
					//not enough quanity for non-serialized
413
					LOGGER.error("not enough quanity for non-serialized");
22925 ashik.ali 414
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft, "FFORDR_1005");
22859 ashik.ali 415
				}
416
				inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
417
			}
418
		}
419
 
22872 ashik.ali 420
		Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
22859 ashik.ali 421
 
22872 ashik.ali 422
		this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
23202 ashik.ali 423
 
424
		String fofoStoreCode = this.getFofoStoreCode(fofoId);
22859 ashik.ali 425
 
23202 ashik.ali 426
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);
22859 ashik.ali 427
 
428
		Customer customer = this.createAndGetCustomer(customCustomer);
429
 
23191 ashik.ali 430
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());
22859 ashik.ali 431
 
23433 ashik.ali 432
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId, invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
22859 ashik.ali 433
 
434
		this.createPaymentOptions(fofoOrder.getId(), createOrderRequest.getPaymentOptions());
435
 
23433 ashik.ali 436
		this.processPrebookingOrders(fofoId, fofoOrder.getId(), prebookingOrders, prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);
23418 ashik.ali 437
 
23172 ashik.ali 438
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
439
 
440
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
441
 
442
		Integer stateId = null;
443
		if(customerAddress.getState().equals(retailerAddress.getState())){
444
			try{
445
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
446
			}catch(Exception e){
447
				LOGGER.error("Unable to get state rates");
448
			}
449
		}
450
 
22859 ashik.ali 451
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
23393 amit.gupta 452
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(), itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), stateId);
22859 ashik.ali 453
 
454
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
455
 
456
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
457
 
458
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
459
 
460
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
461
		}
462
 
463
		// insurance calculation is insurance flag is enabled
464
		if(!insuranceSerialNumberItemPrice.isEmpty()){
465
			LOGGER.info("Processing for insurence for serialNumbers");
466
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
467
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
468
 
469
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount, insurancePricesMap);
470
 
22872 ashik.ali 471
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap, itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
22859 ashik.ali 472
 
473
			LocalDate customerDateOfBirth = this.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
474
 
475
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
476
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this.createPolicyNumberGenerationSequence();
477
 
478
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(
23394 amit.gupta 479
						fofoOrder.getInvoiceNumber(), fofoId,
22859 ashik.ali 480
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
481
						insuranceSerialNumberSaleAmount.get(entry.getKey()),entry.getValue(),
482
						entry.getKey(), serialNumberModelName.get(entry.getKey()),
483
						serialNumberBrand.get(entry.getKey()), policyNumberGenerationSequence.getSequence(),
484
						insuranceProvider.getId(), customer, customerDateOfBirth, customerAddress);
485
 
486
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()), entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
23395 amit.gupta 487
				String walletDescription = "Sale of " + insurancePolicy.getPolicyNumber() 
488
				+ " for " + fofoOrder.getInvoiceNumber();
489
				walletService.consumeAmountFromWallet(fofoId, insurancePolicy.getId(), 
490
						WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getPurchaseAmount());
22859 ashik.ali 491
 
492
				try{
493
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
494
					insurancePolicy.setPosted(true);
495
				}catch (ProfitMandiBusinessException profitMandiBusinessException) {
496
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
497
				}
498
				insurancePolicyRepository.persist(insurancePolicy);
499
			}
500
		}
23365 ashik.ali 501
		schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
502
 
22859 ashik.ali 503
		return fofoOrder.getId();
504
	}
505
 
23418 ashik.ali 506
	private float calculatePrebookingOrdersAmount(List<PrebookingOrder> prebookingOrders, Map<Integer, Integer> prebookingOrderItemIdQuantityMap, Map<Integer, PrebookingListing> itemIdPrebookingListingMap) {
507
		//List<PrebookingOrder> prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId, customerMobileNumber, prebookingOrderItemIdQuantityMap.keySet());
508
		float totalAmount = 0;
509
		for(PrebookingOrder prebookingOrder : prebookingOrders) {
510
			int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
511
			PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
512
			if(requestedQuantity < prebookingOrder.getAvailableQuantity()) {
513
				LOGGER.info("when requestedQuantity < then requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity, prebookingListing.getAdvanceAmount());
514
				totalAmount = totalAmount + (requestedQuantity * prebookingListing.getAdvanceAmount());
515
			}else if(requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
516
				LOGGER.info("else requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity, prebookingListing.getAdvanceAmount());
517
				totalAmount = totalAmount + (prebookingOrder.getAvailableQuantity() * prebookingListing.getAdvanceAmount());
518
			}
519
		}
520
		return totalAmount;
521
	}
522
 
23433 ashik.ali 523
	private void processPrebookingOrders(int fofoId, int orderId, List<PrebookingOrder> prebookingOrders, Map<Integer, Integer> prebookingOrderItemIdQuantityMap, Map<Integer, PrebookingListing> itemIdPrebookingListingMap) 
524
	throws ProfitMandiBusinessException{
23418 ashik.ali 525
		//Map<Integer, PrebookingOrder> prebookingOrderIdPrebookingOrderMap = this.prebookingOrdersToPrebookingOrderIdPrebookingOrderMap(prebookingOrders);
526
 
527
		for(PrebookingOrder prebookingOrder : prebookingOrders) {
528
			if(prebookingOrder.getCompleteTimestamp() == null) {
529
				int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
530
 
531
				PrebookingOrderItem prebookingOrderItem = new PrebookingOrderItem();
532
				if(requestedQuantity < prebookingOrder.getAvailableQuantity()) {
533
					prebookingOrder.setAvailableQuantity(prebookingOrder.getAvailableQuantity() - requestedQuantity);
534
					prebookingOrderItem.setQuantity(requestedQuantity);
535
				}else if(requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
536
					prebookingOrderItem.setQuantity(prebookingOrder.getAvailableQuantity());
537
					prebookingOrder.setAvailableQuantity(0);
538
				}
539
				if(prebookingOrder.getAvailableQuantity() == 0) {
540
					prebookingOrder.setCompleteTimestamp(LocalDateTime.now());
541
				}
542
				prebookingOrderRepository.persist(prebookingOrder);
543
 
544
				prebookingOrderItem.setOrderId(orderId);
545
				prebookingOrderItem.setItemId(prebookingOrder.getItemId());
546
				PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
547
				prebookingOrderItem.setAdvanceAmount(prebookingListing.getAdvanceAmount());
548
 
549
				prebookingOrderItemRepository.persist(prebookingOrderItem);
23433 ashik.ali 550
 
551
				walletService.addAmountToWallet(fofoId, prebookingOrder.getId(), WalletReferenceType.PREBOOKING_ORDER, "Advance Amount credited for Prebooking Order", prebookingListing.getAdvanceAmount());
23418 ashik.ali 552
			}
553
 
554
		}
555
	}
556
 
557
	private Map<Integer, PrebookingListing> prebookingListingsToItemIdPrebookingListingMap(List<PrebookingListing> prebookingListings){
558
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
559
		for(PrebookingListing prebookingListing : prebookingListings) {
560
			itemIdPrebookingListingMap.put(prebookingListing.getItemId(), prebookingListing);
561
		}
562
		return itemIdPrebookingListingMap;
563
	}
564
 
565
 
23377 ashik.ali 566
	private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails){
567
		Set<String> serialNumbers = new HashSet<>();
568
		for(SerialNumberDetail serialNumberDetail : serialNumberDetails) {
569
			if(serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
570
				serialNumbers.add(serialNumberDetail.getSerialNumber());
571
			}
572
		}
573
		return serialNumbers;
574
	}
575
 
22859 ashik.ali 576
	@Override
577
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
578
 
579
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
580
 
23552 amit.gupta 581
		List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
582
 
583
		List<CustomPaymentOption> paymentOptions = new ArrayList<>();
584
 
22859 ashik.ali 585
		PdfModel pdfModel = new PdfModel();
23552 amit.gupta 586
 
587
		for(PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
588
			CustomPaymentOption cpi = new CustomPaymentOption();
589
			cpi.setAmount(paymentOptionTransaction.getAmount());
590
			cpi.setPaymentOption(paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());
23558 amit.gupta 591
			paymentOptions.add(cpi);
23552 amit.gupta 592
		}
593
		pdfModel.setPaymentOptions(paymentOptions);
22859 ashik.ali 594
		pdfModel.setAuther("profitmandi");
595
		pdfModel.setTitle("Retailer Invoice");
596
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
597
 
598
		// insurance calculation
22925 ashik.ali 599
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoId, fofoOrder.getInvoiceNumber());
22859 ashik.ali 600
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
601
		final float totalInsuranceTaxRate = 18;
602
		for(InsurancePolicy insurancePolicy : insurancePolicies){
603
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
604
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
605
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #" + insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
606
			customInsurancePolicy.setHsnCode("998716");
607
			customInsurancePolicy.setRate(taxableInsurancePrice);
608
			customInsurancePolicy.setIgstRate(18);
609
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
22936 amit.gupta 610
			customInsurancePolicy.setCgstRate(9);
22859 ashik.ali 611
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 /100);
612
			customInsurancePolicy.setSgstRate(9);
613
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 /100);
614
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
615
			customInsurancePolicies.add(customInsurancePolicy);
616
		}
617
		pdfModel.setInsurancePolicies(customInsurancePolicies);
23001 amit.gupta 618
		List<String> tncs = new ArrayList<>();
619
		tncs.add("I agree that goods received are in good working condition");
620
		tncs.add("Goods once sold cannot be exchanged or taken back");
621
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
622
        if(pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
23370 ashik.ali 623
        		tncs.add("Damage protection provided is the responisibility of Protection Provider only");
23001 amit.gupta 624
        }
625
		pdfModel.setTncs(tncs);
22859 ashik.ali 626
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
627
		CustomCustomer customCustomer = new CustomCustomer();
628
		customCustomer.setFirstName(customer.getFirstName());
629
		customCustomer.setLastName(customer.getLastName());
630
		customCustomer.setEmailId(customer.getEmailId());
631
		customCustomer.setMobileNumber(customer.getMobileNumber());
23370 ashik.ali 632
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
22859 ashik.ali 633
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
634
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
635
		pdfModel.setCustomer(customCustomer);
636
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
637
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
638
 
639
		Retailer retailer = retailerRepository.selectById(fofoId);
640
		PrivateDealUser privateDealUser = null;
641
		try{
642
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
643
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
644
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
645
		}
646
 
647
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
648
		CustomRetailer customRetailer = new CustomRetailer();
649
		customRetailer.setBusinessName(retailer.getName());
650
		customRetailer.setMobileNumber(user.getMobileNumber());
22933 ashik.ali 651
		//customRetailer.setTinNumber(retailer.getNumber());
22859 ashik.ali 652
		if(privateDealUser == null){
653
			customRetailer.setGstNumber(null);
654
		}else{
655
			if(null != privateDealUser.getCounterId()){
656
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
657
				customRetailer.setGstNumber(counter.getGstin());
658
			}else{
659
				customRetailer.setGstNumber(null);
660
			}
661
		}
662
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
663
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
664
		pdfModel.setRetailer(customRetailer);
22925 ashik.ali 665
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
22859 ashik.ali 666
 
667
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
668
		for(FofoOrderItem fofoOrderItem : fofoOrderItems){
669
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
670
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
671
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
672
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
673
 
674
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
23377 ashik.ali 675
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
676
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
677
			//LOGGER.info("serialNumbers {}", serialNumbers);
678
			//LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
679
			if(!serialNumbers.isEmpty()) {
680
				customFofoOrderItem.setDescription(customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
681
			}
22859 ashik.ali 682
			customFofoOrderItem.setRate(taxableSellingPrice);
683
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
684
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
685
			customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice()-fofoOrderItem.getDiscount())*fofoOrderItem.getQuantity());
686
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
687
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
688
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
689
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
690
			customFofoOrderItem.setIgstAmount(igstAmount);
691
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
692
			customFofoOrderItem.setCgstAmount(cgstAmount);
693
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
694
			customFofoOrderItem.setSgstAmount(sgstAmount);
695
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
696
			customerFofoOrderItems.add(customFofoOrderItem);
697
		}
698
		pdfModel.setOrderItems(customerFofoOrderItems);
699
		return pdfModel;
700
	}
701
 
702
	public String getBillingAddress(CustomerAddress customerAddress) {
703
		StringBuilder address = new StringBuilder();
704
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
705
			address.append(customerAddress.getLine1());
706
			address.append(", ");
707
		}
708
 
709
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
710
			address.append(customerAddress.getLine2());
711
			address.append(", ");
712
		}
713
 
714
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
715
			address.append(customerAddress.getLandmark());
716
			address.append(", ");
717
		}
718
 
719
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
720
			address.append(customerAddress.getCity());
721
			address.append(", ");
722
		}
723
 
724
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
725
			address.append(customerAddress.getState());
726
		}
727
 
728
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
729
			address.append("- ");
730
			address.append(customerAddress.getPinCode());
731
		}
732
 
733
		return address.toString();
734
	}
735
 
736
	@Override
737
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException{
738
		try{
739
			JSONObject cartObject = new JSONObject(cartJson);
740
			Iterator<?> keys = cartObject.keys();
741
 
742
			Set<Integer> itemIds = new HashSet<>();
743
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
744
 
745
			while( keys.hasNext() ) {
746
				String key = (String)keys.next();
747
				if ( cartObject.get(key) instanceof JSONObject ) {
748
					LOGGER.info(cartObject.get(key).toString());
749
				}
750
				CartFofo cf = new CartFofo();
751
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
752
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
753
 
754
				if (cf.getQuantity() <= 0){
755
					continue;
756
				}
757
				cartItems.add(cf);
758
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
759
			}
760
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
761
			if (itemIds.size() > 0){
762
				List<Item> items = itemRepository.selectByIds(itemIds);
763
				for (Item i : items){
764
					itemMap.put(i.getId(), i);
765
				}
766
 
767
			}
768
			for (CartFofo cf : cartItems){
769
				Item i = itemMap.get(cf.getItemId());
770
				if (i == null){
771
					continue;
772
				}
773
				cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
774
				cf.setItemType(i.getType());
775
			}
776
			return cartItems;
777
		}catch (Exception e) {
778
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 779
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 780
		}
781
	}
782
 
23202 ashik.ali 783
	@Override
784
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue, String startTimeString,
785
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
786
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
787
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
788
		long countItems = 0;
789
		List<FofoOrder> fofoOrders = new ArrayList<>();
790
 
791
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
792
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
793
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime);
794
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
795
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
796
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);
797
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
798
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
799
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);
800
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
801
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
802
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);
803
		}else{
804
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
23297 ashik.ali 805
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);
23202 ashik.ali 806
		}
807
		Map<String, Object> map = new HashMap<>();
808
 
809
		map.put("saleHistories", fofoOrders);
810
		map.put("start", offset + 1);
811
		map.put("size", countItems);
812
		map.put("searchType", searchType);
23351 ashik.ali 813
		map.put("searchTypes", SearchType.values());
23202 ashik.ali 814
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
815
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
816
		if (fofoOrders.size() < limit){
817
			map.put("end", offset + fofoOrders.size());
818
		}
819
		else{
820
			map.put("end", offset + limit);
821
		}
822
		return map;
823
	}
824
 
825
	@Override
826
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue, String startTimeString,
827
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
828
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
829
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
830
		List<FofoOrder> fofoOrders = new ArrayList<>();
831
 
832
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
833
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
834
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
835
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
836
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
837
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
838
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
839
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
840
		}else{
841
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
842
		}
843
		Map<String, Object> map = new HashMap<>();
844
 
845
		map.put("saleHistories", fofoOrders);
846
		return map;
847
	}
848
 
849
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException{
850
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 851
		return fofoStore.getCode();
23202 ashik.ali 852
	}
853
 
854
 
23191 ashik.ali 855
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId){
856
		CustomerAddress customerAddress = null;
857
		try{
858
			//CustomAddress customAddress = customCustomer.getAddress();
859
			customerAddress = customerAddressRepository.selectByParams(
860
					customAddress.getName(), customAddress.getLine1(), customAddress.getLine2(),
861
					customAddress.getLandmark(),customAddress.getCity(), customAddress.getPinCode(),
862
					customAddress.getState(), customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
863
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
864
			LOGGER.warn("Customer address not found : ", profitMandiBusinessException);
865
			customerAddress = new CustomerAddress();
866
			this.setCustomerAddress(customerAddress, customAddress);
867
			customerAddress.setCustomerId(customerId);
868
		}
869
		customerAddressRepository.persist(customerAddress);
870
		return customerAddress;
871
	}
872
 
22859 ashik.ali 873
	private String getValidName(String name){
874
		return name!=null?name:"";
875
	}
876
 
877
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){
23377 ashik.ali 878
		Set<String> serialNumbers = new HashSet<>();
879
		for(FofoLineItem fofoLineItem : fofoLineItems) {
23381 amit.gupta 880
			if(fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
23377 ashik.ali 881
				serialNumbers.add(fofoLineItem.getSerialNumber());
22955 ashik.ali 882
			}
23377 ashik.ali 883
		}
884
		return serialNumbers;
22859 ashik.ali 885
	}
886
 
887
 
888
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence(){
889
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
890
		try{
891
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
892
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
893
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
894
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
895
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
896
			policyNumberGenerationSequence.setSequence(1);
897
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
898
		}
899
		return policyNumberGenerationSequence;
900
	}
901
 
902
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber, LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress, InsurancePolicy insurancePolicy){
903
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
904
		gadgetCopsInsuranceModel.setBrand(brand);
905
		gadgetCopsInsuranceModel.setModelName(modelName);
906
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
907
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
908
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
909
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
910
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
911
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
912
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
913
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
914
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
915
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
916
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
917
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
918
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
919
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
920
		return gadgetCopsInsuranceModel;
921
	}
922
 
23394 amit.gupta 923
	private InsurancePolicy createInsurancePolicy(String invoiceNumber, int retailerId, float purchaseAmount, float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand, int policyNumberGenerationSequence, int insuranceProviderId, Customer customer, LocalDate customerDateOfBirth, CustomerAddress customerAddress){
22859 ashik.ali 924
		InsurancePolicy insurancePolicy = new InsurancePolicy();
23394 amit.gupta 925
		insurancePolicy.setInvoiceNumber(invoiceNumber);
22859 ashik.ali 926
		insurancePolicy.setRetailerId(retailerId);
927
		insurancePolicy.setPurchaseAmount(purchaseAmount);
928
		insurancePolicy.setSaleAmount(saleAmount);
929
		insurancePolicy.setSellingPrice(sellingPrice);
930
		insurancePolicy.setSerialNumber(serialNumber);
931
		insurancePolicy.setModelName(modelName);
932
		insurancePolicy.setBrand(brand);
933
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence));
934
		insurancePolicy.setProviderId(insuranceProviderId);
935
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
936
		insurancePolicy.setCustomerLastName(customer.getLastName());
937
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
938
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
939
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
940
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
941
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
942
		insurancePolicy.setCustomerCity(customerAddress.getCity());
943
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
944
		insurancePolicy.setCustomerState(customerAddress.getState());
945
		return insurancePolicy;
946
	}
947
 
22872 ashik.ali 948
	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 949
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
950
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
22872 ashik.ali 951
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 952
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
953
			float itemSellingPrice = entry.getValue();
954
			float itemMargin = itemSellingPrice - itemPurchasePrice;
955
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
956
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
957
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
958
			if(insuranceMargin < (itemMargin * 30 / 100)){
959
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
960
			}
961
		}
962
		if(!invalidInsuranceMarginAmount.isEmpty()){
963
			LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
22925 ashik.ali 964
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount, "FFORDR_1007");
22859 ashik.ali 965
		}
966
	}
967
 
968
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice, Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap) throws ProfitMandiBusinessException{
969
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
970
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
971
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
972
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
973
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
974
			}
975
 
976
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
977
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
978
			}
979
		}
980
 
981
		// insurance sale amount can not be lesser than insurance purchase amount
982
		if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
983
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
22925 ashik.ali 984
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount", invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 985
		}
986
 
987
		if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
988
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
22925 ashik.ali 989
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount", invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 990
		}
991
	}
992
 
22872 ashik.ali 993
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 994
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
995
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
996
		//Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
997
		for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
22872 ashik.ali 998
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
999
			if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()){
1000
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 1001
			}
22872 ashik.ali 1002
			if(entry.getValue().isMop() && customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
1003
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
1004
			}
22859 ashik.ali 1005
		}
1006
 
1007
		if(!invalidMopItemIdPriceMap.isEmpty()){
1008
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 1009
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 1010
		}
1011
 
1012
		if(!invalidMopItemIdPriceMap.isEmpty()){
1013
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 1014
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 1015
		}
1016
	}
1017
 
1018
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString) throws ProfitMandiBusinessException{
1019
		LocalDate customerDateOfBirth = null;
1020
		try{
1021
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
1022
		}catch(DateTimeException dateTimeException){
1023
			LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
22925 ashik.ali 1024
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 1025
		}
1026
		return customerDateOfBirth;
1027
	}
1028
 
1029
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<Integer, Integer> inventoryItemQuantityUsed){
1030
		for(InventoryItem inventoryItem : inventoryItems){
1031
			inventoryItem.setLastScanType(ScanType.SALE);
1032
			inventoryItemRepository.persist(inventoryItem);
1033
			ScanRecord scanRecord = new ScanRecord();
1034
			scanRecord.setInventoryItemId(inventoryItem.getId());
1035
			scanRecord.setFofoId(fofoId);
1036
			//correct this
1037
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1038
			scanRecord.setType(ScanType.SALE);
1039
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1040
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
1041
 
22859 ashik.ali 1042
		}
1043
	}
1044
 
1045
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed){
1046
		for(InventoryItem inventoryItem : inventoryItems){
1047
			FofoLineItem fofoLineItem = new FofoLineItem();
1048
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1049
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1050
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1051
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1052
			fofoLineItemRepository.persist(fofoLineItem);
1053
		}
1054
	}
1055
 
23393 amit.gupta 1056
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId, Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId) throws ProfitMandiBusinessException{
22859 ashik.ali 1057
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1058
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1059
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1060
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1061
		fofoOrderItem.setOrderId(fofoOrderId);
1062
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1063
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
1064
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1065
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1066
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
1067
		if(stateId != null){
1068
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
1069
		}else{
1070
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1071
		}
23393 amit.gupta 1072
		float cost = 0;
22859 ashik.ali 1073
		for(InventoryItem inventoryItem : inventoryItems){
23172 ashik.ali 1074
			if(stateId == null){
1075
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
1076
			}else{
1077
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1078
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1079
			}
23418 ashik.ali 1080
 
22859 ashik.ali 1081
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1082
			break;
1083
		}
23393 amit.gupta 1084
		for(InventoryItem inventoryItem : inventoryItems){
1085
			if(inventoryItem.getSerialNumber() != null) {
1086
				cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
1087
			} else {
1088
				cost += inventoryItem.getUnitPrice();
23382 amit.gupta 1089
			}
1090
		}
23393 amit.gupta 1091
		cost = cost/customFofoOrderItem.getQuantity();
23382 amit.gupta 1092
		fofoOrderItem.setCost(cost);
22859 ashik.ali 1093
		fofoOrderItem.setBrand(item.getBrand());
1094
		fofoOrderItem.setModelName(item.getModelName());
1095
		fofoOrderItem.setModelNumber(item.getModelNumber());
1096
		fofoOrderItem.setColor(item.getColor());
1097
		fofoOrderItemRepository.persist(fofoOrderItem);
1098
		return fofoOrderItem;
1099
	}
1100
 
1101
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId, int itemId, int quantity) throws ProfitMandiBusinessException{
1102
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
1103
			if(currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId){
1104
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId, currentInventorySnapshot.getAvailability() - quantity);
1105
			}
1106
		}
1107
	}
1108
 
23365 ashik.ali 1109
	private void createPaymentOptions(int fofoOrderId, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException{
22859 ashik.ali 1110
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
23371 ashik.ali 1111
			if(customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1112
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
1113
				paymentOptionTransaction.setReferenceId(fofoOrderId);
1114
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1115
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1116
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
1117
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1118
			}
22859 ashik.ali 1119
		}
1120
	}
1121
 
23369 ashik.ali 1122
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
22859 ashik.ali 1123
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1124
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1125
		fofoOrder.setCustomerId(customerId);
1126
		fofoOrder.setFofoId(fofoId);
23370 ashik.ali 1127
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
22859 ashik.ali 1128
		fofoOrder.setTotalAmount(totalAmount);
1129
		fofoOrder.setCustomerAddressId(customerAddressId);
1130
		fofoOrderRepository.persist(fofoOrder);
1131
		return fofoOrder;
1132
	}
1133
 
1134
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
1135
		Customer customer = null;
1136
		try{
1137
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
1138
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1139
			LOGGER.error("Error : ", profitMandiBusinessException);
1140
			customer = new Customer();
1141
		}
23190 ashik.ali 1142
		customer.setFirstName(customCustomer.getFirstName());
1143
		customer.setLastName(customCustomer.getLastName());
1144
		customer.setEmailId(customCustomer.getEmailId());
1145
		customer.setMobileNumber(customCustomer.getMobileNumber());
1146
		customerRepository.persist(customer);
22859 ashik.ali 1147
		return customer;
1148
	}
1149
 
23202 ashik.ali 1150
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId, String fofoStoreCode){
22859 ashik.ali 1151
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1152
		try{
1153
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1154
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1155
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1156
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1157
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23370 ashik.ali 1158
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
22859 ashik.ali 1159
			invoiceNumberGenerationSequence.setSequence(1);
1160
		}
1161
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1162
		return invoiceNumberGenerationSequence;
1163
	}
1164
 
22872 ashik.ali 1165
	private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 1166
 		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1167
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1168
		for (Item i : items){
22872 ashik.ali 1169
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1170
			if (i.getType().equals(ItemType.SERIALIZED)){
1171
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1172
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1173
				}
23202 ashik.ali 1174
			}else{
23377 ashik.ali 1175
				Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1176
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()){
22872 ashik.ali 1177
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1178
				}
1179
			}
1180
		}
1181
 
1182
		if(!invalidItemIdSerialNumbers.isEmpty()){
1183
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1184
			// itemId's are serialized you are saying these are not serialized
22925 ashik.ali 1185
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
22859 ashik.ali 1186
		}
1187
 
1188
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
1189
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1190
			// itemId's are non serialized you are saying these are serialized
22925 ashik.ali 1191
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
22859 ashik.ali 1192
		}
1193
	}
1194
 
22872 ashik.ali 1195
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
1196
		if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
22859 ashik.ali 1197
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1198
		}
1199
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
1200
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
22872 ashik.ali 1201
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
22859 ashik.ali 1202
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
22872 ashik.ali 1203
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
1204
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1205
			if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
22859 ashik.ali 1206
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1207
					itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1208
					Quantity quantity = new Quantity();
1209
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
1210
					quantity.setRequested(customFofoOrderItem.getQuantity());
1211
					itemIdQuantityAvailability.setQuantity(quantity);
1212
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1213
				}
1214
		}
1215
 
1216
		if(!itemIdQuantityAvailabilities.isEmpty()){
1217
			// itemIdQuantity request is not valid
1218
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
22925 ashik.ali 1219
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
22859 ashik.ali 1220
		}
1221
	}
1222
 
22872 ashik.ali 1223
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
1224
		int itemId = 0;
1225
		for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
1226
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1227
			for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
1228
				if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
1229
					itemId = entry.getKey();
1230
					break;
1231
				}
22859 ashik.ali 1232
			}
1233
		}
22872 ashik.ali 1234
		return itemId;
22859 ashik.ali 1235
	}
1236
 
1237
	private Map<Integer, Item> toItemMap(List<Item> items){
22955 ashik.ali 1238
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1239
			@Override
1240
			public Integer apply(Item item) {
1241
				return item.getId();
1242
			}
1243
		};
1244
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1245
			@Override
1246
			public Item apply(Item item) {
1247
				return item;
1248
			}
1249
		};
1250
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1251
	}
1252
 
23190 ashik.ali 1253
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){
22859 ashik.ali 1254
		customerAddress.setName(customAddress.getName());
1255
		customerAddress.setLine1(customAddress.getLine1());
1256
		customerAddress.setLine2(customAddress.getLine2());
1257
		customerAddress.setLandmark(customAddress.getLandmark());
1258
		customerAddress.setCity(customAddress.getCity());
1259
		customerAddress.setPinCode(customAddress.getPinCode());
1260
		customerAddress.setState(customAddress.getState());
1261
		customerAddress.setCountry(customAddress.getCountry());
1262
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1263
	}
1264
 
1265
	private CustomAddress createCustomAddress(Address address){
1266
		CustomAddress customAddress = new CustomAddress();
1267
		customAddress.setName(address.getName());
1268
		customAddress.setLine1(address.getLine1());
1269
		customAddress.setLine2(address.getLine2());
1270
		customAddress.setLandmark(address.getLandmark());
1271
		customAddress.setCity(address.getCity());
1272
		customAddress.setPinCode(address.getPinCode());
1273
		customAddress.setState(address.getState());
1274
		customAddress.setCountry(address.getCountry());
1275
		customAddress.setPhoneNumber(address.getPhoneNumber());
1276
		return customAddress;
1277
	}
1278
 
1279
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
1280
		CustomAddress customAddress = new CustomAddress();
1281
		customAddress.setName(customerAddress.getName());
1282
		customAddress.setLine1(customerAddress.getLine1());
1283
		customAddress.setLine2(customerAddress.getLine2());
1284
		customAddress.setLandmark(customerAddress.getLandmark());
1285
		customAddress.setCity(customerAddress.getCity());
1286
		customAddress.setPinCode(customerAddress.getPinCode());
1287
		customAddress.setState(customerAddress.getState());
1288
		customAddress.setCountry(customerAddress.getCountry());
1289
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1290
		return customAddress;
1291
	}
1292
 
1293
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
1294
	{
23365 ashik.ali 1295
		Set<Integer> paymentOptionIds = new HashSet<>();
1296
 
22859 ashik.ali 1297
		float calculatedAmount = 0;
1298
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
23365 ashik.ali 1299
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1300
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1301
		}
1302
		if(calculatedAmount != totalAmount){
22863 ashik.ali 1303
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
22925 ashik.ali 1304
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1305
		}
23365 ashik.ali 1306
 
1307
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
1308
		if(foundPaymentOptionIds.size() != paymentOptionIds.size()) {
1309
			paymentOptionIds.removeAll(foundPaymentOptionIds);
1310
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds, "FFORDR_1017");
1311
		}
22859 ashik.ali 1312
	}
22925 ashik.ali 1313
 
1314
	@Override
1315
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1316
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1317
		if(!fofoOrderItems.isEmpty()){
1318
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1319
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1320
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1321
			while(fofoOrderItemsIterator.hasNext()){
1322
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1323
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1324
				newFofoOrderItems.add(fofoOrderItem);
1325
				fofoOrderItemsIterator.remove();
1326
			}
1327
			fofoOrderItems = newFofoOrderItems;
1328
		}
1329
		return fofoOrderItems;
1330
	}
1331
 
1332
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
22955 ashik.ali 1333
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1334
			@Override
1335
			public Integer apply(FofoOrderItem fofoOrderItem) {
1336
				return fofoOrderItem.getId();
1337
			}
1338
		};
1339
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1340
	}
1341
 
1342
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
1343
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1344
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1345
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1346
		for(FofoLineItem fofoLineItem : fofoLineItems){
1347
			if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
1348
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1349
				fofoLineItems2.add(fofoLineItem);
1350
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1351
			}else{
1352
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1353
			}
1354
		}
1355
		return fofoOrderItemIdFofoLineItemsMap;
1356
	}
23418 ashik.ali 1357
 
1358
	private String getOtpString(){
1359
		Random rndm_method = new Random();
1360
		String numbers ="0123456789";
1361
		char[] otp = new char[5];
22859 ashik.ali 1362
 
23418 ashik.ali 1363
		for (int i = 0; i < 5; i++){
1364
			otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
1365
		}
1366
		return String.valueOf(otp);
1367
	}
1368
 
1369
	private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount){
1370
		Map<Integer, String> itemIdDescriptionMap = inventoryService.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());
1371
		StringBuilder itemIdAdvanceAmountString = new StringBuilder();
1372
		int index = 0;
1373
		for(Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {
1374
			itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));
1375
			itemIdAdvanceAmountString.append("'s Advance amount [");
1376
			itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());
1377
			itemIdAdvanceAmountString.append("]");
1378
			if(index + 1 < itemIdAdvanceAmount.size()) {
1379
				itemIdAdvanceAmountString.append(", ");
1380
			}
1381
			index++;
1382
		}
1383
		String text = "Dear Customer, {0} is the OTP that you have requested for prebooking orders for items {1} Don't share your OTP with anyone.";
1384
		String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);
1385
		try {
1386
			Utils.sendSms(msg, phone);
1387
		} catch (URISyntaxException e) {
1388
			// TODO Auto-generated catch block
1389
			e.printStackTrace();
1390
		} catch (IOException e) {
1391
			// TODO Auto-generated catch block
1392
			e.printStackTrace();
1393
		}
1394
 
1395
	}
1396
 
1397
	@Override
1398
	public int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber, Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {
1399
		if(!StringUtils.isValidEmailAddress(customerEmailId)){
1400
			LOGGER.error("invalid customer emailId {} ", customerEmailId);
1401
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");
1402
		}
1403
 
1404
		if(!StringUtils.isValidMobile(customerMobileNumber)){
1405
			LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);
1406
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");
1407
		}
1408
 
1409
		List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);
1410
		String otp = null;
1411
		if (otps.size() >= 5){
1412
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId, "FFORDR_1019");
1413
		}
1414
		if (!otps.isEmpty()){
1415
			if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))){
1416
				return otps.get(0).getId();
1417
			}else if(otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))){
1418
				otp = otps.get(0).getOtp();
1419
			}
1420
		}
1421
		if (otp == null || otp.isEmpty()){
1422
			otp = getOtpString();
1423
		}
1424
 
1425
		this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);
1426
 
1427
		Otp otp_bean = new Otp();
1428
		otp_bean.setEmail(customerEmailId);
1429
		otp_bean.setMobile(customerMobileNumber);
1430
		otp_bean.setOtp(otp);
1431
		otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);
1432
		otp_bean.setCreatedOn(LocalDateTime.now());
1433
		otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
1434
		otpRepository.persist(otp_bean);
1435
 
1436
		return otp_bean.getId();
1437
	}
1438
 
1439
	@Override
1440
	public String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)
1441
			throws ProfitMandiBusinessException {
1442
		Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);
1443
		otp.setTryCount(otp.getTryCount() + 1);
1444
		if (!otp.getOtp().equalsIgnoreCase(otpValue)){
1445
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");
1446
		}
1447
		if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())){
1448
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");
1449
		}
1450
		if (otp.getTryCount() >5){
1451
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");
1452
		}
1453
		otp.setExpired(true);
1454
		otp.setVerified(true);
1455
		otpRepository.persist(otp);
1456
 
1457
		return ResponseCodeHolder.getMessage("FFORDR_OK_1002");
1458
	}
1459
 
22859 ashik.ali 1460
}