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
 
364
		CustomerAddress customerAddress = null;
365
		if(createOrderRequest.getCustomer().getCustomerAddressId() > 0){
366
			LOGGER.info("CustomerAddressId found [{}]", createOrderRequest.getCustomer().getCustomerAddressId());
367
			try{
368
				customerAddress = customerAddressRepository.selectById(createOrderRequest.getCustomer().getCustomerAddressId());
369
			}catch(ProfitMandiBusinessException profitMandiBusinessException){
370
				LOGGER.warn("Customer address not found with requested customerAddressId [{}]", createOrderRequest.getCustomer().getCustomerAddressId());
23190 ashik.ali 371
				customerAddress = new CustomerAddress();
372
				this.setCustomerAddress(customerAddress, customCustomer.getAddress());
22859 ashik.ali 373
			}
374
		}else{
375
			LOGGER.info("CustomerAddressId not found");
23190 ashik.ali 376
			customerAddress = new CustomerAddress();
377
			this.setCustomerAddress(customerAddress, customCustomer.getAddress());
22859 ashik.ali 378
		}
379
 
380
		customerAddress.setCustomerId(customer.getId());
381
		customerAddressRepository.persist(customerAddress);
382
 
383
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), fofoId, invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
384
 
385
		this.createPaymentOptions(fofoOrder.getId(), createOrderRequest.getPaymentOptions());
386
 
23172 ashik.ali 387
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
388
 
389
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
390
 
391
		Integer stateId = null;
392
		if(customerAddress.getState().equals(retailerAddress.getState())){
393
			try{
394
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
395
			}catch(Exception e){
396
				LOGGER.error("Unable to get state rates");
397
			}
398
		}
399
 
22859 ashik.ali 400
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
23172 ashik.ali 401
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(), itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), itemIdPriceDropAmount, stateId);
22859 ashik.ali 402
 
403
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
404
 
405
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
406
 
407
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
408
 
409
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
410
		}
411
 
412
		// insurance calculation is insurance flag is enabled
413
		if(!insuranceSerialNumberItemPrice.isEmpty()){
414
			LOGGER.info("Processing for insurence for serialNumbers");
415
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
416
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
417
 
418
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount, insurancePricesMap);
419
 
22872 ashik.ali 420
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap, itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
22859 ashik.ali 421
 
422
			LocalDate customerDateOfBirth = this.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
423
 
424
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
425
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this.createPolicyNumberGenerationSequence();
426
 
427
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(
428
						invoiceNumberGenerationSequence, fofoId,
429
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
430
						insuranceSerialNumberSaleAmount.get(entry.getKey()),entry.getValue(),
431
						entry.getKey(), serialNumberModelName.get(entry.getKey()),
432
						serialNumberBrand.get(entry.getKey()), policyNumberGenerationSequence.getSequence(),
433
						insuranceProvider.getId(), customer, customerDateOfBirth, customerAddress);
434
 
435
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()), entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
436
 
437
				try{
438
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
439
					insurancePolicy.setPosted(true);
440
				}catch (ProfitMandiBusinessException profitMandiBusinessException) {
441
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
442
				}
443
				insurancePolicyRepository.persist(insurancePolicy);
444
			}
445
		}
446
		float cashback = schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
447
		if(cashback > 0){
448
			fofoOrder.setCashback(cashback);
449
			fofoOrderRepository.persist(fofoOrder);
450
		}
451
		return fofoOrder.getId();
452
	}
453
 
454
	@Override
455
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
456
 
457
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
458
 
459
		PdfModel pdfModel = new PdfModel();
460
		pdfModel.setAuther("profitmandi");
461
		pdfModel.setTitle("Retailer Invoice");
462
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
463
 
464
		// insurance calculation
22925 ashik.ali 465
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoId, fofoOrder.getInvoiceNumber());
22859 ashik.ali 466
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
467
		final float totalInsuranceTaxRate = 18;
