Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23365 ashik.ali 1
package com.spice.profitmandi.service.order;
22859 ashik.ali 2
 
3
import java.time.DateTimeException;
4
import java.time.LocalDate;
23202 ashik.ali 5
import java.time.LocalDateTime;
22859 ashik.ali 6
import java.util.ArrayList;
7
import java.util.HashMap;
8
import java.util.HashSet;
9
import java.util.Iterator;
10
import java.util.List;
11
import java.util.Map;
12
import java.util.Set;
22955 ashik.ali 13
import java.util.function.Function;
14
import java.util.stream.Collectors;
22859 ashik.ali 15
 
16
import org.json.JSONObject;
17
import org.slf4j.Logger;
18
import org.slf4j.LoggerFactory;
19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.stereotype.Component;
21
 
23202 ashik.ali 22
import com.spice.profitmandi.common.enumuration.SearchType;
22859 ashik.ali 23
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24
import com.spice.profitmandi.common.model.CartFofo;
25
import com.spice.profitmandi.common.model.CreateOrderRequest;
26
import com.spice.profitmandi.common.model.CustomAddress;
27
import com.spice.profitmandi.common.model.CustomCustomer;
28
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
29
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
30
import com.spice.profitmandi.common.model.CustomOrderItem;
31
import com.spice.profitmandi.common.model.CustomPaymentOption;
32
import com.spice.profitmandi.common.model.CustomRetailer;
33
import com.spice.profitmandi.common.model.GadgetCopsInsuranceModel;
23172 ashik.ali 34
import com.spice.profitmandi.common.model.GstRate;
22859 ashik.ali 35
import com.spice.profitmandi.common.model.ItemIdQuantityAvailability;
36
import com.spice.profitmandi.common.model.PdfModel;
37
import com.spice.profitmandi.common.model.PriceModel;
38
import com.spice.profitmandi.common.model.ProfitMandiConstants;
39
import com.spice.profitmandi.common.model.Quantity;
40
import com.spice.profitmandi.common.model.SerialNumberDetail;
41
import com.spice.profitmandi.common.util.InsuranceUtils;
42
import com.spice.profitmandi.common.util.StringUtils;
23172 ashik.ali 43
import com.spice.profitmandi.common.util.Utils;
22859 ashik.ali 44
import com.spice.profitmandi.dao.entity.catalog.Item;
45
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
46
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
47
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
48
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
49
import com.spice.profitmandi.dao.entity.dtr.Retailer;
50
import com.spice.profitmandi.dao.entity.dtr.User;
51
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
52
import com.spice.profitmandi.dao.entity.fofo.Customer;
53
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
54
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
55
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
56
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23365 ashik.ali 57
import com.spice.profitmandi.dao.entity.fofo.FofoOrderPaymentOption;
23202 ashik.ali 58
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
22859 ashik.ali 59
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
60
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
61
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
62
import com.spice.profitmandi.dao.entity.user.Address;
63
import com.spice.profitmandi.dao.entity.user.Counter;
64
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
65
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
66
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23202 ashik.ali 67
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22859 ashik.ali 68
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
69
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
70
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
71
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
72
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
73
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
74
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
75
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
76
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
77
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
78
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
79
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
23365 ashik.ali 80
import com.spice.profitmandi.dao.repository.fofo.FofoOrderPaymentOptionRepository;
22859 ashik.ali 81
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
82
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
83
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
84
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
85
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
86
import com.spice.profitmandi.dao.repository.user.AddressRepository;
87
import com.spice.profitmandi.dao.repository.user.CounterRepository;
88
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
89
import com.spice.profitmandi.service.pricing.PricingService;
90
import com.spice.profitmandi.service.scheme.SchemeService;
91
 
92
import in.shop2020.model.v1.catalog.ItemType;
93
 
