Subversion Repositories SmartDukaan

Rev

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