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);
664
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
665
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
666
		if (fofoOrders.size() < limit){
667
			map.put("end", offset + fofoOrders.size());
668
		}
669
		else{
670
			map.put("end", offset + limit);
671
		}
672
		return map;
673
	}
674
 
675
	@Override
676
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue, String startTimeString,
677
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
678
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
679
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
680
		List<FofoOrder> fofoOrders = new ArrayList<>();
681
 
682
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
683
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
684
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
685
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
686
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
687
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
688
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
689
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
690
		}else{
691
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
692
		}
693
		Map<String, Object> map = new HashMap<>();
694
 
695
		map.put("saleHistories", fofoOrders);
696
		return map;
697
	}
698
 
699
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException{
700
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
701
		return fofoStore.getCode().substring(0, 3);
702
	}
703
 
704
 
23191 ashik.ali 705
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId){
706
		CustomerAddress customerAddress = null;
707
		try{
708
			//CustomAddress customAddress = customCustomer.getAddress();
709
			customerAddress = customerAddressRepository.selectByParams(
710
					customAddress.getName(), customAddress.getLine1(), customAddress.getLine2(),
711
					customAddress.getLandmark(),customAddress.getCity(), customAddress.getPinCode(),
712
					customAddress.getState(), customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
713
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
714
			LOGGER.warn("Customer address not found : ", profitMandiBusinessException);
715
			customerAddress = new CustomerAddress();
716
			this.setCustomerAddress(customerAddress, customAddress);
717
			customerAddress.setCustomerId(customerId);
718
		}
719
		customerAddressRepository.persist(customerAddress);
720
		return customerAddress;
721
	}
722
 
22859 ashik.ali 723
	private String getValidName(String name){
724
		return name!=null?name:"";
725
	}
726
 
727
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){
22955 ashik.ali 728
		Function<FofoLineItem, String> fofoLineItemToSerialNumberFunction = new Function<FofoLineItem, String>() {
729
			@Override
730
			public String apply(FofoLineItem fofoLineItem) {
731
				return fofoLineItem.getSerialNumber();
732
			}
733
		};
734
		return fofoLineItems.stream().map(fofoLineItemToSerialNumberFunction).collect(Collectors.toSet());
22859 ashik.ali 735
	}
736
 
737
 
738
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence(){
739
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
740
		try{
741
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
742
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
743
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
744
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
745
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
746
			policyNumberGenerationSequence.setSequence(1);
747
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
748
		}
749
		return policyNumberGenerationSequence;
750
	}
751
 
752
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber, LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress, InsurancePolicy insurancePolicy){
753
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
754
		gadgetCopsInsuranceModel.setBrand(brand);
755
		gadgetCopsInsuranceModel.setModelName(modelName);
756
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
757
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
758
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
759
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
760
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
761
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
762
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
763
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
764
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
765
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
766
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
767
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
768
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
769
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
770
		return gadgetCopsInsuranceModel;
771
	}
772
 
773
	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){
774
		InsurancePolicy insurancePolicy = new InsurancePolicy();
775
		insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
776
		insurancePolicy.setRetailerId(retailerId);
777
		insurancePolicy.setPurchaseAmount(purchaseAmount);
778
		insurancePolicy.setSaleAmount(saleAmount);
779
		insurancePolicy.setSellingPrice(sellingPrice);
780
		insurancePolicy.setSerialNumber(serialNumber);
781
		insurancePolicy.setModelName(modelName);
782
		insurancePolicy.setBrand(brand);
783
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence));
784
		insurancePolicy.setProviderId(insuranceProviderId);
785
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
786
		insurancePolicy.setCustomerLastName(customer.getLastName());
787
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
788
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
789
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
790
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
791
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
792
		insurancePolicy.setCustomerCity(customerAddress.getCity());
793
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
794
		insurancePolicy.setCustomerState(customerAddress.getState());
795
		return insurancePolicy;
796
	}
797
 
22872 ashik.ali 798
	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 799
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
800
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
22872 ashik.ali 801
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 802
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
803
			float itemSellingPrice = entry.getValue();
