Subversion Repositories SmartDukaan

Rev

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