468
		for(InsurancePolicy insurancePolicy : insurancePolicies){
469
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
470
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
471
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #" + insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
472
			customInsurancePolicy.setHsnCode("998716");
473
			customInsurancePolicy.setRate(taxableInsurancePrice);
474
			customInsurancePolicy.setIgstRate(18);
475
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
22936 amit.gupta 476
			customInsurancePolicy.setCgstRate(9);
22859 ashik.ali 477
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 /100);
478
			customInsurancePolicy.setSgstRate(9);
479
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 /100);
480
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
481
			customInsurancePolicies.add(customInsurancePolicy);
482
		}
483
		pdfModel.setInsurancePolicies(customInsurancePolicies);
23001 amit.gupta 484
		List<String> tncs = new ArrayList<>();
485
		tncs.add("I agree that goods received are in good working condition");
486
		tncs.add("Goods once sold cannot be exchanged or taken back");
487
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
488
        if(pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
489
        	tncs.add("Damage protection provided is the responisibility of Protection Provider only");
490
        }
491
		pdfModel.setTncs(tncs);
22859 ashik.ali 492
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
493
		CustomCustomer customCustomer = new CustomCustomer();
494
		customCustomer.setFirstName(customer.getFirstName());
495
		customCustomer.setLastName(customer.getLastName());
496
		customCustomer.setEmailId(customer.getEmailId());
497
		customCustomer.setMobileNumber(customer.getMobileNumber());
498
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
499
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
500
		pdfModel.setCustomer(customCustomer);
501
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
502
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
503
 
504
		Retailer retailer = retailerRepository.selectById(fofoId);
505
		PrivateDealUser privateDealUser = null;
506
		try{
507
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
508
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
509
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
510
		}
511
 
512
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
513
		CustomRetailer customRetailer = new CustomRetailer();
514
		customRetailer.setBusinessName(retailer.getName());
515
		customRetailer.setMobileNumber(user.getMobileNumber());
22933 ashik.ali 516
		//customRetailer.setTinNumber(retailer.getNumber());
22859 ashik.ali 517
		if(privateDealUser == null){
518
			customRetailer.setGstNumber(null);
519
		}else{
520
			if(null != privateDealUser.getCounterId()){
521
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
522
				customRetailer.setGstNumber(counter.getGstin());
523
			}else{
524
				customRetailer.setGstNumber(null);
525
			}
526
		}
527
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
528
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
529
		pdfModel.setRetailer(customRetailer);
22925 ashik.ali 530
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
22859 ashik.ali 531
 
532
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
533
		for(FofoOrderItem fofoOrderItem : fofoOrderItems){
534
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
535
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
536
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
537
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
538
 
539
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
540
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor() + "\n IMEIS - " + String.join(", ",this.toSerialNumbers(fofoOrderItem.getFofoLineItems())));
541
			customFofoOrderItem.setRate(taxableSellingPrice);
542
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
543
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
544
			customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice()-fofoOrderItem.getDiscount())*fofoOrderItem.getQuantity());
545
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
546
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
547
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
548
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
549
			customFofoOrderItem.setIgstAmount(igstAmount);
550
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
551
			customFofoOrderItem.setCgstAmount(cgstAmount);
552
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
553
			customFofoOrderItem.setSgstAmount(sgstAmount);
554
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
555
			customerFofoOrderItems.add(customFofoOrderItem);
556
		}
557
		pdfModel.setOrderItems(customerFofoOrderItems);
558
		return pdfModel;
559
	}
560
 
561
	public String getBillingAddress(CustomerAddress customerAddress) {
562
		StringBuilder address = new StringBuilder();
563
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
564
			address.append(customerAddress.getLine1());
565
			address.append(", ");
566
		}
567
 
568
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
569
			address.append(customerAddress.getLine2());
570
			address.append(", ");
571
		}
572
 
573
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
574
			address.append(customerAddress.getLandmark());
575
			address.append(", ");
576
		}
577
 
578
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
579
			address.append(customerAddress.getCity());
580
			address.append(", ");
581
		}
582
 
583
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
584
			address.append(customerAddress.getState());
585
		}
586
 
587
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
588
			address.append("- ");
