Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
22925 ashik.ali 1
package com.spice.profitmandi.service.inventory;
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;
23202 ashik.ali 57
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
22859 ashik.ali 58
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
59
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
60
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
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.PaymentOptionType;
66
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
67
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23202 ashik.ali 68
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22859 ashik.ali 69
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
70
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
71
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
72
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
73
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
74
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
75
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
76
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
77
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
78
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
79
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
80
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
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
22859 ashik.ali 169
	private SchemeService schemeService;
170
 
171
	@Override
172
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) throws ProfitMandiBusinessException {
173
 
22872 ashik.ali 174
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
175
 
176
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
177
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
22925 ashik.ali 178
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "VE_1016");
22872 ashik.ali 179
		}
180
 
181
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
182
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
22925 ashik.ali 183
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "VE_1071");
22872 ashik.ali 184
		}
185
 
22859 ashik.ali 186
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
22872 ashik.ali 187
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
22859 ashik.ali 188
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
189
 
190
		float totalAmount = 0;
191
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
22872 ashik.ali 192
			//itemIds.add(customFofoOrderItem.getItemId());
22859 ashik.ali 193
			if(!customFofoOrderItem.getSerialNumberDetails().isEmpty() && customFofoOrderItem.getQuantity() != customFofoOrderItem.getSerialNumberDetails().size()){
194
				itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
195
			}
196
			if(!(customFofoOrderItem.getSellingPrice() > 0)){
197
				lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
198
			}else{
22863 ashik.ali 199
				totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
200
				totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
22859 ashik.ali 201
				for(SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
202
					if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
203
						totalAmount = totalAmount + serialNumberDetail.getAmount();
204
					}
205
				}
206
			}
207
 
22872 ashik.ali 208
			itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
22859 ashik.ali 209
		}
210
		if(!itemIdQuantity.isEmpty()){
211
			// if item quantity does not match with given serialnumbers size
212
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
22925 ashik.ali 213
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
22859 ashik.ali 214
			//return "error";
215
		}
216
 
217
		this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
218
 
219
		if(!lineItemPrice.isEmpty()){
220
			// given fofo line item price must be greater than zero
221
			LOGGER.error("requested itemId's selling price must greater than 0");
22925 ashik.ali 222
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
22859 ashik.ali 223
		}
224
 
22872 ashik.ali 225
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
22859 ashik.ali 226
 
22872 ashik.ali 227
		this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 228
 
229
 
22872 ashik.ali 230
		List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
231
		if(items.size() != itemIdCustomFofoOrderItemMap.keySet().size()){
232
			LOGGER.error("Requested ItemIds not found in catalog");
233
			// invalid itemIds 
22925 ashik.ali 234
			throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(), "FFORDR_1003");
22872 ashik.ali 235
		}
236
 
22859 ashik.ali 237
		Map<Integer, Item>  itemMap = this.toItemMap(items);
238
 
239
		Set<Integer> nonSerializedItemIds = new HashSet<>();
240
		Set<String> serialNumbers = new HashSet<>();
241
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
242
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
243
		Map<String, String> serialNumberModelName = new HashMap<>();
244
		Map<String, String> serialNumberBrand = new HashMap<>();
22872 ashik.ali 245
		for (CustomFofoOrderItem customFofoOrderItem: createOrderRequest.getFofoOrderItems()){
246
			Item item = itemMap.get(customFofoOrderItem.getItemId());
22859 ashik.ali 247
			if (item.getType().equals(ItemType.SERIALIZED)){
22872 ashik.ali 248
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
22859 ashik.ali 249
					serialNumbers.add(serialNumberDetail.getSerialNumber());
250
					if(serialNumberDetail.isInsurance()){
22872 ashik.ali 251
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 252
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
253
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(), item.getModelName());
254
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
255
					}
256
				}
257
			}
258
			else{
22872 ashik.ali 259
				nonSerializedItemIds.add(customFofoOrderItem.getItemId());
22859 ashik.ali 260
			}
261
		}
262
 
263
		Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
264
		Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
265
		Map<Integer, List<Float>> itemIdPriceDropAmount = new HashMap<>();
266
		//Map<String, Float> serialNumberItemPrice = new HashMap<>();
267
 
268
		if (!serialNumbers.isEmpty()){
269
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, serialNumbers);
270
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
271
			for (InventoryItem inventoryItem : serializedInventoryItems){
272
				if (inventoryItem.getGoodQuantity() == 1){
273
					if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())){
274
						serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
275
						itemIdPriceDropAmount.get(inventoryItem.getItemId()).
23116 ashik.ali 276
						add(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
22859 ashik.ali 277
					}
278
					else{
279
						Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
280
						itemIdInventoryItems.add(inventoryItem);
281
						serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
282
						ArrayList<Float> priceDropAmouts = new ArrayList<>();
23116 ashik.ali 283
						priceDropAmouts.add(inventoryItem.getUnitPrice() - (inventoryItem.getPriceDropAmount()));
22859 ashik.ali 284
						itemIdPriceDropAmount.put(inventoryItem.getItemId(), priceDropAmouts);
285
					}
286
				}