94
@Component
95
public class OrderServiceImpl implements OrderService {
96
 
97
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
98
 
99
	@Autowired
100
	private InventoryItemRepository inventoryItemRepository;
101
 
102
	@Autowired
103
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
104
 
105
	@Autowired
106
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
107
 
108
	@Autowired
109
	private CustomerRepository customerRepository;
110
 
111
	@Autowired
112
	private AddressRepository addressRepository;
113
 
114
	@Autowired
115
	private FofoLineItemRepository fofoLineItemRepository;
116
 
117
	@Autowired
118
	private FofoOrderItemRepository fofoOrderItemRepository;
119
 
120
	@Autowired
121
	private PaymentOptionRepository paymentOptionRepository;
122
 
123
	@Autowired
124
	private ScanRecordRepository scanRecordRepository;
125
 
126
	@Autowired
127
	private FofoOrderRepository fofoOrderRepository;
128
 
129
	@Autowired
130
	private RetailerRepository retailerRepository;
131
 
132
	@Autowired
133
	private UserRepository userRepository;
134
 
135
	@Autowired
136
	private UserAccountRepository userAccountRepository;
137
 
138
	@Autowired
139
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
140
 
141
	@Autowired
142
	private CustomerAddressRepository customerAddressRepository;
143
 
144
	@Autowired
145
	private ItemRepository itemRepository;
146
 
147
	@Autowired
148
	private InsuranceProviderRepository insuranceProviderRepository;
149
 
150
	@Autowired
151
	private InsurancePolicyRepository insurancePolicyRepository;
152
 
153
	@Autowired
154
	private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
155
 
156
	@Autowired
157
	private PricingService pricingService;
158
 
159
	@Autowired
160
	private PrivateDealUserRepository privateDealUserRepository;
161
 
162
	@Autowired
163
	private CounterRepository counterRepository;
164
 
165
	@Autowired
23202 ashik.ali 166
	private FofoStoreRepository fofoStoreRepository;
167
 
168
	@Autowired
23365 ashik.ali 169
	private FofoOrderPaymentOptionRepository fofoOrderPaymentOptionRepository;
170
 
171
	@Autowired
22859 ashik.ali 172
	private SchemeService schemeService;
173
 
174
	@Override
175
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) throws ProfitMandiBusinessException {
176
 
22872 ashik.ali 177
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
178
 
179
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
180
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
22925 ashik.ali 181
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "VE_1016");
22872 ashik.ali 182
		}
183
 
184
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
185
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
22925 ashik.ali 186
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "VE_1071");
22872 ashik.ali 187
		}
188
 
23370 ashik.ali 189
		if(!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
23369 ashik.ali 190
			LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
191
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER, customCustomer.getGstNumber(), "VE_1072");
192
		}
193
 
22859 ashik.ali 194
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
22872 ashik.ali 195
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
22859 ashik.ali 196
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
197
 
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) {
23370 ashik.ali 486
        		tncs.add("Damage protection provided is the responisibility of Protection Provider only");
23001 amit.gupta 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());
23370 ashik.ali 495
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
22859 ashik.ali 496
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
497
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
498
		pdfModel.setCustomer(customCustomer);
499
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
500
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
501
 
502
		Retailer retailer = retailerRepository.selectById(fofoId);
503
		PrivateDealUser privateDealUser = null;
504
		try{
505
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
506
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
507
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
508
		}
509
 
510
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
511
		CustomRetailer customRetailer = new CustomRetailer();
512
		customRetailer.setBusinessName(retailer.getName());
513
		customRetailer.setMobileNumber(user.getMobileNumber());
22933 ashik.ali 514
		//customRetailer.setTinNumber(retailer.getNumber());
22859 ashik.ali 515
		if(privateDealUser == null){
516
			customRetailer.setGstNumber(null);
517
		}else{
518
			if(null != privateDealUser.getCounterId()){
519
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
520
				customRetailer.setGstNumber(counter.getGstin());
521
			}else{
522
				customRetailer.setGstNumber(null);
523
			}
524
		}
525
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
526
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
527
		pdfModel.setRetailer(customRetailer);
22925 ashik.ali 528
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
22859 ashik.ali 529
 