589
			address.append(customerAddress.getPinCode());
590
		}
591
 
592
		return address.toString();
593
	}
594
 
595
	@Override
596
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException{
597
		try{
598
			JSONObject cartObject = new JSONObject(cartJson);
599
			Iterator<?> keys = cartObject.keys();
600
 
601
			Set<Integer> itemIds = new HashSet<>();
602
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
603
 
604
			while( keys.hasNext() ) {
605
				String key = (String)keys.next();
606
				if ( cartObject.get(key) instanceof JSONObject ) {
607
					LOGGER.info(cartObject.get(key).toString());
608
				}
609
				CartFofo cf = new CartFofo();
610
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
611
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
612
 
613
				if (cf.getQuantity() <= 0){
614
					continue;
615
				}
616
				cartItems.add(cf);
617
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
618
			}
619
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
620
			if (itemIds.size() > 0){
621
				List<Item> items = itemRepository.selectByIds(itemIds);
622
				for (Item i : items){
623
					itemMap.put(i.getId(), i);
624
				}
625
 
626
			}
627
			for (CartFofo cf : cartItems){
628
				Item i = itemMap.get(cf.getItemId());
629
				if (i == null){
630
					continue;
631
				}
632
				cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
633
				cf.setItemType(i.getType());
634
			}
635
			return cartItems;
636
		}catch (Exception e) {
637
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 638
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 639
		}
640
	}
641
 
642
	private String getValidName(String name){
643
		return name!=null?name:"";
644
	}
645
 
646
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){
22955 ashik.ali 647
		Function<FofoLineItem, String> fofoLineItemToSerialNumberFunction = new Function<FofoLineItem, String>() {
648
			@Override
649
			public String apply(FofoLineItem fofoLineItem) {
650
				return fofoLineItem.getSerialNumber();
651
			}
652
		};
653
		return fofoLineItems.stream().map(fofoLineItemToSerialNumberFunction).collect(Collectors.toSet());
22859 ashik.ali 654
	}
655
 
656
 
657
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence(){
658
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
659
		try{
660
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
661
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
662
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
663
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
664
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
665
			policyNumberGenerationSequence.setSequence(1);
666
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
667
		}
668
		return policyNumberGenerationSequence;
669
	}
670
 
671
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber, LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress, InsurancePolicy insurancePolicy){
672
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
673
		gadgetCopsInsuranceModel.setBrand(brand);
674
		gadgetCopsInsuranceModel.setModelName(modelName);
675
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
676
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
677
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
678
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
679
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
680
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
681
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
682
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
683
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
684
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
685
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
686
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
687
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
688
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
689
		return gadgetCopsInsuranceModel;
690
	}
691
 
692
	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){
693
		InsurancePolicy insurancePolicy = new InsurancePolicy();
694
		insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
695
		insurancePolicy.setRetailerId(retailerId);
696
		insurancePolicy.setPurchaseAmount(purchaseAmount);
697
		insurancePolicy.setSaleAmount(saleAmount);
698
		insurancePolicy.setSellingPrice(sellingPrice);
699
		insurancePolicy.setSerialNumber(serialNumber);
700
		insurancePolicy.setModelName(modelName);
701
		insurancePolicy.setBrand(brand);
702
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence));
703
		insurancePolicy.setProviderId(insuranceProviderId);
704
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
705
		insurancePolicy.setCustomerLastName(customer.getLastName());
706
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
707
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
708
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
709
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
710
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
711
		insurancePolicy.setCustomerCity(customerAddress.getCity());
712
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
713
		insurancePolicy.setCustomerState(customerAddress.getState());
714
		return insurancePolicy;
715
	}
716
 
22872 ashik.ali 717
	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 718
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
719
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
22872 ashik.ali 720
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 721
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
722
			float itemSellingPrice = entry.getValue();
723
			float itemMargin = itemSellingPrice - itemPurchasePrice;
724
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
725
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
726
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
727
			if(insuranceMargin < (itemMargin * 30 / 100)){
728
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
729
			}
730
		}
