Subversion Repositories SmartDukaan

Rev

Rev 23365 | Rev 23370 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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