530
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
531
		for(FofoOrderItem fofoOrderItem : fofoOrderItems){
532
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
533
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
534
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
535
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
536
 
537
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
538
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor() + "\n IMEIS - " + String.join(", ",this.toSerialNumbers(fofoOrderItem.getFofoLineItems())));
539
			customFofoOrderItem.setRate(taxableSellingPrice);
540
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
541
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
542
			customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice()-fofoOrderItem.getDiscount())*fofoOrderItem.getQuantity());
543
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
544
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
545
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
546
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
547
			customFofoOrderItem.setIgstAmount(igstAmount);
548
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
549
			customFofoOrderItem.setCgstAmount(cgstAmount);
550
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
551
			customFofoOrderItem.setSgstAmount(sgstAmount);
552
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
553
			customerFofoOrderItems.add(customFofoOrderItem);
554
		}
555
		pdfModel.setOrderItems(customerFofoOrderItems);
556
		return pdfModel;
557
	}
558
 
559
	public String getBillingAddress(CustomerAddress customerAddress) {
560
		StringBuilder address = new StringBuilder();
561
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
562
			address.append(customerAddress.getLine1());
563
			address.append(", ");
564
		}
565
 
566
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
567
			address.append(customerAddress.getLine2());
568
			address.append(", ");
569
		}
570
 
571
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
572
			address.append(customerAddress.getLandmark());
573
			address.append(", ");
574
		}
575
 
576
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
577
			address.append(customerAddress.getCity());
578
			address.append(", ");
579
		}
580
 
581
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
582
			address.append(customerAddress.getState());
583
		}
584
 
585
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
586
			address.append("- ");
587
			address.append(customerAddress.getPinCode());
588
		}
589
 
590
		return address.toString();
591
	}
592
 
593
	@Override
594
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException{
595
		try{
596
			JSONObject cartObject = new JSONObject(cartJson);
597
			Iterator<?> keys = cartObject.keys();
598
 
599
			Set<Integer> itemIds = new HashSet<>();
600
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
601
 
602
			while( keys.hasNext() ) {
603
				String key = (String)keys.next();
604
				if ( cartObject.get(key) instanceof JSONObject ) {
605
					LOGGER.info(cartObject.get(key).toString());
606
				}
607
				CartFofo cf = new CartFofo();
608
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
609
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
610
 
611
				if (cf.getQuantity() <= 0){
612
					continue;
613
				}
614
				cartItems.add(cf);
615
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
616
			}
617
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
618
			if (itemIds.size() > 0){
619
				List<Item> items = itemRepository.selectByIds(itemIds);
620
				for (Item i : items){
621
					itemMap.put(i.getId(), i);
622
				}
623
 
624
			}
625
			for (CartFofo cf : cartItems){
626
				Item i = itemMap.get(cf.getItemId());
627
				if (i == null){
628
					continue;
629
				}
630
				cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
631
				cf.setItemType(i.getType());
632
			}
633
			return cartItems;
634
		}catch (Exception e) {
635
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 636
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 637
		}
638
	}
639
 
23202 ashik.ali 640
	@Override
641
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue, String startTimeString,
642
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
643
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
644
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
645
		long countItems = 0;
646
		List<FofoOrder> fofoOrders = new ArrayList<>();
647
 
648
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
649
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
650
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime);
651
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
652
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
653
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);
654
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
655
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
656
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);
657
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
658
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
659
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);
660
		}else{
661
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
23297 ashik.ali 662
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);
23202 ashik.ali 663
		}
664
		Map<String, Object> map = new HashMap<>();
665
 
666
		map.put("saleHistories", fofoOrders);
667
		map.put("start", offset + 1);
668
		map.put("size", countItems);
669
		map.put("searchType", searchType);
23351 ashik.ali 670
		map.put("searchTypes", SearchType.values());
23202 ashik.ali 671
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
672
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
673
		if (fofoOrders.size() < limit){
674
			map.put("end", offset + fofoOrders.size());
675
		}