731
		if(!invalidInsuranceMarginAmount.isEmpty()){
732
			LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
22925 ashik.ali 733
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount, "FFORDR_1007");
22859 ashik.ali 734
		}
735
	}
736
 
737
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice, Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap) throws ProfitMandiBusinessException{
738
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
739
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
740
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
741
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
742
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
743
			}
744
 
745
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
746
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
747
			}
748
		}
749
 
750
		// insurance sale amount can not be lesser than insurance purchase amount
751
		if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
752
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
22925 ashik.ali 753
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount", invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 754
		}
755
 
756
		if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
757
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
22925 ashik.ali 758
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount", invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 759
		}
760
	}
761
 
22872 ashik.ali 762
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 763
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
764
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
765
		//Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
766
		for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
22872 ashik.ali 767
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
768
			if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()){
769
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 770
			}
22872 ashik.ali 771
			if(entry.getValue().isMop() && customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
772
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
773
			}
22859 ashik.ali 774
		}
775
 
776
		if(!invalidMopItemIdPriceMap.isEmpty()){
777
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 778
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 779
		}
780
 
781
		if(!invalidMopItemIdPriceMap.isEmpty()){
782
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 783
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 784
		}
785
	}
786
 
787
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString) throws ProfitMandiBusinessException{
788
		LocalDate customerDateOfBirth = null;
789
		try{
790
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
791
		}catch(DateTimeException dateTimeException){
792
			LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
22925 ashik.ali 793
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 794
		}
795
		return customerDateOfBirth;
796
	}
797
 
798
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<Integer, Integer> inventoryItemQuantityUsed){
799
		for(InventoryItem inventoryItem : inventoryItems){
800
			inventoryItem.setLastScanType(ScanType.SALE);
801
			inventoryItemRepository.persist(inventoryItem);
802
			ScanRecord scanRecord = new ScanRecord();
803
			scanRecord.setInventoryItemId(inventoryItem.getId());
804
			scanRecord.setFofoId(fofoId);
805
			//correct this
806
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
807
			scanRecord.setType(ScanType.SALE);
808
			scanRecordRepository.persist(scanRecord);
809
		}
810
	}
811
 
812
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed){
813
		for(InventoryItem inventoryItem : inventoryItems){
814
			FofoLineItem fofoLineItem = new FofoLineItem();
815
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
816
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
817
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
818
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
819
			fofoLineItemRepository.persist(fofoLineItem);
820
		}
821
	}
822
 
23172 ashik.ali 823
	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 824
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
825
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
826
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
827
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
828
		fofoOrderItem.setOrderId(fofoOrderId);
829
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
830
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
831
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 832
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
833
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
834
		if(stateId != null){
835
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
836
		}else{
837
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
838
		}
22859 ashik.ali 839
		for(InventoryItem inventoryItem : inventoryItems){
23172 ashik.ali 840
			if(stateId == null){
841
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
842
			}else{
843
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
844
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
845
			}
846
 
22859 ashik.ali 847
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
848
			break;
849
		}
850
		List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoOrderItem.getItemId());
851
		float cost = 0;
852
		if (priceDropAmounts!=null){
853
			for (Float pda : priceDropAmounts){
854
				cost = cost + pda;
855
			}
856
		}
857
		else{
858
			cost = customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
859
		}
860
		fofoOrderItem.setCost(cost);
861
		fofoOrderItem.setBrand(item.getBrand());
862
		fofoOrderItem.setModelName(item.getModelName());
863
		fofoOrderItem.setModelNumber(item.getModelNumber());
864
		fofoOrderItem.setColor(item.getColor());
865
		fofoOrderItemRepository.persist(fofoOrderItem);
866
		return fofoOrderItem;
867
	}
868
 
869
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId, int itemId, int quantity) throws ProfitMandiBusinessException{
870
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
871
			if(currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId){
872
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId, currentInventorySnapshot.getAvailability() - quantity);
873
			}
874
		}
875
	}
876
 
