Subversion Repositories SmartDukaan

Rev

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