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