877
	private void createPaymentOptions(int fofoOrderId, Set<CustomPaymentOption> customPaymentOptions){
878
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
879
			if(customPaymentOption.getAmount() > 0){
880
				PaymentOption paymentOption = new PaymentOption();
881
				paymentOption.setOrderId(fofoOrderId);
882
				paymentOption.setAmount(customPaymentOption.getAmount());
883
				paymentOption.setType(PaymentOptionType.valueOf(customPaymentOption.getType()));
884
				paymentOptionRepository.persist(paymentOption);
885
			}
886
		}
887
	}
888
 
889
	private FofoOrder createAndGetFofoOrder(int customerId, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
890
		FofoOrder fofoOrder = new FofoOrder();
891
		fofoOrder.setCustomerId(customerId);
892
		fofoOrder.setFofoId(fofoId);
893
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
894
		fofoOrder.setTotalAmount(totalAmount);
895
		fofoOrder.setCustomerAddressId(customerAddressId);
896
		fofoOrderRepository.persist(fofoOrder);
897
		return fofoOrder;
898
	}
899
 
900
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
901
		Customer customer = null;
902
		try{
903
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
904
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
905
			LOGGER.error("Error : ", profitMandiBusinessException);
906
			customer = new Customer();
907
		}
23190 ashik.ali 908
		customer.setFirstName(customCustomer.getFirstName());
909
		customer.setLastName(customCustomer.getLastName());
910
		customer.setEmailId(customCustomer.getEmailId());
911
		customer.setMobileNumber(customCustomer.getMobileNumber());
912
		customerRepository.persist(customer);
22859 ashik.ali 913
		return customer;
914
	}
915
 
916
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId){
917
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
918
		try{
919
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
920
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
921
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
922
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
923
			invoiceNumberGenerationSequence.setFofoId(fofoId);
924
			invoiceNumberGenerationSequence.setPrefix("INVOICE");
925
			invoiceNumberGenerationSequence.setSequence(1);
926
		}
927
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
928
		return invoiceNumberGenerationSequence;
929
	}
930
 
22872 ashik.ali 931
	private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
22859 ashik.ali 932
 		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
933
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
934
		for (Item i : items){
22872 ashik.ali 935
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
936
			if (i.getType().equals(ItemType.SERIALIZED)){
937
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
938
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 939
				}
22872 ashik.ali 940
			}
941
			else{
942
				if (customFofoOrderItem == null || !customFofoOrderItem.getSerialNumberDetails().isEmpty()){
943
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 944
				}
945
			}
946
		}
947
 
948
		if(!invalidItemIdSerialNumbers.isEmpty()){
949
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
950
			// itemId's are serialized you are saying these are not serialized
22925 ashik.ali 951
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
22859 ashik.ali 952
		}
953
 
954
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
955
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
956
			// itemId's are non serialized you are saying these are serialized
22925 ashik.ali 957
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
22859 ashik.ali 958
		}
959
	}
960
 
22872 ashik.ali 961
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
962
		if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
22859 ashik.ali 963
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
964
		}
965
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
966
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
22872 ashik.ali 967
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
22859 ashik.ali 968
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
22872 ashik.ali 969
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
970
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
971
			if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
22859 ashik.ali 972
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
973
					itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
974
					Quantity quantity = new Quantity();
975
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
976
					quantity.setRequested(customFofoOrderItem.getQuantity());
977
					itemIdQuantityAvailability.setQuantity(quantity);
978
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
979
				}
980
 
981
		}
982
 
983
 
984
 
985
		if(!itemIdQuantityAvailabilities.isEmpty()){
986
			// itemIdQuantity request is not valid
987
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
22925 ashik.ali 988
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
22859 ashik.ali 989
		}
990
	}
991
 
22872 ashik.ali 992
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
993
		int itemId = 0;
994
		for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
995
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
996
			for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
997
				if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
998
					itemId = entry.getKey();
999
					break;
1000
				}
22859 ashik.ali 1001
			}
1002
		}
22872 ashik.ali 1003
		return itemId;
22859 ashik.ali 1004
	}
1005
 