804
			float itemMargin = itemSellingPrice - itemPurchasePrice;
805
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
806
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
807
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
808
			if(insuranceMargin < (itemMargin * 30 / 100)){
809
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
810
			}
811
		}
812
		if(!invalidInsuranceMarginAmount.isEmpty()){
813
			LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
22925 ashik.ali 814
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount, "FFORDR_1007");
22859 ashik.ali 815
		}
816
	}
817
 
818
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice, Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap) throws ProfitMandiBusinessException{
819
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
820
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
821
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
822
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
823
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
824
			}
825
 
826
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
827
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
828
			}
829
		}
830
 
831
		// insurance sale amount can not be lesser than insurance purchase amount
832
		if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
833
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
22925 ashik.ali 834
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount", invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 835
		}
836
 
837
		if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
838
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
22925 ashik.ali 839
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount", invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 840
		}
841
	}
842
 
22872 ashik.ali 843
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 844
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
845
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
846
		//Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
847
		for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
22872 ashik.ali 848
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
849
			if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()){
850
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 851
			}
22872 ashik.ali 852
			if(entry.getValue().isMop() && customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
853
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
854
			}
22859 ashik.ali 855
		}
856
 
857
		if(!invalidMopItemIdPriceMap.isEmpty()){
858
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 859
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 860
		}
861
 
862
		if(!invalidMopItemIdPriceMap.isEmpty()){
863
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 864
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 865
		}
866
	}
867
 
868
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString) throws ProfitMandiBusinessException{
869
		LocalDate customerDateOfBirth = null;
870
		try{
871
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
872
		}catch(DateTimeException dateTimeException){
873
			LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
22925 ashik.ali 874
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 875
		}
876
		return customerDateOfBirth;
877
	}
878
 
879
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<Integer, Integer> inventoryItemQuantityUsed){
880
		for(InventoryItem inventoryItem : inventoryItems){
881
			inventoryItem.setLastScanType(ScanType.SALE);
882
			inventoryItemRepository.persist(inventoryItem);
883
			ScanRecord scanRecord = new ScanRecord();
884
			scanRecord.setInventoryItemId(inventoryItem.getId());
885
			scanRecord.setFofoId(fofoId);
886
			//correct this
887
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
888
			scanRecord.setType(ScanType.SALE);
889
			scanRecordRepository.persist(scanRecord);
890
		}
891
	}
892
 
893
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed){
894
		for(InventoryItem inventoryItem : inventoryItems){
895
			FofoLineItem fofoLineItem = new FofoLineItem();
896
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
897
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
898
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
899
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
900
			fofoLineItemRepository.persist(fofoLineItem);
901
		}
902
	}
903
 
23172 ashik.ali 904
	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 905
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
906
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
907
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
908
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
909
		fofoOrderItem.setOrderId(fofoOrderId);
910
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
911
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
912
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 913
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
914
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
915
		if(stateId != null){
916
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
917
		}else{
918
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
919
		}
22859 ashik.ali 920
		for(InventoryItem inventoryItem : inventoryItems){
23172 ashik.ali 921
			if(stateId == null){
922
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
923
			}else{
924
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
925
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
926
			}
927
 
22859 ashik.ali 928
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
929
			break;
930
		}
931
		List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoOrderItem.getItemId());
932
		float cost = 0;
933
		if (priceDropAmounts!=null){
934
			for (Float pda : priceDropAmounts){
935
				cost = cost + pda;
936
			}
937
		}
938
		else{
939
			cost = customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
940
		}
941
		fofoOrderItem.setCost(cost);
942
		fofoOrderItem.setBrand(item.getBrand());
943
		fofoOrderItem.setModelName(item.getModelName());
944
		fofoOrderItem.setModelNumber(item.getModelNumber());
945
		fofoOrderItem.setColor(item.getColor());
946
		fofoOrderItemRepository.persist(fofoOrderItem);
947
		return fofoOrderItem;
948
	}
949
 
950
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId, int itemId, int quantity) throws ProfitMandiBusinessException{
951
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
952
			if(currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId){
953
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId, currentInventorySnapshot.getAvailability() - quantity);
954
			}
