Subversion Repositories SmartDukaan

Rev

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