1006
	private Map<Integer, Item> toItemMap(List<Item> items){
22955 ashik.ali 1007
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1008
			@Override
1009
			public Integer apply(Item item) {
1010
				return item.getId();
1011
			}
1012
		};
1013
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1014
			@Override
1015
			public Item apply(Item item) {
1016
				return item;
1017
			}
1018
		};
1019
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1020
	}
1021
 
23190 ashik.ali 1022
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){
22859 ashik.ali 1023
		customerAddress.setName(customAddress.getName());
1024
		customerAddress.setLine1(customAddress.getLine1());
1025
		customerAddress.setLine2(customAddress.getLine2());
1026
		customerAddress.setLandmark(customAddress.getLandmark());
1027
		customerAddress.setCity(customAddress.getCity());
1028
		customerAddress.setPinCode(customAddress.getPinCode());
1029
		customerAddress.setState(customAddress.getState());
1030
		customerAddress.setCountry(customAddress.getCountry());
1031
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1032
	}
1033
 
1034
	private CustomAddress createCustomAddress(Address address){
1035
		CustomAddress customAddress = new CustomAddress();
1036
		customAddress.setName(address.getName());
1037
		customAddress.setLine1(address.getLine1());
1038
		customAddress.setLine2(address.getLine2());
1039
		customAddress.setLandmark(address.getLandmark());
1040
		customAddress.setCity(address.getCity());
1041
		customAddress.setPinCode(address.getPinCode());
1042
		customAddress.setState(address.getState());
1043
		customAddress.setCountry(address.getCountry());
1044
		customAddress.setPhoneNumber(address.getPhoneNumber());
1045
		return customAddress;
1046
	}
1047
 
1048
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
1049
		CustomAddress customAddress = new CustomAddress();
1050
		customAddress.setName(customerAddress.getName());
1051
		customAddress.setLine1(customerAddress.getLine1());
1052
		customAddress.setLine2(customerAddress.getLine2());
1053
		customAddress.setLandmark(customerAddress.getLandmark());
1054
		customAddress.setCity(customerAddress.getCity());
1055
		customAddress.setPinCode(customerAddress.getPinCode());
1056
		customAddress.setState(customerAddress.getState());
1057
		customAddress.setCountry(customerAddress.getCountry());
1058
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1059
		return customAddress;
1060
	}
1061
 
1062
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
1063
	{
1064
		float calculatedAmount = 0;
1065
		Set<String> paymentOptionTypes = new HashSet<>();
1066
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
1067
			if(paymentOptionTypes.contains(PaymentOptionType.valueOf(customPaymentOption.getType()))){
1068
				throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType(), "");
1069
			}else{
1070
				paymentOptionTypes.add(customPaymentOption.getType());
1071
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
1072
			}
1073
		}
1074
		if(calculatedAmount != totalAmount){
22863 ashik.ali 1075
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
22925 ashik.ali 1076
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1077
		}
1078
	}
22925 ashik.ali 1079
 
1080
	@Override
1081
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1082
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1083
		if(!fofoOrderItems.isEmpty()){
1084
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1085
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1086
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1087
			while(fofoOrderItemsIterator.hasNext()){
1088
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1089
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1090
				newFofoOrderItems.add(fofoOrderItem);
1091
				fofoOrderItemsIterator.remove();
1092
			}
1093
			fofoOrderItems = newFofoOrderItems;
1094
		}
1095
		return fofoOrderItems;
1096
	}
1097
 
1098
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
22955 ashik.ali 1099
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1100
			@Override
1101
			public Integer apply(FofoOrderItem fofoOrderItem) {
1102
				return fofoOrderItem.getId();
1103
			}
1104
		};
1105
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1106
	}
1107
 
1108
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
1109
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1110
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1111
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1112
		for(FofoLineItem fofoLineItem : fofoLineItems){
1113
			if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
1114
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1115
				fofoLineItems2.add(fofoLineItem);
1116
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1117
			}else{
1118
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1119
			}
1120
		}
1121
		return fofoOrderItemIdFofoLineItemsMap;
1122
	}
22859 ashik.ali 1123
 
1124
}