Subversion Repositories SmartDukaan

Rev

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