287
			}
288
		}
289
 
290
		if (!nonSerializedItemIds.isEmpty()){
291
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId, nonSerializedItemIds);
22872 ashik.ali 292
			LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
22859 ashik.ali 293
			for (InventoryItem it : nonSerializedInventoryItems){
294
				if (it.getGoodQuantity() > 0){
295
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
296
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
297
					}
298
					else{
299
						Set<InventoryItem> tmp = new HashSet<>();
300
						tmp.add(it);
301
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
302
					}
303
				}
304
			}
305
		}
306
 
22872 ashik.ali 307
		this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 308
 
309
		Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
310
		Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
311
 
312
		LOGGER.info("itemMap keys {}", itemMap.keySet());
313
		//Lets reduce quantity and decide what inventory items to use.
314
		for (Item item : items){
315
			if (item.getType().equals(ItemType.SERIALIZED)){
316
				//TODO:handle null
22872 ashik.ali 317
				if (serializedInventoryItemMap.get(item.getId()) == null || itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().size() != serializedInventoryItemMap.get(item.getId()).size()){
22859 ashik.ali 318
					//not enough serial numbers
319
					//LOGGER.info("serialNumbers {}", serialNumbers);
22872 ashik.ali 320
					//LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
321
					LOGGER.error("itemId {} => mismatch size of requested serial numbers", item.getId());
22955 ashik.ali 322
					Function<SerialNumberDetail, String> serialNumberDetailToSerialNumberFunction = new Function<SerialNumberDetail, String>() {
323
						@Override
324
						public String apply(SerialNumberDetail serialNumberDetail) {
325
							return serialNumberDetail.getSerialNumber();
326
						}
327
					};
328
					throw new ProfitMandiBusinessException("invalidSerialNumbers", itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream().map(serialNumberDetailToSerialNumberFunction).collect(Collectors.toList()), "FFORDR_1004");
22872 ashik.ali 329
				}
22859 ashik.ali 330
				Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
22872 ashik.ali 331
				for (InventoryItem inventoryItem : inventoryItemsSerializedserialized){
332
					inventoryItem.setGoodQuantity(0);
333
					inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
22859 ashik.ali 334
				}
335
				inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
336
			}
337
			else{
338
				Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
22872 ashik.ali 339
				int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
22859 ashik.ali 340
				int totalLeft = quantityToBill;
341
				Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
342
				if (inventoryItemsNonSerialized!=null){
343
					for (InventoryItem inventoryItem : inventoryItemsNonSerialized){
344
						if (totalLeft > 0){
345
							int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
346
							inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
347
							inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity()  - toUse);
348
							totalLeft = totalLeft - toUse;
349
							inventoryItemsNonSerializedUsed.add(inventoryItem);
350
						}
351
					}
352
				}
353
 
354
				if (totalLeft > 0){
355
					//not enough quanity for non-serialized
356
					LOGGER.error("not enough quanity for non-serialized");
22925 ashik.ali 357
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft, "FFORDR_1005");
22859 ashik.ali 358
				}
359
				inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
360
			}
361
		}
362
 
22872 ashik.ali 363
		Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
22859 ashik.ali 364
 
22872 ashik.ali 365
		this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
23202 ashik.ali 366
 
367
		String fofoStoreCode = this.getFofoStoreCode(fofoId);
22859 ashik.ali 368
 
23202 ashik.ali 369
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);
22859 ashik.ali 370
 
371
		Customer customer = this.createAndGetCustomer(customCustomer);
372
 
23191 ashik.ali 373
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());
22859 ashik.ali 374
 
375
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), fofoId, invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
376
 
377
		this.createPaymentOptions(fofoOrder.getId(), createOrderRequest.getPaymentOptions());
378
 
23172 ashik.ali 379
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
380
 
381
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
382
 
383
		Integer stateId = null;
384
		if(customerAddress.getState().equals(retailerAddress.getState())){
385
			try{
386
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
387
			}catch(Exception e){
388
				LOGGER.error("Unable to get state rates");
389
			}
390
		}
391
 
22859 ashik.ali 392
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
23172 ashik.ali 393
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(), itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), itemIdPriceDropAmount, stateId);
22859 ashik.ali 394
 
395
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
396
 
397
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
398
 
399
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
400
 
401
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
402
		}
403
 
404
		// insurance calculation is insurance flag is enabled
405
		if(!insuranceSerialNumberItemPrice.isEmpty()){
406
			LOGGER.info("Processing for insurence for serialNumbers");
407
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
408
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
409
 
410
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount, insurancePricesMap);
411
 