676
		else{
677
			map.put("end", offset + limit);
678
		}
679
		return map;
680
	}
681
 
682
	@Override
683
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue, String startTimeString,
684
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
685
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
686
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
687
		List<FofoOrder> fofoOrders = new ArrayList<>();
688
 
689
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
690
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
691
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
692
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
693
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
694
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
695
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
696
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
697
		}else{
698
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
699
		}
700
		Map<String, Object> map = new HashMap<>();
701
 
702
		map.put("saleHistories", fofoOrders);
703
		return map;
704
	}
705
 
706
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException{
707
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 708
		return fofoStore.getCode();
23202 ashik.ali 709
	}
710
 
711
 
23191 ashik.ali 712
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId){
713
		CustomerAddress customerAddress = null;
714
		try{
715
			//CustomAddress customAddress = customCustomer.getAddress();
716
			customerAddress = customerAddressRepository.selectByParams(
717
					customAddress.getName(), customAddress.getLine1(), customAddress.getLine2(),
718
					customAddress.getLandmark(),customAddress.getCity(), customAddress.getPinCode(),
719
					customAddress.getState(), customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
720
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
721
			LOGGER.warn("Customer address not found : ", profitMandiBusinessException);
722
			customerAddress = new CustomerAddress();
723
			this.setCustomerAddress(customerAddress, customAddress);
724
			customerAddress.setCustomerId(customerId);
725
		}
726
		customerAddressRepository.persist(customerAddress);
727
		return customerAddress;
728
	}
729
 
22859 ashik.ali 730
	private String getValidName(String name){
731
		return name!=null?name:"";
732
	}
733
 
734
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){
22955 ashik.ali 735
		Function<FofoLineItem, String> fofoLineItemToSerialNumberFunction = new Function<FofoLineItem, String>() {
736
			@Override
737
			public String apply(FofoLineItem fofoLineItem) {
738
				return fofoLineItem.getSerialNumber();
739
			}
740
		};
741
		return fofoLineItems.stream().map(fofoLineItemToSerialNumberFunction).collect(Collectors.toSet());
22859 ashik.ali 742
	}
743
 
744
 
745
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence(){
746
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
747
		try{
748
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
749
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
750
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
751
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
752
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
753
			policyNumberGenerationSequence.setSequence(1);
754
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
755
		}
756
		return policyNumberGenerationSequence;
757
	}
758
 
759
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber, LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress, InsurancePolicy insurancePolicy){
760
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
761
		gadgetCopsInsuranceModel.setBrand(brand);
762
		gadgetCopsInsuranceModel.setModelName(modelName);
763
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
764
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
765
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
766
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
767
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
768
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
769
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
770
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
771
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
772
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
773
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
774
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
775
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
776
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
777
		return gadgetCopsInsuranceModel;
778
	}
779
 
780
	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){
781
		InsurancePolicy insurancePolicy = new InsurancePolicy();
782
		insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
783
		insurancePolicy.setRetailerId(retailerId);
784
		insurancePolicy.setPurchaseAmount(purchaseAmount);
785
		insurancePolicy.setSaleAmount(saleAmount);
786
		insurancePolicy.setSellingPrice(sellingPrice);
787
		insurancePolicy.setSerialNumber(serialNumber);
788
		insurancePolicy.setModelName(modelName);
789
		insurancePolicy.setBrand(brand);
790
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence));
791
		insurancePolicy.setProviderId(insuranceProviderId);
792
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
793
		insurancePolicy.setCustomerLastName(customer.getLastName());
794
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
795
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
796
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
797
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
798
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
799
		insurancePolicy.setCustomerCity(customerAddress.getCity());
800
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
801
		insurancePolicy.setCustomerState(customerAddress.getState());
802
		return insurancePolicy;
803
	}
804
 
22872 ashik.ali 805
	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 806
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
807
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
22872 ashik.ali 808
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 809
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
810
			float itemSellingPrice = entry.getValue();