955
		}
956
	}
957
 
958
	private void createPaymentOptions(int fofoOrderId, Set<CustomPaymentOption> customPaymentOptions){
959
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
960
			if(customPaymentOption.getAmount() > 0){
961
				PaymentOption paymentOption = new PaymentOption();
962
				paymentOption.setOrderId(fofoOrderId);
963
				paymentOption.setAmount(customPaymentOption.getAmount());
964
				paymentOption.setType(PaymentOptionType.valueOf(customPaymentOption.getType()));
965
				paymentOptionRepository.persist(paymentOption);
966
			}
967
		}
968
	}
969
 
970
	private FofoOrder createAndGetFofoOrder(int customerId, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
971
		FofoOrder fofoOrder = new FofoOrder();
972
		fofoOrder.setCustomerId(customerId);
973
		fofoOrder.setFofoId(fofoId);
974
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
975
		fofoOrder.setTotalAmount(totalAmount);
976
		fofoOrder.setCustomerAddressId(customerAddressId);
977
		fofoOrderRepository.persist(fofoOrder);
978
		return fofoOrder;
979
	}
980
 
981
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
982
		Customer customer = null;
983
		try{
984
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
985
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
986
			LOGGER.error("Error : ", profitMandiBusinessException);
987
			customer = new Customer();
988
		}
23190 ashik.ali 989
		customer.setFirstName(customCustomer.getFirstName());
990
		customer.setLastName(customCustomer.getLastName());
991
		customer.setEmailId(customCustomer.getEmailId());
992
		customer.setMobileNumber(customCustomer.getMobileNumber());
993
		customerRepository.persist(customer);
22859 ashik.ali 994
		return customer;
995
	}
996
 
23202 ashik.ali 997
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId, String fofoStoreCode){
22859 ashik.ali 998
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
999
		try{
1000
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1001
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1002
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1003
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1004
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23350 amit.gupta 1005
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode + "-");
22859 ashik.ali 1006
			invoiceNumberGenerationSequence.setSequence(1);
1007
		}
1008
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1009
		return invoiceNumberGenerationSequence;
1010
	}
1011
 
22872 ashik.ali 1012
	private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 1013
 		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1014
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1015
		for (Item i : items){
22872 ashik.ali 1016
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1017
			if (i.getType().equals(ItemType.SERIALIZED)){
1018
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1019
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1020
				}
23202 ashik.ali 1021
			}else{
22872 ashik.ali 1022
				if (customFofoOrderItem == null || !customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1023
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1024
				}
1025
			}
1026
		}
1027
 
1028
		if(!invalidItemIdSerialNumbers.isEmpty()){
1029
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1030
			// itemId's are serialized you are saying these are not serialized
22925 ashik.ali 1031
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
22859 ashik.ali 1032
		}
1033
 
1034
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
1035
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1036
			// itemId's are non serialized you are saying these are serialized
22925 ashik.ali 1037
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
22859 ashik.ali 1038
		}
1039
	}
1040
 
22872 ashik.ali 1041
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
1042
		if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
22859 ashik.ali 1043
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1044
		}
1045
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
1046
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
22872 ashik.ali 1047
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
22859 ashik.ali 1048
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
22872 ashik.ali 1049
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
1050
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1051
			if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
22859 ashik.ali 1052
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1053
					itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1054
					Quantity quantity = new Quantity();
1055
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
1056
					quantity.setRequested(customFofoOrderItem.getQuantity());
1057
					itemIdQuantityAvailability.setQuantity(quantity);
1058
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1059
				}
1060
 
1061
		}
1062
 
1063
 
1064
 
1065
		if(!itemIdQuantityAvailabilities.isEmpty()){
1066
			// itemIdQuantity request is not valid
1067
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
22925 ashik.ali 1068
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
22859 ashik.ali 1069
		}
1070
	}
1071
 
22872 ashik.ali 1072
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
1073
		int itemId = 0;
1074
		for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
1075
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1076
			for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
1077
				if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
1078
					itemId = entry.getKey();
1079
					break;
1080
				}
22859 ashik.ali 1081
			}
