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