811
			float itemMargin = itemSellingPrice - itemPurchasePrice;
812
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
813
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
814
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
815
			if(insuranceMargin < (itemMargin * 30 / 100)){
816
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
817
			}
818
		}
819
		if(!invalidInsuranceMarginAmount.isEmpty()){
820
			LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
22925 ashik.ali 821
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount, "FFORDR_1007");
22859 ashik.ali 822
		}
823
	}
824
 
825
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice, Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap) throws ProfitMandiBusinessException{
826
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
827
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
828
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
829
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
830
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
831
			}
832
 
833
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
834
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
835
			}
836
		}
837
 
838
		// insurance sale amount can not be lesser than insurance purchase amount
839
		if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
840
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
22925 ashik.ali 841
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount", invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 842
		}
843
 
844
		if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
845
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
22925 ashik.ali 846
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount", invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 847
		}
848
	}
849
 
22872 ashik.ali 850
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 851
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
852
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
853
		//Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
854
		for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
22872 ashik.ali 855
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
856
			if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()){
857
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 858
			}
22872 ashik.ali 859
			if(entry.getValue().isMop() && customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
860
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
861
			}
22859 ashik.ali 862
		}
863
 
864
		if(!invalidMopItemIdPriceMap.isEmpty()){
865
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 866
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 867
		}
868
 
869
		if(!invalidMopItemIdPriceMap.isEmpty()){
870
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 871
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 872
		}
873
	}
874
 
875
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString) throws ProfitMandiBusinessException{
876
		LocalDate customerDateOfBirth = null;
877
		try{
878
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
879
		}catch(DateTimeException dateTimeException){
880
			LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
22925 ashik.ali 881
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 882
		}
883
		return customerDateOfBirth;
884
	}
885
 
886
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<Integer, Integer> inventoryItemQuantityUsed){
887
		for(InventoryItem inventoryItem : inventoryItems){
888
			inventoryItem.setLastScanType(ScanType.SALE);
889
			inventoryItemRepository.persist(inventoryItem);
890
			ScanRecord scanRecord = new ScanRecord();
891
			scanRecord.setInventoryItemId(inventoryItem.getId());
892
			scanRecord.setFofoId(fofoId);
893
			//correct this
894
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
895
			scanRecord.setType(ScanType.SALE);
896
			scanRecordRepository.persist(scanRecord);
897
		}
898
	}
899
 
900
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed){
901
		for(InventoryItem inventoryItem : inventoryItems){
902
			FofoLineItem fofoLineItem = new FofoLineItem();
903
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
904
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
905
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
906
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
907
			fofoLineItemRepository.persist(fofoLineItem);
908
		}
909
	}
910
 
23172 ashik.ali 911
	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 912
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
913
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
914
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
915
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
916
		fofoOrderItem.setOrderId(fofoOrderId);
917
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
918
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
919
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 920
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
921
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
922
		if(stateId != null){
923
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
924
		}else{
925
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
926
		}
22859 ashik.ali 927
		for(InventoryItem inventoryItem : inventoryItems){
23172 ashik.ali 928
			if(stateId == null){
929
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
930
			}else{
931
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
932
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
933
			}
934
 
22859 ashik.ali 935
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
936
			break;
937
		}
938
		List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoOrderItem.getItemId());
939
		float cost = 0;
940
		if (priceDropAmounts!=null){
941
			for (Float pda : priceDropAmounts){
942
				cost = cost + pda;
943
			}
23372 ashik.ali 944
		}else{
22859 ashik.ali 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){
23371 ashik.ali 966
			if(customPaymentOption.getAmount() > 0) {
967
				FofoOrderPaymentOption fofoOrderPaymentOption = new FofoOrderPaymentOption();
968
				fofoOrderPaymentOption.setFofoOrderId(fofoOrderId);
969
				fofoOrderPaymentOption.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
970
				fofoOrderPaymentOption.setAmount(customPaymentOption.getAmount());
971
				fofoOrderPaymentOptionRepository.persist(fofoOrderPaymentOption);
972
			}
22859 ashik.ali 973
		}
