Subversion Repositories SmartDukaan

Rev

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