Subversion Repositories SmartDukaan

Rev

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