Subversion Repositories SmartDukaan

Rev

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

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