22872 ashik.ali 412
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap, itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
22859 ashik.ali 413
 
414
			LocalDate customerDateOfBirth = this.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
415
 
416
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
417
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this.createPolicyNumberGenerationSequence();
418
 
419
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(
420
						invoiceNumberGenerationSequence, fofoId,
421
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
422
						insuranceSerialNumberSaleAmount.get(entry.getKey()),entry.getValue(),
423
						entry.getKey(), serialNumberModelName.get(entry.getKey()),
424
						serialNumberBrand.get(entry.getKey()), policyNumberGenerationSequence.getSequence(),
425
						insuranceProvider.getId(), customer, customerDateOfBirth, customerAddress);
426
 
427
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()), entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
428
 
429
				try{
430
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
431
					insurancePolicy.setPosted(true);
432
				}catch (ProfitMandiBusinessException profitMandiBusinessException) {
433
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
434
				}
435
				insurancePolicyRepository.persist(insurancePolicy);
436
			}
437
		}
438
		float cashback = schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
439
		if(cashback > 0){
440
			fofoOrder.setCashback(cashback);
441
			fofoOrderRepository.persist(fofoOrder);
442
		}
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
 
959
	private void createPaymentOptions(int fofoOrderId, Set<CustomPaymentOption> customPaymentOptions){
960
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
961
			if(customPaymentOption.getAmount() > 0){
962
				PaymentOption paymentOption = new PaymentOption();
963
				paymentOption.setOrderId(fofoOrderId);
964
				paymentOption.setAmount(customPaymentOption.getAmount());
965
				paymentOption.setType(PaymentOptionType.valueOf(customPaymentOption.getType()));
966
				paymentOptionRepository.persist(paymentOption);
967
			}
968
		}
969
	}
970
 
971
	private FofoOrder createAndGetFofoOrder(int customerId, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
972
		FofoOrder fofoOrder = new FofoOrder();
973
		fofoOrder.setCustomerId(customerId);
974
		fofoOrder.setFofoId(fofoId);
975
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
976
		fofoOrder.setTotalAmount(totalAmount);
977
		fofoOrder.setCustomerAddressId(customerAddressId);
978
		fofoOrderRepository.persist(fofoOrder);
979
		return fofoOrder;
980
	}
981
 
982
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
983
		Customer customer = null;
984
		try{
985
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
986
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
987
			LOGGER.error("Error : ", profitMandiBusinessException);
988
			customer = new Customer();
989
		}
23190 ashik.ali 990
		customer.setFirstName(customCustomer.getFirstName());
991
		customer.setLastName(customCustomer.getLastName());
992
		customer.setEmailId(customCustomer.getEmailId());
993
		customer.setMobileNumber(customCustomer.getMobileNumber());
994
		customerRepository.persist(customer);
22859 ashik.ali 995
		return customer;
996
	}
997
 
23202 ashik.ali 998
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId, String fofoStoreCode){
22859 ashik.ali 999
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1000
		try{
1001
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1002
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1003
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1004
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1005
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23350 amit.gupta 1006
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode + "-");
22859 ashik.ali 1007
			invoiceNumberGenerationSequence.setSequence(1);
1008
		}
1009
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1010
		return invoiceNumberGenerationSequence;
1011
	}
1012
 
22872 ashik.ali 1013
	private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 1014
 		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1015
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1016
		for (Item i : items){
22872 ashik.ali 1017
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1018
			if (i.getType().equals(ItemType.SERIALIZED)){
1019
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1020
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1021
				}
23202 ashik.ali 1022
			}else{
22872 ashik.ali 1023
				if (customFofoOrderItem == null || !customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1024
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1025
				}
1026
			}
1027
		}
1028
 
1029
		if(!invalidItemIdSerialNumbers.isEmpty()){
1030
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1031
			// itemId's are serialized you are saying these are not serialized
22925 ashik.ali 1032
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
22859 ashik.ali 1033
		}
1034
 
1035
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
1036
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1037
			// itemId's are non serialized you are saying these are serialized
22925 ashik.ali 1038
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
22859 ashik.ali 1039
		}
1040
	}
1041
 
22872 ashik.ali 1042
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
1043
		if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
22859 ashik.ali 1044
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1045
		}
1046
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
1047
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
22872 ashik.ali 1048
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
22859 ashik.ali 1049
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
22872 ashik.ali 1050
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
1051
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1052
			if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
22859 ashik.ali 1053
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1054
					itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1055
					Quantity quantity = new Quantity();
1056
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
1057
					quantity.setRequested(customFofoOrderItem.getQuantity());
1058
					itemIdQuantityAvailability.setQuantity(quantity);
1059
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1060
				}