974
	}
975
 
23369 ashik.ali 976
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
22859 ashik.ali 977
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 978
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 979
		fofoOrder.setCustomerId(customerId);
980
		fofoOrder.setFofoId(fofoId);
23370 ashik.ali 981
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
22859 ashik.ali 982
		fofoOrder.setTotalAmount(totalAmount);
983
		fofoOrder.setCustomerAddressId(customerAddressId);
984
		fofoOrderRepository.persist(fofoOrder);
985
		return fofoOrder;
986
	}
987
 
988
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
989
		Customer customer = null;
990
		try{
991
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
992
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
993
			LOGGER.error("Error : ", profitMandiBusinessException);
994
			customer = new Customer();
995
		}
23190 ashik.ali 996
		customer.setFirstName(customCustomer.getFirstName());
997
		customer.setLastName(customCustomer.getLastName());
998
		customer.setEmailId(customCustomer.getEmailId());
999
		customer.setMobileNumber(customCustomer.getMobileNumber());
1000
		customerRepository.persist(customer);
22859 ashik.ali 1001
		return customer;
1002
	}
1003
 
23202 ashik.ali 1004
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId, String fofoStoreCode){
22859 ashik.ali 1005
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1006
		try{
1007
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1008
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1009
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1010
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1011
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23370 ashik.ali 1012
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
22859 ashik.ali 1013
			invoiceNumberGenerationSequence.setSequence(1);
1014
		}
1015
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1016
		return invoiceNumberGenerationSequence;
1017
	}
1018
 
22872 ashik.ali 1019
	private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 1020
 		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1021
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1022
		for (Item i : items){
22872 ashik.ali 1023
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1024
			if (i.getType().equals(ItemType.SERIALIZED)){
1025
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1026
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1027
				}
23202 ashik.ali 1028
			}else{
22872 ashik.ali 1029
				if (customFofoOrderItem == null || !customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1030
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1031
				}
1032
			}
1033
		}
1034
 
1035
		if(!invalidItemIdSerialNumbers.isEmpty()){
1036
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1037
			// itemId's are serialized you are saying these are not serialized
22925 ashik.ali 1038
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
22859 ashik.ali 1039
		}
1040
 
1041
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
1042
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1043
			// itemId's are non serialized you are saying these are serialized
22925 ashik.ali 1044
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
22859 ashik.ali 1045
		}
1046
	}
1047
 
22872 ashik.ali 1048
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
1049
		if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
22859 ashik.ali 1050
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1051
		}
1052
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
1053
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
22872 ashik.ali 1054
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
22859 ashik.ali 1055
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
22872 ashik.ali 1056
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
1057
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1058
			if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
22859 ashik.ali 1059
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1060
					itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1061
					Quantity quantity = new Quantity();
1062
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
1063
					quantity.setRequested(customFofoOrderItem.getQuantity());
1064
					itemIdQuantityAvailability.setQuantity(quantity);
1065
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1066
				}
1067
 
1068
		}
1069
 
1070
 
1071
 
1072
		if(!itemIdQuantityAvailabilities.isEmpty()){
1073
			// itemIdQuantity request is not valid
1074
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
22925 ashik.ali 1075
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
22859 ashik.ali 1076
		}
1077
	}
1078
 
22872 ashik.ali 1079
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
1080
		int itemId = 0;
1081
		for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
1082
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1083
			for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
1084
				if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
1085
					itemId = entry.getKey();
1086
					break;
1087
				}
22859 ashik.ali 1088
			}
1089
		}
22872 ashik.ali 1090
		return itemId;
22859 ashik.ali 1091
	}
1092
 
1093
	private Map<Integer, Item> toItemMap(List<Item> items){
22955 ashik.ali 1094
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1095
			@Override
1096
			public Integer apply(Item item) {
1097
				return item.getId();
1098
			}
1099
		};
1100
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1101
			@Override