1082
		}
22872 ashik.ali 1083
		return itemId;
22859 ashik.ali 1084
	}
1085
 
1086
	private Map<Integer, Item> toItemMap(List<Item> items){
22955 ashik.ali 1087
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1088
			@Override
1089
			public Integer apply(Item item) {
1090
				return item.getId();
1091
			}
1092
		};
1093
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1094
			@Override
1095
			public Item apply(Item item) {
1096
				return item;
1097
			}
1098
		};
1099
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1100
	}
1101
 
23190 ashik.ali 1102
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){
22859 ashik.ali 1103
		customerAddress.setName(customAddress.getName());
1104
		customerAddress.setLine1(customAddress.getLine1());
1105
		customerAddress.setLine2(customAddress.getLine2());
1106
		customerAddress.setLandmark(customAddress.getLandmark());
1107
		customerAddress.setCity(customAddress.getCity());
1108
		customerAddress.setPinCode(customAddress.getPinCode());
1109
		customerAddress.setState(customAddress.getState());
1110
		customerAddress.setCountry(customAddress.getCountry());
1111
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1112
	}
1113
 
1114
	private CustomAddress createCustomAddress(Address address){
1115
		CustomAddress customAddress = new CustomAddress();
1116
		customAddress.setName(address.getName());
1117
		customAddress.setLine1(address.getLine1());
1118
		customAddress.setLine2(address.getLine2());
1119
		customAddress.setLandmark(address.getLandmark());
1120
		customAddress.setCity(address.getCity());
1121
		customAddress.setPinCode(address.getPinCode());
1122
		customAddress.setState(address.getState());
1123
		customAddress.setCountry(address.getCountry());
1124
		customAddress.setPhoneNumber(address.getPhoneNumber());
1125
		return customAddress;
1126
	}
1127
 
1128
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
1129
		CustomAddress customAddress = new CustomAddress();
1130
		customAddress.setName(customerAddress.getName());
1131
		customAddress.setLine1(customerAddress.getLine1());
1132
		customAddress.setLine2(customerAddress.getLine2());
1133
		customAddress.setLandmark(customerAddress.getLandmark());
1134
		customAddress.setCity(customerAddress.getCity());
1135
		customAddress.setPinCode(customerAddress.getPinCode());
1136
		customAddress.setState(customerAddress.getState());
1137
		customAddress.setCountry(customerAddress.getCountry());
1138
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1139
		return customAddress;
1140
	}
1141
 
1142
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
1143
	{
1144
		float calculatedAmount = 0;
1145
		Set<String> paymentOptionTypes = new HashSet<>();
1146
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
1147
			if(paymentOptionTypes.contains(PaymentOptionType.valueOf(customPaymentOption.getType()))){
1148
				throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType(), "");
1149
			}else{
1150
				paymentOptionTypes.add(customPaymentOption.getType());
1151
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
1152
			}
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
		}
1158
	}
22925 ashik.ali 1159
 
1160
	@Override
1161
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1162
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1163
		if(!fofoOrderItems.isEmpty()){
1164
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1165
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1166
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1167
			while(fofoOrderItemsIterator.hasNext()){
1168
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1169
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1170
				newFofoOrderItems.add(fofoOrderItem);
1171
				fofoOrderItemsIterator.remove();
1172
			}
1173
			fofoOrderItems = newFofoOrderItems;
1174
		}
1175
		return fofoOrderItems;
1176
	}
1177
 
1178
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
22955 ashik.ali 1179
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1180
			@Override
1181
			public Integer apply(FofoOrderItem fofoOrderItem) {
1182
				return fofoOrderItem.getId();
1183
			}
1184
		};
1185
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1186
	}
1187
 
1188
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
1189
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1190
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1191
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1192
		for(FofoLineItem fofoLineItem : fofoLineItems){
1193
			if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
1194
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1195
				fofoLineItems2.add(fofoLineItem);
1196
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1197
			}else{
1198
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1199
			}
1200
		}
1201
		return fofoOrderItemIdFofoLineItemsMap;
1202
	}
22859 ashik.ali 1203
 
1204
}