1061
 
1062
		}
1063
 
1064
 
1065
 
1066
		if(!itemIdQuantityAvailabilities.isEmpty()){
1067
			// itemIdQuantity request is not valid
1068
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
22925 ashik.ali 1069
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
22859 ashik.ali 1070
		}
1071
	}
1072
 
22872 ashik.ali 1073
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
1074
		int itemId = 0;
1075
		for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
1076
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1077
			for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
1078
				if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
1079
					itemId = entry.getKey();
1080
					break;
1081
				}
22859 ashik.ali 1082
			}
1083
		}
22872 ashik.ali 1084
		return itemId;
22859 ashik.ali 1085
	}
1086
 
1087
	private Map<Integer, Item> toItemMap(List<Item> items){
22955 ashik.ali 1088
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1089
			@Override
1090
			public Integer apply(Item item) {
1091
				return item.getId();
1092
			}
1093
		};
1094
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1095
			@Override
1096
			public Item apply(Item item) {
1097
				return item;
1098
			}
1099
		};
1100
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1101
	}
1102
 
23190 ashik.ali 1103
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){
22859 ashik.ali 1104
		customerAddress.setName(customAddress.getName());
1105
		customerAddress.setLine1(customAddress.getLine1());
1106
		customerAddress.setLine2(customAddress.getLine2());
1107
		customerAddress.setLandmark(customAddress.getLandmark());
1108
		customerAddress.setCity(customAddress.getCity());
1109
		customerAddress.setPinCode(customAddress.getPinCode());
1110
		customerAddress.setState(customAddress.getState());
1111
		customerAddress.setCountry(customAddress.getCountry());
1112
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1113
	}
1114
 
1115
	private CustomAddress createCustomAddress(Address address){
1116
		CustomAddress customAddress = new CustomAddress();
1117
		customAddress.setName(address.getName());
1118
		customAddress.setLine1(address.getLine1());
1119
		customAddress.setLine2(address.getLine2());
1120
		customAddress.setLandmark(address.getLandmark());
1121
		customAddress.setCity(address.getCity());
1122
		customAddress.setPinCode(address.getPinCode());
1123
		customAddress.setState(address.getState());
1124
		customAddress.setCountry(address.getCountry());
1125
		customAddress.setPhoneNumber(address.getPhoneNumber());
1126
		return customAddress;
1127
	}
1128
 
1129
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
1130
		CustomAddress customAddress = new CustomAddress();
1131
		customAddress.setName(customerAddress.getName());
1132
		customAddress.setLine1(customerAddress.getLine1());
1133
		customAddress.setLine2(customerAddress.getLine2());
1134
		customAddress.setLandmark(customerAddress.getLandmark());
1135
		customAddress.setCity(customerAddress.getCity());
1136
		customAddress.setPinCode(customerAddress.getPinCode());
1137
		customAddress.setState(customerAddress.getState());
1138
		customAddress.setCountry(customerAddress.getCountry());
1139
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1140
		return customAddress;
1141
	}
1142
 
1143
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
1144
	{
1145
		float calculatedAmount = 0;
1146
		Set<String> paymentOptionTypes = new HashSet<>();
1147
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
1148
			if(paymentOptionTypes.contains(PaymentOptionType.valueOf(customPaymentOption.getType()))){
1149
				throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType(), "");
1150
			}else{
1151
				paymentOptionTypes.add(customPaymentOption.getType());
1152
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
1153
			}
1154
		}
1155
		if(calculatedAmount != totalAmount){
22863 ashik.ali 1156
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
22925 ashik.ali 1157
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1158
		}
1159
	}
22925 ashik.ali 1160
 
1161
	@Override
1162
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1163
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1164
		if(!fofoOrderItems.isEmpty()){
1165
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1166
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1167
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1168
			while(fofoOrderItemsIterator.hasNext()){
1169
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1170
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1171
				newFofoOrderItems.add(fofoOrderItem);
1172
				fofoOrderItemsIterator.remove();
1173
			}
1174
			fofoOrderItems = newFofoOrderItems;
1175
		}
1176
		return fofoOrderItems;
1177
	}
1178
 
1179
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
22955 ashik.ali 1180
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1181
			@Override
1182
			public Integer apply(FofoOrderItem fofoOrderItem) {
1183
				return fofoOrderItem.getId();
1184
			}
1185
		};
1186
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1187
	}
1188
 
1189
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
1190
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1191
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1192
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1193
		for(FofoLineItem fofoLineItem : fofoLineItems){
1194
			if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
1195
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1196
				fofoLineItems2.add(fofoLineItem);
1197
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1198
			}else{
1199
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1200
			}
1201
		}
1202
		return fofoOrderItemIdFofoLineItemsMap;
1203
	}
22859 ashik.ali 1204
 
1205
}