1102
			public Item apply(Item item) {
1103
				return item;
1104
			}
1105
		};
1106
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1107
	}
1108
 
23190 ashik.ali 1109
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){
22859 ashik.ali 1110
		customerAddress.setName(customAddress.getName());
1111
		customerAddress.setLine1(customAddress.getLine1());
1112
		customerAddress.setLine2(customAddress.getLine2());
1113
		customerAddress.setLandmark(customAddress.getLandmark());
1114
		customerAddress.setCity(customAddress.getCity());
1115
		customerAddress.setPinCode(customAddress.getPinCode());
1116
		customerAddress.setState(customAddress.getState());
1117
		customerAddress.setCountry(customAddress.getCountry());
1118
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1119
	}
1120
 
1121
	private CustomAddress createCustomAddress(Address address){
1122
		CustomAddress customAddress = new CustomAddress();
1123
		customAddress.setName(address.getName());
1124
		customAddress.setLine1(address.getLine1());
1125
		customAddress.setLine2(address.getLine2());
1126
		customAddress.setLandmark(address.getLandmark());
1127
		customAddress.setCity(address.getCity());
1128
		customAddress.setPinCode(address.getPinCode());
1129
		customAddress.setState(address.getState());
1130
		customAddress.setCountry(address.getCountry());
1131
		customAddress.setPhoneNumber(address.getPhoneNumber());
1132
		return customAddress;
1133
	}
1134
 
1135
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
1136
		CustomAddress customAddress = new CustomAddress();
1137
		customAddress.setName(customerAddress.getName());
1138
		customAddress.setLine1(customerAddress.getLine1());
1139
		customAddress.setLine2(customerAddress.getLine2());
1140
		customAddress.setLandmark(customerAddress.getLandmark());
1141
		customAddress.setCity(customerAddress.getCity());
1142
		customAddress.setPinCode(customerAddress.getPinCode());
1143
		customAddress.setState(customerAddress.getState());
1144
		customAddress.setCountry(customerAddress.getCountry());
1145
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1146
		return customAddress;
1147
	}
1148
 
1149
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
1150
	{
23365 ashik.ali 1151
		Set<Integer> paymentOptionIds = new HashSet<>();
1152
 
22859 ashik.ali 1153
		float calculatedAmount = 0;
1154
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
23365 ashik.ali 1155
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1156
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1157
		}
1158
		if(calculatedAmount != totalAmount){
22863 ashik.ali 1159
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
22925 ashik.ali 1160
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1161
		}
23365 ashik.ali 1162
 
1163
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
1164
		if(foundPaymentOptionIds.size() != paymentOptionIds.size()) {
1165
			paymentOptionIds.removeAll(foundPaymentOptionIds);
1166
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds, "FFORDR_1017");
1167
		}
22859 ashik.ali 1168
	}
22925 ashik.ali 1169
 
1170
	@Override
1171
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1172
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1173
		if(!fofoOrderItems.isEmpty()){
1174
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1175
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1176
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1177
			while(fofoOrderItemsIterator.hasNext()){
1178
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1179
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1180
				newFofoOrderItems.add(fofoOrderItem);
1181
				fofoOrderItemsIterator.remove();
1182
			}
1183
			fofoOrderItems = newFofoOrderItems;
1184
		}
1185
		return fofoOrderItems;
1186
	}
1187
 
1188
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
22955 ashik.ali 1189
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1190
			@Override
1191
			public Integer apply(FofoOrderItem fofoOrderItem) {
1192
				return fofoOrderItem.getId();
1193
			}
1194
		};
1195
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1196
	}
1197
 
1198
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
1199
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1200
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1201
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1202
		for(FofoLineItem fofoLineItem : fofoLineItems){
1203
			if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
1204
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1205
				fofoLineItems2.add(fofoLineItem);
1206
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1207
			}else{
1208
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1209
			}
1210
		}
1211
		return fofoOrderItemIdFofoLineItemsMap;
1212
	}
22859 ashik.ali 1213
 
1214
}