Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23365 ashik.ali 1
package com.spice.profitmandi.service.order;
22859 ashik.ali 2
 
23418 ashik.ali 3
import java.io.IOException;
4
import java.net.URISyntaxException;
22859 ashik.ali 5
import java.time.DateTimeException;
6
import java.time.LocalDate;
23202 ashik.ali 7
import java.time.LocalDateTime;
22859 ashik.ali 8
import java.util.ArrayList;
23655 amit.gupta 9
import java.util.Arrays;
22859 ashik.ali 10
import java.util.HashMap;
11
import java.util.HashSet;
12
import java.util.Iterator;
13
import java.util.List;
14
import java.util.Map;
23418 ashik.ali 15
import java.util.Random;
22859 ashik.ali 16
import java.util.Set;
22955 ashik.ali 17
import java.util.function.Function;
18
import java.util.stream.Collectors;
22859 ashik.ali 19
 
23638 amit.gupta 20
import org.apache.logging.log4j.LogManager;
21
import org.apache.logging.log4j.Logger;
22859 ashik.ali 22
import org.json.JSONObject;
23
import org.springframework.beans.factory.annotation.Autowired;
23781 ashik.ali 24
import org.springframework.beans.factory.annotation.Qualifier;
22859 ashik.ali 25
import org.springframework.stereotype.Component;
26
 
23418 ashik.ali 27
import com.spice.profitmandi.common.ResponseCodeHolder;
23202 ashik.ali 28
import com.spice.profitmandi.common.enumuration.SearchType;
22859 ashik.ali 29
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23638 amit.gupta 30
import com.spice.profitmandi.common.model.BadReturnRequest;
22859 ashik.ali 31
import com.spice.profitmandi.common.model.CartFofo;
32
import com.spice.profitmandi.common.model.CreateOrderRequest;
23638 amit.gupta 33
import com.spice.profitmandi.common.model.CreditNotePdfModel;
22859 ashik.ali 34
import com.spice.profitmandi.common.model.CustomAddress;
35
import com.spice.profitmandi.common.model.CustomCustomer;
36
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
37
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
38
import com.spice.profitmandi.common.model.CustomOrderItem;
39
import com.spice.profitmandi.common.model.CustomPaymentOption;
40
import com.spice.profitmandi.common.model.CustomRetailer;
23638 amit.gupta 41
import com.spice.profitmandi.common.model.FoiBadReturnRequest;
22859 ashik.ali 42
import com.spice.profitmandi.common.model.GadgetCopsInsuranceModel;
23172 ashik.ali 43
import com.spice.profitmandi.common.model.GstRate;
22859 ashik.ali 44
import com.spice.profitmandi.common.model.ItemIdQuantityAvailability;
45
import com.spice.profitmandi.common.model.PdfModel;
46
import com.spice.profitmandi.common.model.PriceModel;
47
import com.spice.profitmandi.common.model.ProfitMandiConstants;
48
import com.spice.profitmandi.common.model.Quantity;
49
import com.spice.profitmandi.common.model.SerialNumberDetail;
23650 amit.gupta 50
import com.spice.profitmandi.common.util.FormattingUtils;
22859 ashik.ali 51
import com.spice.profitmandi.common.util.InsuranceUtils;
52
import com.spice.profitmandi.common.util.StringUtils;
23172 ashik.ali 53
import com.spice.profitmandi.common.util.Utils;
22859 ashik.ali 54
import com.spice.profitmandi.dao.entity.catalog.Item;
55
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
56
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
57
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
23418 ashik.ali 58
import com.spice.profitmandi.dao.entity.dtr.Otp;
23546 ashik.ali 59
import com.spice.profitmandi.dao.entity.dtr.PaymentOptionTransaction;
22859 ashik.ali 60
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
61
import com.spice.profitmandi.dao.entity.dtr.Retailer;
62
import com.spice.profitmandi.dao.entity.dtr.User;
63
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
64
import com.spice.profitmandi.dao.entity.fofo.Customer;
65
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
23650 amit.gupta 66
import com.spice.profitmandi.dao.entity.fofo.CustomerCreditNote;
67
import com.spice.profitmandi.dao.entity.fofo.CustomerReturnItem;
22859 ashik.ali 68
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
69
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
70
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23202 ashik.ali 71
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
22859 ashik.ali 72
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
73
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
23418 ashik.ali 74
import com.spice.profitmandi.dao.entity.fofo.PrebookingListing;
75
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;
76
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrderItem;
22859 ashik.ali 77
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
78
import com.spice.profitmandi.dao.entity.user.Address;
79
import com.spice.profitmandi.dao.entity.user.Counter;
80
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
23418 ashik.ali 81
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
23546 ashik.ali 82
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
23650 amit.gupta 83
import com.spice.profitmandi.dao.enumuration.fofo.ReturnType;
22859 ashik.ali 84
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
23655 amit.gupta 85
import com.spice.profitmandi.dao.enumuration.fofo.SettlementType;
22859 ashik.ali 86
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23202 ashik.ali 87
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22859 ashik.ali 88
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
89
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
23418 ashik.ali 90
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
23552 amit.gupta 91
import com.spice.profitmandi.dao.repository.dtr.PaymentOptionTransactionRepository;
22859 ashik.ali 92
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
93
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
94
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
95
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
96
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
23650 amit.gupta 97
import com.spice.profitmandi.dao.repository.fofo.BadInventorySnapshotRepository;
22859 ashik.ali 98
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
99
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
23650 amit.gupta 100
import com.spice.profitmandi.dao.repository.fofo.CustomerCreditNoteRepository;
22859 ashik.ali 101
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
23650 amit.gupta 102
import com.spice.profitmandi.dao.repository.fofo.CustomerReturnItemRepository;
22859 ashik.ali 103
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
104
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
105
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
106
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
107
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
108
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
23418 ashik.ali 109
import com.spice.profitmandi.dao.repository.fofo.PrebookingListingRepository;
110
import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderItemRepository;
111
import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderRepository;
23566 amit.gupta 112
import com.spice.profitmandi.dao.repository.fofo.PurchaseReturnItemRepository;
22859 ashik.ali 113
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
114
import com.spice.profitmandi.dao.repository.user.AddressRepository;
115
import com.spice.profitmandi.dao.repository.user.CounterRepository;
116
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
23418 ashik.ali 117
import com.spice.profitmandi.service.inventory.InventoryService;
23655 amit.gupta 118
import com.spice.profitmandi.service.inventory.PurchaseReturnService;
22859 ashik.ali 119
import com.spice.profitmandi.service.pricing.PricingService;
120
import com.spice.profitmandi.service.scheme.SchemeService;
23655 amit.gupta 121
import com.spice.profitmandi.service.user.RetailerService;
23395 amit.gupta 122
import com.spice.profitmandi.service.wallet.WalletService;
22859 ashik.ali 123
 
124
import in.shop2020.model.v1.catalog.ItemType;
23395 amit.gupta 125
import in.shop2020.model.v1.order.WalletReferenceType;
22859 ashik.ali 126
 
127
@Component
128
public class OrderServiceImpl implements OrderService {
129
 
23568 govind 130
	private static final Logger LOGGER = LogManager.getLogger(OrderServiceImpl.class);
22859 ashik.ali 131
 
132
	@Autowired
23781 ashik.ali 133
	@Qualifier("fofoInventoryItemRepository")
22859 ashik.ali 134
	private InventoryItemRepository inventoryItemRepository;
23650 amit.gupta 135
 
23395 amit.gupta 136
	@Autowired
137
	private WalletService walletService;
22859 ashik.ali 138
 
139
	@Autowired
23781 ashik.ali 140
	@Qualifier("fofoCurrentInventorySnapshotRepository")
22859 ashik.ali 141
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
142
 
143
	@Autowired
144
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
145
 
146
	@Autowired
23655 amit.gupta 147
	private PurchaseReturnService purchaseReturnService;
148
 
149
	@Autowired
150
	private RetailerService retailerService;
151
 
152
	@Autowired
22859 ashik.ali 153
	private CustomerRepository customerRepository;
23650 amit.gupta 154
 
23566 amit.gupta 155
	@Autowired
156
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
22859 ashik.ali 157
 
158
	@Autowired
159
	private AddressRepository addressRepository;
160
 
161
	@Autowired
162
	private FofoLineItemRepository fofoLineItemRepository;
163
 
164
	@Autowired
165
	private FofoOrderItemRepository fofoOrderItemRepository;
23650 amit.gupta 166
 
22859 ashik.ali 167
	@Autowired
168
	private PaymentOptionRepository paymentOptionRepository;
169
 
170
	@Autowired
23650 amit.gupta 171
	private CustomerReturnItemRepository customerReturnItemRepository;
172
 
173
	@Autowired
23781 ashik.ali 174
	@Qualifier("fofoScanRecordRepository")
22859 ashik.ali 175
	private ScanRecordRepository scanRecordRepository;
176
 
177
	@Autowired
178
	private FofoOrderRepository fofoOrderRepository;
179
 
180
	@Autowired
181
	private RetailerRepository retailerRepository;
182
 
183
	@Autowired
184
	private UserRepository userRepository;
185
 
186
	@Autowired
23650 amit.gupta 187
	private BadInventorySnapshotRepository badInventorySnapshotRepository;
188
 
189
	@Autowired
22859 ashik.ali 190
	private UserAccountRepository userAccountRepository;
191
 
192
	@Autowired
193
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
194
 
195
	@Autowired
196
	private CustomerAddressRepository customerAddressRepository;
197
 
198
	@Autowired
23781 ashik.ali 199
	@Qualifier("catalogItemRepository")
22859 ashik.ali 200
	private ItemRepository itemRepository;
23650 amit.gupta 201
 
22859 ashik.ali 202
	@Autowired
203
	private InsuranceProviderRepository insuranceProviderRepository;
23650 amit.gupta 204
 
22859 ashik.ali 205
	@Autowired
206
	private InsurancePolicyRepository insurancePolicyRepository;
23650 amit.gupta 207
 
22859 ashik.ali 208
	@Autowired
209
	private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
23650 amit.gupta 210
 
22859 ashik.ali 211
	@Autowired
212
	private PricingService pricingService;
23650 amit.gupta 213
 
22859 ashik.ali 214
	@Autowired
215
	private PrivateDealUserRepository privateDealUserRepository;
23650 amit.gupta 216
 
22859 ashik.ali 217
	@Autowired
218
	private CounterRepository counterRepository;
23650 amit.gupta 219
 
22859 ashik.ali 220
	@Autowired
23202 ashik.ali 221
	private FofoStoreRepository fofoStoreRepository;
23650 amit.gupta 222
 
23202 ashik.ali 223
	@Autowired
23546 ashik.ali 224
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
23650 amit.gupta 225
 
23365 ashik.ali 226
	@Autowired
23418 ashik.ali 227
	private PrebookingListingRepository prebookingListingRepository;
23650 amit.gupta 228
 
23418 ashik.ali 229
	@Autowired
230
	private PrebookingOrderRepository prebookingOrderRepository;
23650 amit.gupta 231
 
23418 ashik.ali 232
	@Autowired
233
	private PrebookingOrderItemRepository prebookingOrderItemRepository;
23650 amit.gupta 234
 
23418 ashik.ali 235
	@Autowired
22859 ashik.ali 236
	private SchemeService schemeService;
23650 amit.gupta 237
 
23418 ashik.ali 238
	@Autowired
23781 ashik.ali 239
	@Qualifier("fofoInventoryService")
23418 ashik.ali 240
	private InventoryService inventoryService;
23650 amit.gupta 241
 
23418 ashik.ali 242
	@Autowired
23650 amit.gupta 243
	private CustomerCreditNoteRepository customerCreditNoteRepository;
244
 
245
	@Autowired
23418 ashik.ali 246
	private OtpRepository otpRepository;
23650 amit.gupta 247
 
22859 ashik.ali 248
	@Override
23823 amit.gupta 249
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId, boolean accessoriesDeals) throws ProfitMandiBusinessException {
23650 amit.gupta 250
 
22872 ashik.ali 251
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
252
 
23650 amit.gupta 253
		if (!StringUtils.isValidEmailAddress(customCustomer.getEmailId())) {
22872 ashik.ali 254
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
23650 amit.gupta 255
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(),
256
					"VE_1016");
22872 ashik.ali 257
		}
258
 
23650 amit.gupta 259
		if (!StringUtils.isValidMobile(customCustomer.getMobileNumber())) {
22872 ashik.ali 260
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
23650 amit.gupta 261
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(),
262
					"VE_1071");
22872 ashik.ali 263
		}
23650 amit.gupta 264
 
265
		if (!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
23369 ashik.ali 266
			LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
23650 amit.gupta 267
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER,
268
					customCustomer.getGstNumber(), "VE_1072");
23369 ashik.ali 269
		}
23650 amit.gupta 270
 
271
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); // this is for error
22872 ashik.ali 272
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
23650 amit.gupta 273
		Map<Integer, Float> lineItemPrice = new HashMap<>(); // this is for pricing error
274
 
23418 ashik.ali 275
		Map<Integer, Integer> prebookingOrderItemIdQuantityMap = new HashMap<>(); // for prebooking order adjustment
23650 amit.gupta 276
 
22859 ashik.ali 277
		float totalAmount = 0;
23650 amit.gupta 278
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
279
			// itemIds.add(customFofoOrderItem.getItemId());
280
			if (customFofoOrderItem.isPrebookingOrder()) {
281
				prebookingOrderItemIdQuantityMap.put(customFofoOrderItem.getItemId(),
282
						customFofoOrderItem.getQuantity());
23418 ashik.ali 283
			}
23650 amit.gupta 284
			Set<String> serialNumbers = this
285
					.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
286
			if (!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.size()) {
22859 ashik.ali 287
				itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
288
			}
23650 amit.gupta 289
			if (!(customFofoOrderItem.getSellingPrice() > 0)) {
22859 ashik.ali 290
				lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
23650 amit.gupta 291
			} else {
22863 ashik.ali 292
				totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
293
				totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
23650 amit.gupta 294
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
295
					if (serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0) {
22859 ashik.ali 296
						totalAmount = totalAmount + serialNumberDetail.getAmount();
297
					}
298
				}
299
			}
23650 amit.gupta 300
 
22872 ashik.ali 301
			itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
22859 ashik.ali 302
		}
23650 amit.gupta 303
		if (!itemIdQuantity.isEmpty()) {
22859 ashik.ali 304
			// if item quantity does not match with given serialnumbers size
305
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
22925 ashik.ali 306
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
23650 amit.gupta 307
			// return "error";
22859 ashik.ali 308
		}
23650 amit.gupta 309
 
23427 amit.gupta 310
		List<PrebookingListing> prebookingListings = new ArrayList<>();
23650 amit.gupta 311
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
23427 amit.gupta 312
		List<PrebookingOrder> prebookingOrders = new ArrayList<>();
313
		float prebookingOrdersTotalAmount = 0;
23650 amit.gupta 314
		if (!prebookingOrderItemIdQuantityMap.isEmpty()) {
315
			prebookingListings = prebookingListingRepository
316
					.selectAllByItemIds(prebookingOrderItemIdQuantityMap.keySet());
23427 amit.gupta 317
			itemIdPrebookingListingMap = this.prebookingListingsToItemIdPrebookingListingMap(prebookingListings);
23650 amit.gupta 318
			prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId,
319
					customCustomer.getMobileNumber(), prebookingOrderItemIdQuantityMap.keySet());
320
			prebookingOrdersTotalAmount = this.calculatePrebookingOrdersAmount(prebookingOrders,
321
					prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);
23427 amit.gupta 322
		}
23650 amit.gupta 323
 
324
		this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(),
325
				totalAmount - prebookingOrdersTotalAmount);
326
 
327
		if (!lineItemPrice.isEmpty()) {
22859 ashik.ali 328
			// given fofo line item price must be greater than zero
329
			LOGGER.error("requested itemId's selling price must greater than 0");
22925 ashik.ali 330
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
22859 ashik.ali 331
		}
332
 
23650 amit.gupta 333
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository
334
				.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
335
 
22872 ashik.ali 336
		this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 337
 
22872 ashik.ali 338
		List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
23650 amit.gupta 339
		if (items.size() != itemIdCustomFofoOrderItemMap.keySet().size()) {
22872 ashik.ali 340
			LOGGER.error("Requested ItemIds not found in catalog");
23650 amit.gupta 341
			// invalid itemIds
342
			throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(),
343
					"FFORDR_1003");
22872 ashik.ali 344
		}
23650 amit.gupta 345
 
346
		Map<Integer, Item> itemMap = this.toItemMap(items);
347
 
22859 ashik.ali 348
		Set<Integer> nonSerializedItemIds = new HashSet<>();
349
		Set<String> serialNumbers = new HashSet<>();
350
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
351
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
352
		Map<String, String> serialNumberModelName = new HashMap<>();
353
		Map<String, String> serialNumberBrand = new HashMap<>();
23650 amit.gupta 354
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
22872 ashik.ali 355
			Item item = itemMap.get(customFofoOrderItem.getItemId());
23650 amit.gupta 356
			if (item.getType().equals(ItemType.SERIALIZED)) {
357
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
22859 ashik.ali 358
					serialNumbers.add(serialNumberDetail.getSerialNumber());
23650 amit.gupta 359
					if (serialNumberDetail.isInsurance()) {
360
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(),
361
								customFofoOrderItem.getSellingPrice());
362
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(),
363
								serialNumberDetail.getAmount());
364
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(),
365
								(item.getModelName() + item.getModelNumber()).trim());
22859 ashik.ali 366
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
367
					}
368
				}
23650 amit.gupta 369
			} else {
22872 ashik.ali 370
				nonSerializedItemIds.add(customFofoOrderItem.getItemId());
22859 ashik.ali 371
			}
372
		}
23650 amit.gupta 373
 
22859 ashik.ali 374
		Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
375
		Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
23650 amit.gupta 376
		// Map<String, Float> serialNumberItemPrice = new HashMap<>();
377
 
378
		if (!serialNumbers.isEmpty()) {
379
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId,
23968 amit.gupta 380
					serialNumbers, false);
23397 amit.gupta 381
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
23650 amit.gupta 382
			for (InventoryItem inventoryItem : serializedInventoryItems) {
383
				if (inventoryItem.getGoodQuantity() == 1) {
384
					if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())) {
23397 amit.gupta 385
						serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
23650 amit.gupta 386
					} else {
23397 amit.gupta 387
						Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
388
						itemIdInventoryItems.add(inventoryItem);
389
						serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
390
					}
391
				}
392
			}
393
		}
23418 ashik.ali 394
 
23650 amit.gupta 395
		if (!nonSerializedItemIds.isEmpty()) {
396
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId,
397
					nonSerializedItemIds);
22872 ashik.ali 398
			LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
23650 amit.gupta 399
			for (InventoryItem it : nonSerializedInventoryItems) {
400
				if (it.getGoodQuantity() > 0) {
401
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())) {
22859 ashik.ali 402
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
23650 amit.gupta 403
					} else {
22859 ashik.ali 404
						Set<InventoryItem> tmp = new HashSet<>();
405
						tmp.add(it);
406
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
407
					}
408
				}
409
			}
410
		}
23650 amit.gupta 411
 
22872 ashik.ali 412
		this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 413
 
414
		Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
23650 amit.gupta 415
		Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); // to keep track of inventoryitem quanity
416
																				// used for scan records insertion
22859 ashik.ali 417
 
418
		LOGGER.info("itemMap keys {}", itemMap.keySet());
23650 amit.gupta 419
		// Lets reduce quantity and decide what inventory items to use.
420
		for (Item item : items) {
421
			if (item.getType().equals(ItemType.SERIALIZED)) {
422
				// TODO:handle null
423
				if (serializedInventoryItemMap.get(item.getId()) == null
424
						|| itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails()
425
								.size() != serializedInventoryItemMap.get(item.getId()).size()) {
426
					// not enough serial numbers
427
					// LOGGER.info("serialNumbers {}", serialNumbers);
428
					// LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
22872 ashik.ali 429
					LOGGER.error("itemId {} => mismatch size of requested serial numbers", item.getId());
22955 ashik.ali 430
					Function<SerialNumberDetail, String> serialNumberDetailToSerialNumberFunction = new Function<SerialNumberDetail, String>() {
431
						@Override
432
						public String apply(SerialNumberDetail serialNumberDetail) {
433
							return serialNumberDetail.getSerialNumber();
434
						}
435
					};
23650 amit.gupta 436
					throw new ProfitMandiBusinessException("invalidSerialNumbers",
437
							itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream()
438
									.map(serialNumberDetailToSerialNumberFunction).collect(Collectors.toList()),
439
							"FFORDR_1004");
22872 ashik.ali 440
				}
22859 ashik.ali 441
				Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
23650 amit.gupta 442
				for (InventoryItem inventoryItem : inventoryItemsSerializedserialized) {
22872 ashik.ali 443
					inventoryItem.setGoodQuantity(0);
444
					inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
22859 ashik.ali 445
				}
446
				inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
23650 amit.gupta 447
			} else {
22859 ashik.ali 448
				Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
22872 ashik.ali 449
				int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
22859 ashik.ali 450
				int totalLeft = quantityToBill;
451
				Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
23650 amit.gupta 452
				if (inventoryItemsNonSerialized != null) {
453
					for (InventoryItem inventoryItem : inventoryItemsNonSerialized) {
454
						if (totalLeft > 0) {
22859 ashik.ali 455
							int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
456
							inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
23650 amit.gupta 457
							inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity() - toUse);
22859 ashik.ali 458
							totalLeft = totalLeft - toUse;
459
							inventoryItemsNonSerializedUsed.add(inventoryItem);
460
						}
461
					}
462
				}
23650 amit.gupta 463
 
464
				if (totalLeft > 0) {
465
					// not enough quanity for non-serialized
22859 ashik.ali 466
					LOGGER.error("not enough quanity for non-serialized");
23650 amit.gupta 467
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft,
468
							"FFORDR_1005");
22859 ashik.ali 469
				}
470
				inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
471
			}
472
		}
23650 amit.gupta 473
 
474
		Map<Integer, PriceModel> itemIdMopPriceMap = pricingService
475
				.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
23823 amit.gupta 476
		if(accessoriesDeals) {
477
			this.validateDpPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
478
		} else {
479
			this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
480
		}
23650 amit.gupta 481
 
23202 ashik.ali 482
		String fofoStoreCode = this.getFofoStoreCode(fofoId);
22859 ashik.ali 483
 
23650 amit.gupta 484
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this
485
				.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);
486
 
22859 ashik.ali 487
		Customer customer = this.createAndGetCustomer(customCustomer);
23650 amit.gupta 488
 
23191 ashik.ali 489
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());
23650 amit.gupta 490
 
491
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId,
492
				invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
493
 
23612 amit.gupta 494
		this.createPaymentOptions(fofoOrder, createOrderRequest.getPaymentOptions());
23650 amit.gupta 495
 
496
		this.processPrebookingOrders(fofoId, fofoOrder.getId(), prebookingOrders, prebookingOrderItemIdQuantityMap,
497
				itemIdPrebookingListingMap);
498
 
23172 ashik.ali 499
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
23650 amit.gupta 500
 
23172 ashik.ali 501
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
23650 amit.gupta 502
 
23172 ashik.ali 503
		Integer stateId = null;
23650 amit.gupta 504
		if (customerAddress.getState().equals(retailerAddress.getState())) {
505
			try {
23172 ashik.ali 506
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
23650 amit.gupta 507
			} catch (Exception e) {
23172 ashik.ali 508
				LOGGER.error("Unable to get state rates");
509
			}
510
		}
23650 amit.gupta 511
 
512
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
513
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(),
514
					itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), stateId);
515
 
22859 ashik.ali 516
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
23650 amit.gupta 517
 
22859 ashik.ali 518
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
23650 amit.gupta 519
 
520
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(),
521
					customFofoOrderItem.getQuantity());
522
 
22859 ashik.ali 523
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
524
		}
23650 amit.gupta 525
 
22859 ashik.ali 526
		// insurance calculation is insurance flag is enabled
23650 amit.gupta 527
		if (!insuranceSerialNumberItemPrice.isEmpty()) {
22859 ashik.ali 528
			LOGGER.info("Processing for insurence for serialNumbers");
23650 amit.gupta 529
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(
530
					new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
531
			InsuranceProvider insuranceProvider = insuranceProviderRepository
532
					.selectByName(ProfitMandiConstants.GADGET_COPS);
533
 
534
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount,
535
					insurancePricesMap);
536
 
537
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap,
538
					itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
539
 
540
			LocalDate customerDateOfBirth = this
541
					.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
542
 
543
			for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
544
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this
545
						.createPolicyNumberGenerationSequence();
546
 
547
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(fofoOrder.getInvoiceNumber(), fofoId,
22859 ashik.ali 548
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
23650 amit.gupta 549
						insuranceSerialNumberSaleAmount.get(entry.getKey()), entry.getValue(), entry.getKey(),
550
						serialNumberModelName.get(entry.getKey()), serialNumberBrand.get(entry.getKey()),
551
						policyNumberGenerationSequence.getSequence(), insuranceProvider.getId(), customer,
552
						customerDateOfBirth, customerAddress);
553
 
554
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(
555
						serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()),
556
						entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
557
				String walletDescription = "Sale of " + insurancePolicy.getPolicyNumber() + " for "
558
						+ fofoOrder.getInvoiceNumber();
559
				walletService.consumeAmountFromWallet(fofoId, insurancePolicy.getId(),
23395 amit.gupta 560
						WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getPurchaseAmount());
23650 amit.gupta 561
 
562
				try {
22859 ashik.ali 563
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
564
					insurancePolicy.setPosted(true);
23650 amit.gupta 565
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
566
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(),
567
							profitMandiBusinessException);
22859 ashik.ali 568
				}
569
				insurancePolicyRepository.persist(insurancePolicy);
570
			}
571
		}
23365 ashik.ali 572
		schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
23650 amit.gupta 573
 
22859 ashik.ali 574
		return fofoOrder.getId();
575
	}
23650 amit.gupta 576
 
577
	private float calculatePrebookingOrdersAmount(List<PrebookingOrder> prebookingOrders,
578
			Map<Integer, Integer> prebookingOrderItemIdQuantityMap,
579
			Map<Integer, PrebookingListing> itemIdPrebookingListingMap) {
580
		// List<PrebookingOrder> prebookingOrders =
581
		// prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId,
582
		// customerMobileNumber, prebookingOrderItemIdQuantityMap.keySet());
23418 ashik.ali 583
		float totalAmount = 0;
23650 amit.gupta 584
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
23418 ashik.ali 585
			int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
586
			PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
23650 amit.gupta 587
			if (requestedQuantity < prebookingOrder.getAvailableQuantity()) {
588
				LOGGER.info("when requestedQuantity < then requestedQuantity [{}] * advanceAmount [{}]",
589
						requestedQuantity, prebookingListing.getAdvanceAmount());
23418 ashik.ali 590
				totalAmount = totalAmount + (requestedQuantity * prebookingListing.getAdvanceAmount());
23650 amit.gupta 591
			} else if (requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
592
				LOGGER.info("else requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity,
593
						prebookingListing.getAdvanceAmount());
594
				totalAmount = totalAmount
595
						+ (prebookingOrder.getAvailableQuantity() * prebookingListing.getAdvanceAmount());
23418 ashik.ali 596
			}
597
		}
598
		return totalAmount;
599
	}
23650 amit.gupta 600
 
601
	private void processPrebookingOrders(int fofoId, int orderId, List<PrebookingOrder> prebookingOrders,
602
			Map<Integer, Integer> prebookingOrderItemIdQuantityMap,
603
			Map<Integer, PrebookingListing> itemIdPrebookingListingMap) throws ProfitMandiBusinessException {
604
		// Map<Integer, PrebookingOrder> prebookingOrderIdPrebookingOrderMap =
605
		// this.prebookingOrdersToPrebookingOrderIdPrebookingOrderMap(prebookingOrders);
606
 
607
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
608
			if (prebookingOrder.getCompleteTimestamp() == null) {
23418 ashik.ali 609
				int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
23650 amit.gupta 610
 
23418 ashik.ali 611
				PrebookingOrderItem prebookingOrderItem = new PrebookingOrderItem();
23650 amit.gupta 612
				if (requestedQuantity < prebookingOrder.getAvailableQuantity()) {
23418 ashik.ali 613
					prebookingOrder.setAvailableQuantity(prebookingOrder.getAvailableQuantity() - requestedQuantity);
614
					prebookingOrderItem.setQuantity(requestedQuantity);
23650 amit.gupta 615
				} else if (requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
23418 ashik.ali 616
					prebookingOrderItem.setQuantity(prebookingOrder.getAvailableQuantity());
617
					prebookingOrder.setAvailableQuantity(0);
618
				}
23650 amit.gupta 619
				if (prebookingOrder.getAvailableQuantity() == 0) {
23418 ashik.ali 620
					prebookingOrder.setCompleteTimestamp(LocalDateTime.now());
621
				}
622
				prebookingOrderRepository.persist(prebookingOrder);
23650 amit.gupta 623
 
23418 ashik.ali 624
				prebookingOrderItem.setOrderId(orderId);
625
				prebookingOrderItem.setItemId(prebookingOrder.getItemId());
626
				PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
627
				prebookingOrderItem.setAdvanceAmount(prebookingListing.getAdvanceAmount());
23650 amit.gupta 628
 
23418 ashik.ali 629
				prebookingOrderItemRepository.persist(prebookingOrderItem);
23650 amit.gupta 630
 
631
				walletService.addAmountToWallet(fofoId, prebookingOrder.getId(), WalletReferenceType.PREBOOKING_ORDER,
632
						"Advance Amount credited for Prebooking Order", prebookingListing.getAdvanceAmount());
23418 ashik.ali 633
			}
23650 amit.gupta 634
 
23418 ashik.ali 635
		}
636
	}
23650 amit.gupta 637
 
638
	private Map<Integer, PrebookingListing> prebookingListingsToItemIdPrebookingListingMap(
639
			List<PrebookingListing> prebookingListings) {
23418 ashik.ali 640
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
23650 amit.gupta 641
		for (PrebookingListing prebookingListing : prebookingListings) {
23418 ashik.ali 642
			itemIdPrebookingListingMap.put(prebookingListing.getItemId(), prebookingListing);
643
		}
644
		return itemIdPrebookingListingMap;
645
	}
23650 amit.gupta 646
 
647
	private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails) {
23377 ashik.ali 648
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 649
		for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
650
			if (serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
23377 ashik.ali 651
				serialNumbers.add(serialNumberDetail.getSerialNumber());
652
			}
653
		}
654
		return serialNumbers;
655
	}
23650 amit.gupta 656
 
22859 ashik.ali 657
	@Override
23596 ashik.ali 658
	public PdfModel getInvoicePdfModel(int orderId) throws ProfitMandiBusinessException {
659
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
660
		return this.getInvoicePdfModel(fofoOrder);
661
	}
23650 amit.gupta 662
 
663
	private PdfModel getInvoicePdfModel(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
664
 
665
		List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
666
				.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
667
 
23552 amit.gupta 668
		List<CustomPaymentOption> paymentOptions = new ArrayList<>();
669
 
22859 ashik.ali 670
		PdfModel pdfModel = new PdfModel();
23650 amit.gupta 671
 
672
		for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
23552 amit.gupta 673
			CustomPaymentOption cpi = new CustomPaymentOption();
674
			cpi.setAmount(paymentOptionTransaction.getAmount());
23650 amit.gupta 675
			cpi.setPaymentOption(
676
					paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());
23558 amit.gupta 677
			paymentOptions.add(cpi);
23552 amit.gupta 678
		}
679
		pdfModel.setPaymentOptions(paymentOptions);
22859 ashik.ali 680
		pdfModel.setAuther("profitmandi");
681
		pdfModel.setTitle("Retailer Invoice");
682
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
23650 amit.gupta 683
 
22859 ashik.ali 684
		// insurance calculation
23650 amit.gupta 685
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository
686
				.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
22859 ashik.ali 687
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
688
		final float totalInsuranceTaxRate = 18;
23650 amit.gupta 689
		for (InsurancePolicy insurancePolicy : insurancePolicies) {
22859 ashik.ali 690
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
691
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
23650 amit.gupta 692
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #"
693
					+ insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
22859 ashik.ali 694
			customInsurancePolicy.setHsnCode("998716");
695
			customInsurancePolicy.setRate(taxableInsurancePrice);
696
			customInsurancePolicy.setIgstRate(18);
23650 amit.gupta 697
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
22936 amit.gupta 698
			customInsurancePolicy.setCgstRate(9);
23650 amit.gupta 699
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
22859 ashik.ali 700
			customInsurancePolicy.setSgstRate(9);
23650 amit.gupta 701
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
22859 ashik.ali 702
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
703
			customInsurancePolicies.add(customInsurancePolicy);
704
		}
705
		pdfModel.setInsurancePolicies(customInsurancePolicies);
23001 amit.gupta 706
		List<String> tncs = new ArrayList<>();
707
		tncs.add("I agree that goods received are in good working condition");
708
		tncs.add("Goods once sold cannot be exchanged or taken back");
709
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
23650 amit.gupta 710
		if (pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
711
			tncs.add("Damage protection provided is the responisibility of Protection Provider only");
712
		}
23001 amit.gupta 713
		pdfModel.setTncs(tncs);
23655 amit.gupta 714
 
715
		pdfModel.setCustomer(getCustomCustomer(fofoOrder));
22859 ashik.ali 716
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
717
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
23650 amit.gupta 718
 
23596 ashik.ali 719
		Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
22859 ashik.ali 720
		PrivateDealUser privateDealUser = null;
23650 amit.gupta 721
		try {
22859 ashik.ali 722
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23650 amit.gupta 723
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 724
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
725
		}
23650 amit.gupta 726
 
22859 ashik.ali 727
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
728
		CustomRetailer customRetailer = new CustomRetailer();
729
		customRetailer.setBusinessName(retailer.getName());
730
		customRetailer.setMobileNumber(user.getMobileNumber());
23650 amit.gupta 731
		// customRetailer.setTinNumber(retailer.getNumber());
732
		if (privateDealUser == null) {
22859 ashik.ali 733
			customRetailer.setGstNumber(null);
23650 amit.gupta 734
		} else {
735
			if (null != privateDealUser.getCounterId()) {
22859 ashik.ali 736
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
737
				customRetailer.setGstNumber(counter.getGstin());
23650 amit.gupta 738
			} else {
22859 ashik.ali 739
				customRetailer.setGstNumber(null);
740
			}
741
		}
23650 amit.gupta 742
		Address retailerAddress = addressRepository
743
				.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
22859 ashik.ali 744
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
745
		pdfModel.setRetailer(customRetailer);
22925 ashik.ali 746
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
23650 amit.gupta 747
 
22859 ashik.ali 748
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
23650 amit.gupta 749
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
22859 ashik.ali 750
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
23650 amit.gupta 751
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate()
752
					+ fofoOrderItem.getCgstRate();
22859 ashik.ali 753
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
754
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
23650 amit.gupta 755
 
22859 ashik.ali 756
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
23650 amit.gupta 757
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
758
					+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
23377 ashik.ali 759
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
23650 amit.gupta 760
			// LOGGER.info("serialNumbers {}", serialNumbers);
761
			// LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
762
			if (!serialNumbers.isEmpty()) {
763
				customFofoOrderItem.setDescription(
764
						customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
23377 ashik.ali 765
			}
22859 ashik.ali 766
			customFofoOrderItem.setRate(taxableSellingPrice);
767
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
768
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
23650 amit.gupta 769
			customFofoOrderItem.setNetAmount(
770
					(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
22859 ashik.ali 771
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
772
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
773
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
774
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
775
			customFofoOrderItem.setIgstAmount(igstAmount);
776
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
777
			customFofoOrderItem.setCgstAmount(cgstAmount);
778
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
779
			customFofoOrderItem.setSgstAmount(sgstAmount);
780
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
781
			customerFofoOrderItems.add(customFofoOrderItem);
782
		}
783
		pdfModel.setOrderItems(customerFofoOrderItems);
784
		return pdfModel;
23650 amit.gupta 785
 
22859 ashik.ali 786
	}
23650 amit.gupta 787
 
23655 amit.gupta 788
	private CustomCustomer getCustomCustomer(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
789
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
790
		CustomCustomer customCustomer = new CustomCustomer();
791
		customCustomer.setFirstName(customer.getFirstName());
792
		customCustomer.setLastName(customer.getLastName());
793
		customCustomer.setEmailId(customer.getEmailId());
794
		customCustomer.setMobileNumber(customer.getMobileNumber());
795
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
796
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
797
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
798
		return customCustomer;
799
	}
800
 
23596 ashik.ali 801
	@Override
802
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
803
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
804
		return this.getInvoicePdfModel(fofoOrder);
805
	}
23650 amit.gupta 806
 
22859 ashik.ali 807
	public String getBillingAddress(CustomerAddress customerAddress) {
808
		StringBuilder address = new StringBuilder();
809
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
810
			address.append(customerAddress.getLine1());
811
			address.append(", ");
812
		}
813
 
814
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
815
			address.append(customerAddress.getLine2());
816
			address.append(", ");
817
		}
818
 
819
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
820
			address.append(customerAddress.getLandmark());
821
			address.append(", ");
822
		}
823
 
824
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
825
			address.append(customerAddress.getCity());
826
			address.append(", ");
827
		}
828
 
829
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
830
			address.append(customerAddress.getState());
831
		}
832
 
833
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
834
			address.append("- ");
835
			address.append(customerAddress.getPinCode());
836
		}
837
 
838
		return address.toString();
839
	}
23650 amit.gupta 840
 
22859 ashik.ali 841
	@Override
23650 amit.gupta 842
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException {
843
		try {
22859 ashik.ali 844
			JSONObject cartObject = new JSONObject(cartJson);
845
			Iterator<?> keys = cartObject.keys();
23650 amit.gupta 846
 
22859 ashik.ali 847
			Set<Integer> itemIds = new HashSet<>();
848
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
23650 amit.gupta 849
 
850
			while (keys.hasNext()) {
851
				String key = (String) keys.next();
852
				if (cartObject.get(key) instanceof JSONObject) {
22859 ashik.ali 853
					LOGGER.info(cartObject.get(key).toString());
854
				}
855
				CartFofo cf = new CartFofo();
856
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
857
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
23650 amit.gupta 858
 
859
				if (cf.getQuantity() <= 0) {
22859 ashik.ali 860
					continue;
861
				}
862
				cartItems.add(cf);
863
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
864
			}
23650 amit.gupta 865
			Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
866
			if (itemIds.size() > 0) {
22859 ashik.ali 867
				List<Item> items = itemRepository.selectByIds(itemIds);
23650 amit.gupta 868
				for (Item i : items) {
22859 ashik.ali 869
					itemMap.put(i.getId(), i);
870
				}
23650 amit.gupta 871
 
22859 ashik.ali 872
			}
23650 amit.gupta 873
			for (CartFofo cf : cartItems) {
22859 ashik.ali 874
				Item i = itemMap.get(cf.getItemId());
23650 amit.gupta 875
				if (i == null) {
22859 ashik.ali 876
					continue;
877
				}
23650 amit.gupta 878
				cf.setDisplayName(getValidName(i.getBrand()) + " " + getValidName(i.getModelName()) + " "
879
						+ getValidName(i.getModelNumber()) + " " + getValidName(i.getColor()).replaceAll("\\s+", " "));
22859 ashik.ali 880
				cf.setItemType(i.getType());
881
			}
882
			return cartItems;
23650 amit.gupta 883
		} catch (Exception e) {
22859 ashik.ali 884
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 885
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 886
		}
887
	}
23650 amit.gupta 888
 
23202 ashik.ali 889
	@Override
23650 amit.gupta 890
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue,
23891 amit.gupta 891
			LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 892
		long countItems = 0;
893
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 894
 
895
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
23973 govind 896
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, null,
897
					null, offset, limit);
898
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, null,
899
					null);
23650 amit.gupta 900
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
23973 govind 901
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, null,
902
					null, offset, limit);
903
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, null, null);
23650 amit.gupta 904
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
23973 govind 905
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, null,
906
					null, offset, limit);
907
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, null, null);
23650 amit.gupta 908
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
23973 govind 909
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, null, null,
23650 amit.gupta 910
					offset, limit);
23973 govind 911
			countItems=fofoOrderRepository.selectCountByItemName(fofoId, searchValue, null, null);
23953 amit.gupta 912
		} else if (searchType == SearchType.INVOICE_NUMBER && !searchValue.isEmpty()) {
913
			fofoOrders = Arrays.asList(fofoOrderRepository.selectByFofoIdAndInvoiceNumber(fofoId, searchValue));
914
			countItems = fofoOrders.size();
23973 govind 915
		}  else if(searchType == SearchType.DATE_RANGE){
23891 amit.gupta 916
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
917
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDate, endDate);
23202 ashik.ali 918
		}
919
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 920
 
23202 ashik.ali 921
		map.put("saleHistories", fofoOrders);
922
		map.put("start", offset + 1);
923
		map.put("size", countItems);
924
		map.put("searchType", searchType);
23351 ashik.ali 925
		map.put("searchTypes", SearchType.values());
23891 amit.gupta 926
		map.put("startDate", startDate);
23973 govind 927
		map.put("searchValue", searchValue);
23891 amit.gupta 928
		map.put(ProfitMandiConstants.END_TIME, endDate);
23650 amit.gupta 929
		if (fofoOrders.size() < limit) {
23202 ashik.ali 930
			map.put("end", offset + fofoOrders.size());
23650 amit.gupta 931
		} else {
23202 ashik.ali 932
			map.put("end", offset + limit);
933
		}
934
		return map;
935
	}
936
 
937
	@Override
23650 amit.gupta 938
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue,
23891 amit.gupta 939
			LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 940
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 941
 
942
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
23891 amit.gupta 943
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDate,
944
					endDate, offset, limit);
23650 amit.gupta 945
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
23891 amit.gupta 946
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDate,
947
					endDate, offset, limit);
23650 amit.gupta 948
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
23891 amit.gupta 949
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDate,
950
					endDate, offset, limit);
23650 amit.gupta 951
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
23891 amit.gupta 952
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDate, endDate,
23650 amit.gupta 953
					offset, limit);
23973 govind 954
 
955
		}  else if (searchType == SearchType.DATE_RANGE){
23891 amit.gupta 956
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
23202 ashik.ali 957
		}
958
		Map<String, Object> map = new HashMap<>();
959
		map.put("saleHistories", fofoOrders);
23973 govind 960
		map.put("searchType", searchType);
961
		map.put("searchTypes", SearchType.values());
962
		map.put("startDate", startDate);
963
		map.put("searchValue", searchValue);
964
		map.put(ProfitMandiConstants.END_TIME, endDate);
23202 ashik.ali 965
		return map;
966
	}
23650 amit.gupta 967
 
968
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
23202 ashik.ali 969
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 970
		return fofoStore.getCode();
23202 ashik.ali 971
	}
23650 amit.gupta 972
 
973
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId) {
23191 ashik.ali 974
		CustomerAddress customerAddress = null;
23650 amit.gupta 975
		try {
976
			// CustomAddress customAddress = customCustomer.getAddress();
977
			customerAddress = customerAddressRepository.selectByParams(customAddress.getName(),
978
					customAddress.getLine1(), customAddress.getLine2(), customAddress.getLandmark(),
979
					customAddress.getCity(), customAddress.getPinCode(), customAddress.getState(),
980
					customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
981
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 982
			LOGGER.warn("Customer address not found with [{}]", customAddress);
23191 ashik.ali 983
			customerAddress = new CustomerAddress();
984
			this.setCustomerAddress(customerAddress, customAddress);
985
			customerAddress.setCustomerId(customerId);
986
		}
987
		customerAddressRepository.persist(customerAddress);
988
		return customerAddress;
989
	}
23650 amit.gupta 990
 
991
	private String getValidName(String name) {
992
		return name != null ? name : "";
22859 ashik.ali 993
	}
23650 amit.gupta 994
 
995
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
23377 ashik.ali 996
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 997
		for (FofoLineItem fofoLineItem : fofoLineItems) {
998
			if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
23377 ashik.ali 999
				serialNumbers.add(fofoLineItem.getSerialNumber());
22955 ashik.ali 1000
			}
23377 ashik.ali 1001
		}
1002
		return serialNumbers;
22859 ashik.ali 1003
	}
23650 amit.gupta 1004
 
1005
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence() {
22859 ashik.ali 1006
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
23650 amit.gupta 1007
		try {
22859 ashik.ali 1008
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
1009
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
1010
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
23650 amit.gupta 1011
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 1012
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
1013
			policyNumberGenerationSequence.setSequence(1);
1014
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
1015
		}
1016
		return policyNumberGenerationSequence;
1017
	}
23650 amit.gupta 1018
 
1019
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber,
1020
			LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress,
1021
			InsurancePolicy insurancePolicy) {
22859 ashik.ali 1022
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
1023
		gadgetCopsInsuranceModel.setBrand(brand);
1024
		gadgetCopsInsuranceModel.setModelName(modelName);
1025
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
1026
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
1027
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
1028
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
1029
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
1030
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
1031
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
1032
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
1033
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
1034
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
1035
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
1036
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
1037
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
1038
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
1039
		return gadgetCopsInsuranceModel;
1040
	}
23650 amit.gupta 1041
 
1042
	private InsurancePolicy createInsurancePolicy(String invoiceNumber, int retailerId, float purchaseAmount,
1043
			float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand,
1044
			int policyNumberGenerationSequence, int insuranceProviderId, Customer customer,
1045
			LocalDate customerDateOfBirth, CustomerAddress customerAddress) {
22859 ashik.ali 1046
		InsurancePolicy insurancePolicy = new InsurancePolicy();
23394 amit.gupta 1047
		insurancePolicy.setInvoiceNumber(invoiceNumber);
22859 ashik.ali 1048
		insurancePolicy.setRetailerId(retailerId);
1049
		insurancePolicy.setPurchaseAmount(purchaseAmount);
1050
		insurancePolicy.setSaleAmount(saleAmount);
1051
		insurancePolicy.setSellingPrice(sellingPrice);
1052
		insurancePolicy.setSerialNumber(serialNumber);
1053
		insurancePolicy.setModelName(modelName);
1054
		insurancePolicy.setBrand(brand);
23650 amit.gupta 1055
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX,
1056
				policyNumberGenerationSequence));
22859 ashik.ali 1057
		insurancePolicy.setProviderId(insuranceProviderId);
1058
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
1059
		insurancePolicy.setCustomerLastName(customer.getLastName());
1060
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
1061
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
1062
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
1063
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
1064
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
1065
		insurancePolicy.setCustomerCity(customerAddress.getCity());
1066
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
1067
		insurancePolicy.setCustomerState(customerAddress.getState());
1068
		return insurancePolicy;
1069
	}
23650 amit.gupta 1070
 
1071
	private void validateInsuranceMargin(Map<String, Float> insuranceSerialNumberItemPrice,
1072
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, Map<Integer, PriceModel> itemIdMopPriceMap,
1073
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap, Map<String, Float> insuranceSerialNumberSaleAmount)
1074
			throws ProfitMandiBusinessException {
22859 ashik.ali 1075
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
23650 amit.gupta 1076
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
22872 ashik.ali 1077
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 1078
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
1079
			float itemSellingPrice = entry.getValue();
1080
			float itemMargin = itemSellingPrice - itemPurchasePrice;
1081
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
1082
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
1083
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
23650 amit.gupta 1084
			if (insuranceMargin < (itemMargin * 30 / 100)) {
22859 ashik.ali 1085
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
1086
			}
1087
		}
23650 amit.gupta 1088
		if (!invalidInsuranceMarginAmount.isEmpty()) {
1089
			LOGGER.error(
1090
					"insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}",
1091
					invalidInsuranceMarginAmount);
1092
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount,
1093
					"FFORDR_1007");
22859 ashik.ali 1094
		}
1095
	}
23650 amit.gupta 1096
 
1097
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice,
1098
			Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap)
1099
			throws ProfitMandiBusinessException {
22859 ashik.ali 1100
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
1101
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
23650 amit.gupta 1102
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
1103
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue())
1104
					.getDealerPrice()) {
1105
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(),
1106
						insuranceSerialNumberSaleAmount.get(entry.getKey()));
22859 ashik.ali 1107
			}
23650 amit.gupta 1108
 
1109
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue())
1110
					.getSellingPrice()) {
1111
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()),
1112
						insurancePricesMap.get(entry.getValue()).getDealerPrice());
22859 ashik.ali 1113
			}
1114
		}
23650 amit.gupta 1115
 
22859 ashik.ali 1116
		// insurance sale amount can not be lesser than insurance purchase amount
23650 amit.gupta 1117
		if (!invalidInsurancePurchaseSaleAmount.isEmpty()) {
1118
			LOGGER.error(
1119
					"Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount",
1120
					invalidInsurancePurchaseSaleAmount);
1121
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount",
1122
					invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 1123
		}
23650 amit.gupta 1124
 
1125
		if (!invalidInsuranceSalePurchaseAmount.isEmpty()) {
1126
			LOGGER.error(
1127
					"Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount",
1128
					invalidInsuranceSalePurchaseAmount);
1129
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount",
1130
					invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 1131
		}
1132
	}
23823 amit.gupta 1133
	private void validateDpPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1134
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
1135
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoLineItemMap.entrySet()) {
1136
			int itemId = entry.getKey();
1137
			CustomFofoOrderItem customFofoOrderItem = entry.getValue();
1138
			PriceModel priceModel = itemIdMopPriceMap.get(itemId);
1139
			if(customFofoOrderItem.getSerialNumberDetails().size() > 0) {
23857 amit.gupta 1140
				if(priceModel.getPrice() > customFofoOrderItem.getSellingPrice()) {
23823 amit.gupta 1141
					throw new ProfitMandiBusinessException("Selling Price", itemRepository.selectById(itemId).getItemDescription(), "FFORDR_1010");
1142
				}
1143
			} else {
23857 amit.gupta 1144
				if(priceModel.getPurchasePrice() > customFofoOrderItem.getSellingPrice()) {
23823 amit.gupta 1145
					throw new ProfitMandiBusinessException("Selling Price", itemRepository.selectById(itemId).getItemDescription(), "Selling Price should not be less than DP");
1146
				}
1147
			}
1148
		}
1149
	}
23650 amit.gupta 1150
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1151
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
22859 ashik.ali 1152
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
1153
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
23650 amit.gupta 1154
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
22872 ashik.ali 1155
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
23650 amit.gupta 1156
			if (entry.getValue().getPrice() < Float.MAX_VALUE
1157
					&& customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
22872 ashik.ali 1158
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 1159
			}
23650 amit.gupta 1160
			if (entry.getValue().isMop()
1161
					&& customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()) {
22872 ashik.ali 1162
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
1163
			}
22859 ashik.ali 1164
		}
23650 amit.gupta 1165
 
1166
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1167
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
1168
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 1169
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 1170
		}
23650 amit.gupta 1171
 
23857 amit.gupta 1172
		if (!invalidDiscountAmountMap.isEmpty()) {
23650 amit.gupta 1173
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}",
1174
					invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 1175
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 1176
		}
1177
	}
23650 amit.gupta 1178
 
1179
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString)
1180
			throws ProfitMandiBusinessException {
22859 ashik.ali 1181
		LocalDate customerDateOfBirth = null;
23650 amit.gupta 1182
		try {
22859 ashik.ali 1183
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
23650 amit.gupta 1184
		} catch (DateTimeException dateTimeException) {
23596 ashik.ali 1185
			LOGGER.error("Unable to parse dateOfBirth message {}", dateTimeException.getMessage());
22925 ashik.ali 1186
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 1187
		}
1188
		return customerDateOfBirth;
1189
	}
23650 amit.gupta 1190
 
1191
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
1192
			Map<Integer, Integer> inventoryItemQuantityUsed) {
1193
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1194
			inventoryItem.setLastScanType(ScanType.SALE);
1195
			inventoryItemRepository.persist(inventoryItem);
1196
			ScanRecord scanRecord = new ScanRecord();
1197
			scanRecord.setInventoryItemId(inventoryItem.getId());
1198
			scanRecord.setFofoId(fofoId);
23650 amit.gupta 1199
			// correct this
22859 ashik.ali 1200
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1201
			scanRecord.setType(ScanType.SALE);
1202
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1203
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1204
 
22859 ashik.ali 1205
		}
1206
	}
23650 amit.gupta 1207
 
1208
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1209
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1210
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1211
			FofoLineItem fofoLineItem = new FofoLineItem();
1212
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1213
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1214
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1215
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1216
			fofoLineItemRepository.persist(fofoLineItem);
1217
		}
1218
	}
23650 amit.gupta 1219
 
1220
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1221
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1222
			throws ProfitMandiBusinessException {
22859 ashik.ali 1223
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1224
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1225
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1226
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1227
		fofoOrderItem.setOrderId(fofoOrderId);
1228
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1229
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
1230
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1231
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1232
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1233
		if (stateId != null) {
23172 ashik.ali 1234
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1235
		} else {
23172 ashik.ali 1236
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1237
		}
23393 amit.gupta 1238
		float cost = 0;
23650 amit.gupta 1239
		for (InventoryItem inventoryItem : inventoryItems) {
1240
			if (stateId == null) {
23172 ashik.ali 1241
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1242
			} else {
23172 ashik.ali 1243
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1244
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1245
			}
23650 amit.gupta 1246
 
22859 ashik.ali 1247
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1248
			break;
1249
		}
23650 amit.gupta 1250
		for (InventoryItem inventoryItem : inventoryItems) {
1251
			if (inventoryItem.getSerialNumber() != null) {
23393 amit.gupta 1252
				cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
1253
			} else {
1254
				cost += inventoryItem.getUnitPrice();
23382 amit.gupta 1255
			}
1256
		}
23650 amit.gupta 1257
		cost = cost / customFofoOrderItem.getQuantity();
23382 amit.gupta 1258
		fofoOrderItem.setCost(cost);
22859 ashik.ali 1259
		fofoOrderItem.setBrand(item.getBrand());
1260
		fofoOrderItem.setModelName(item.getModelName());
1261
		fofoOrderItem.setModelNumber(item.getModelNumber());
1262
		fofoOrderItem.setColor(item.getColor());
1263
		fofoOrderItemRepository.persist(fofoOrderItem);
1264
		return fofoOrderItem;
1265
	}
23650 amit.gupta 1266
 
1267
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1268
			int itemId, int quantity) throws ProfitMandiBusinessException {
1269
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1270
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1271
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1272
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1273
			}
1274
		}
1275
	}
23650 amit.gupta 1276
 
1277
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1278
			throws ProfitMandiBusinessException {
1279
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1280
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1281
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1282
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1283
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1284
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1285
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1286
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1287
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1288
			}
22859 ashik.ali 1289
		}
1290
	}
23650 amit.gupta 1291
 
1292
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId,
1293
			InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId) {
22859 ashik.ali 1294
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1295
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1296
		fofoOrder.setCustomerId(customerId);
1297
		fofoOrder.setFofoId(fofoId);
23650 amit.gupta 1298
		fofoOrder.setInvoiceNumber(
1299
				invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
22859 ashik.ali 1300
		fofoOrder.setTotalAmount(totalAmount);
1301
		fofoOrder.setCustomerAddressId(customerAddressId);
1302
		fofoOrderRepository.persist(fofoOrder);
1303
		return fofoOrder;
1304
	}
23650 amit.gupta 1305
 
1306
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException {
22859 ashik.ali 1307
		Customer customer = null;
23650 amit.gupta 1308
		try {
22859 ashik.ali 1309
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
23650 amit.gupta 1310
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 1311
			LOGGER.error("Customer not found with mobileNumber [{}]", customCustomer.getMobileNumber());
22859 ashik.ali 1312
			customer = new Customer();
1313
		}
23190 ashik.ali 1314
		customer.setFirstName(customCustomer.getFirstName());
1315
		customer.setLastName(customCustomer.getLastName());
1316
		customer.setEmailId(customCustomer.getEmailId());
1317
		customer.setMobileNumber(customCustomer.getMobileNumber());
1318
		customerRepository.persist(customer);
22859 ashik.ali 1319
		return customer;
1320
	}
23650 amit.gupta 1321
 
1322
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId,
1323
			String fofoStoreCode) {
22859 ashik.ali 1324
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
23650 amit.gupta 1325
		try {
22859 ashik.ali 1326
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1327
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
23650 amit.gupta 1328
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 1329
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1330
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23370 ashik.ali 1331
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
22859 ashik.ali 1332
			invoiceNumberGenerationSequence.setSequence(1);
1333
		}
1334
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1335
		return invoiceNumberGenerationSequence;
1336
	}
23650 amit.gupta 1337
 
1338
	private void validateItemsSerializedNonSerialized(List<Item> items,
1339
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1340
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1341
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1342
		for (Item i : items) {
22872 ashik.ali 1343
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1344
			if (i.getType().equals(ItemType.SERIALIZED)) {
1345
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1346
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1347
				}
23650 amit.gupta 1348
			} else {
1349
				Set<String> serialNumbers = this
1350
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1351
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1352
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1353
				}
1354
			}
1355
		}
1356
 
23650 amit.gupta 1357
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1358
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1359
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1360
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1361
					"FFORDR_1013");
22859 ashik.ali 1362
		}
1363
 
23650 amit.gupta 1364
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1365
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1366
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1367
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1368
					"FFORDR_1014");
22859 ashik.ali 1369
		}
1370
	}
23650 amit.gupta 1371
 
1372
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1373
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1374
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1375
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1376
		}
23650 amit.gupta 1377
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1378
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1379
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1380
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1381
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1382
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1383
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1384
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1385
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1386
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1387
				Quantity quantity = new Quantity();
1388
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1389
				quantity.setRequested(customFofoOrderItem.getQuantity());
1390
				itemIdQuantityAvailability.setQuantity(quantity);
1391
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1392
			}
22859 ashik.ali 1393
		}
1394
 
23650 amit.gupta 1395
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1396
			// itemIdQuantity request is not valid
23650 amit.gupta 1397
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1398
					itemIdQuantityAvailabilities);
1399
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1400
					"FFORDR_1015");
22859 ashik.ali 1401
		}
1402
	}
23650 amit.gupta 1403
 
1404
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1405
			String serialNumber) {
22872 ashik.ali 1406
		int itemId = 0;
23650 amit.gupta 1407
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1408
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1409
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1410
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1411
					itemId = entry.getKey();
1412
					break;
1413
				}
22859 ashik.ali 1414
			}
1415
		}
22872 ashik.ali 1416
		return itemId;
22859 ashik.ali 1417
	}
23650 amit.gupta 1418
 
1419
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1420
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1421
			@Override
1422
			public Integer apply(Item item) {
1423
				return item.getId();
1424
			}
1425
		};
1426
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1427
			@Override
1428
			public Item apply(Item item) {
1429
				return item;
1430
			}
1431
		};
1432
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1433
	}
1434
 
23650 amit.gupta 1435
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1436
		customerAddress.setName(customAddress.getName());
1437
		customerAddress.setLine1(customAddress.getLine1());
1438
		customerAddress.setLine2(customAddress.getLine2());
1439
		customerAddress.setLandmark(customAddress.getLandmark());
1440
		customerAddress.setCity(customAddress.getCity());
1441
		customerAddress.setPinCode(customAddress.getPinCode());
1442
		customerAddress.setState(customAddress.getState());
1443
		customerAddress.setCountry(customAddress.getCountry());
1444
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1445
	}
1446
 
23650 amit.gupta 1447
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1448
		CustomAddress customAddress = new CustomAddress();
1449
		customAddress.setName(address.getName());
1450
		customAddress.setLine1(address.getLine1());
1451
		customAddress.setLine2(address.getLine2());
1452
		customAddress.setLandmark(address.getLandmark());
1453
		customAddress.setCity(address.getCity());
1454
		customAddress.setPinCode(address.getPinCode());
1455
		customAddress.setState(address.getState());
1456
		customAddress.setCountry(address.getCountry());
1457
		customAddress.setPhoneNumber(address.getPhoneNumber());
1458
		return customAddress;
1459
	}
1460
 
23650 amit.gupta 1461
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1462
		CustomAddress customAddress = new CustomAddress();
1463
		customAddress.setName(customerAddress.getName());
1464
		customAddress.setLine1(customerAddress.getLine1());
1465
		customAddress.setLine2(customerAddress.getLine2());
1466
		customAddress.setLandmark(customerAddress.getLandmark());
1467
		customAddress.setCity(customerAddress.getCity());
1468
		customAddress.setPinCode(customerAddress.getPinCode());
1469
		customAddress.setState(customerAddress.getState());
1470
		customAddress.setCountry(customerAddress.getCountry());
1471
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1472
		return customAddress;
1473
	}
1474
 
23650 amit.gupta 1475
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1476
			throws ProfitMandiBusinessException {
23365 ashik.ali 1477
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1478
 
22859 ashik.ali 1479
		float calculatedAmount = 0;
23650 amit.gupta 1480
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1481
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1482
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1483
		}
23650 amit.gupta 1484
		if (calculatedAmount != totalAmount) {
1485
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
1486
					calculatedAmount, totalAmount);
1487
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1488
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1489
		}
23650 amit.gupta 1490
 
23365 ashik.ali 1491
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1492
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1493
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1494
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1495
					"FFORDR_1017");
23365 ashik.ali 1496
		}
22859 ashik.ali 1497
	}
23650 amit.gupta 1498
 
22925 ashik.ali 1499
	@Override
1500
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1501
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1502
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1503
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1504
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1505
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1506
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1507
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1508
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1509
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1510
				newFofoOrderItems.add(fofoOrderItem);
1511
				fofoOrderItemsIterator.remove();
1512
			}
1513
			fofoOrderItems = newFofoOrderItems;
1514
		}
1515
		return fofoOrderItems;
1516
	}
23650 amit.gupta 1517
 
1518
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1519
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1520
			@Override
1521
			public Integer apply(FofoOrderItem fofoOrderItem) {
1522
				return fofoOrderItem.getId();
1523
			}
1524
		};
1525
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1526
	}
23650 amit.gupta 1527
 
1528
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1529
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1530
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1531
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1532
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1533
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1534
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1535
				fofoLineItems2.add(fofoLineItem);
1536
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1537
			} else {
22925 ashik.ali 1538
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1539
			}
1540
		}
1541
		return fofoOrderItemIdFofoLineItemsMap;
1542
	}
23650 amit.gupta 1543
 
1544
	private String getOtpString() {
23418 ashik.ali 1545
		Random rndm_method = new Random();
23650 amit.gupta 1546
		String numbers = "0123456789";
23418 ashik.ali 1547
		char[] otp = new char[5];
22859 ashik.ali 1548
 
23650 amit.gupta 1549
		for (int i = 0; i < 5; i++) {
23418 ashik.ali 1550
			otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
1551
		}
1552
		return String.valueOf(otp);
1553
	}
23650 amit.gupta 1554
 
1555
	private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount) {
1556
		Map<Integer, String> itemIdDescriptionMap = inventoryService
1557
				.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());
23418 ashik.ali 1558
		StringBuilder itemIdAdvanceAmountString = new StringBuilder();
1559
		int index = 0;
23650 amit.gupta 1560
		for (Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {
23418 ashik.ali 1561
			itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));
1562
			itemIdAdvanceAmountString.append("'s Advance amount [");
1563
			itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());
1564
			itemIdAdvanceAmountString.append("]");
23650 amit.gupta 1565
			if (index + 1 < itemIdAdvanceAmount.size()) {
23418 ashik.ali 1566
				itemIdAdvanceAmountString.append(", ");
1567
			}
1568
			index++;
1569
		}
1570
		String text = "Dear Customer, {0} is the OTP that you have requested for prebooking orders for items {1} Don't share your OTP with anyone.";
23650 amit.gupta 1571
		LOGGER.info("OTP to Customer Successfully sends" + text);
23418 ashik.ali 1572
		String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);
1573
		try {
1574
			Utils.sendSms(msg, phone);
1575
		} catch (URISyntaxException e) {
1576
			// TODO Auto-generated catch block
1577
			e.printStackTrace();
1578
		} catch (IOException e) {
1579
			// TODO Auto-generated catch block
1580
			e.printStackTrace();
1581
		}
23650 amit.gupta 1582
 
23418 ashik.ali 1583
	}
23650 amit.gupta 1584
 
23418 ashik.ali 1585
	@Override
23650 amit.gupta 1586
	public int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber,
1587
			Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {
1588
		if (!StringUtils.isValidEmailAddress(customerEmailId)) {
23418 ashik.ali 1589
			LOGGER.error("invalid customer emailId {} ", customerEmailId);
1590
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");
1591
		}
1592
 
23650 amit.gupta 1593
		if (!StringUtils.isValidMobile(customerMobileNumber)) {
23418 ashik.ali 1594
			LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);
1595
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");
1596
		}
23650 amit.gupta 1597
 
23418 ashik.ali 1598
		List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);
1599
		String otp = null;
23650 amit.gupta 1600
		if (otps.size() >= 5) {
1601
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId,
1602
					"FFORDR_1019");
23418 ashik.ali 1603
		}
23650 amit.gupta 1604
		if (!otps.isEmpty()) {
1605
			if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))) {
23418 ashik.ali 1606
				return otps.get(0).getId();
23650 amit.gupta 1607
			} else if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))) {
23418 ashik.ali 1608
				otp = otps.get(0).getOtp();
1609
			}
1610
		}
23650 amit.gupta 1611
		if (otp == null || otp.isEmpty()) {
23418 ashik.ali 1612
			otp = getOtpString();
1613
		}
23650 amit.gupta 1614
 
23418 ashik.ali 1615
		this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);
23650 amit.gupta 1616
 
23418 ashik.ali 1617
		Otp otp_bean = new Otp();
1618
		otp_bean.setEmail(customerEmailId);
1619
		otp_bean.setMobile(customerMobileNumber);
1620
		otp_bean.setOtp(otp);
1621
		otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);
1622
		otp_bean.setCreatedOn(LocalDateTime.now());
1623
		otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
1624
		otpRepository.persist(otp_bean);
23650 amit.gupta 1625
 
23418 ashik.ali 1626
		return otp_bean.getId();
1627
	}
23650 amit.gupta 1628
 
23418 ashik.ali 1629
	@Override
1630
	public String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)
1631
			throws ProfitMandiBusinessException {
1632
		Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);
1633
		otp.setTryCount(otp.getTryCount() + 1);
23650 amit.gupta 1634
		if (!otp.getOtp().equalsIgnoreCase(otpValue)) {
23418 ashik.ali 1635
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");
1636
		}
23650 amit.gupta 1637
		if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
23418 ashik.ali 1638
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");
1639
		}
23650 amit.gupta 1640
		if (otp.getTryCount() > 5) {
23418 ashik.ali 1641
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");
1642
		}
1643
		otp.setExpired(true);
1644
		otp.setVerified(true);
1645
		otpRepository.persist(otp);
23650 amit.gupta 1646
 
23418 ashik.ali 1647
		return ResponseCodeHolder.getMessage("FFORDR_OK_1002");
1648
	}
23650 amit.gupta 1649
 
23582 ashik.ali 1650
	@Override
23650 amit.gupta 1651
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1652
			throws ProfitMandiBusinessException {
23582 ashik.ali 1653
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1654
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1655
		customer.setFirstName(customCustomer.getFirstName());
1656
		customer.setLastName(customCustomer.getLastName());
1657
		customerRepository.persist(customer);
1658
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1659
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1660
		customerAddressRepository.persist(customerAddress);
1661
	}
23418 ashik.ali 1662
 
23638 amit.gupta 1663
	@Override
23655 amit.gupta 1664
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest) throws ProfitMandiBusinessException {
1665
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1666
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1667
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1668
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1669
		}
23655 amit.gupta 1670
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
1671
		if(foiBadReturnRequest.getMarkedBadArr().size() > billedQty ) {
1672
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1673
		}
23650 amit.gupta 1674
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1675
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1676
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1677
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1678
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
1679
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1680
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1681
			customerReturnItem.setQuantity(1);
1682
			customerReturnItem.setType(ReturnType.BAD);
1683
			//customerReturnItemRepository.persist(customerReturnItem);
1684
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1685
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1686
		}
23655 amit.gupta 1687
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
1688
		for (CustomerReturnItem customerReturnItem: customerReturnItems) {
1689
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(), ReturnType.BAD);
1690
		}
1691
        return creditNote;
23638 amit.gupta 1692
	}
1693
 
23655 amit.gupta 1694
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems) throws ProfitMandiBusinessException {
23650 amit.gupta 1695
 
23638 amit.gupta 1696
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1697
				.selectByFofoId(fofoOrder.getFofoId());
1698
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1699
		invoiceNumberGenerationSequenceRepository.persist(sequence);
23650 amit.gupta 1700
 
23655 amit.gupta 1701
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1702
		CustomerCreditNote creditNote = new CustomerCreditNote();
1703
		creditNote.setCreditNoteNumber(creditNoteNumber);
1704
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1705
		creditNote.setFofoOrderId(fofoOrder.getId());
1706
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1707
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1708
		customerCreditNoteRepository.persist(creditNote);
1709
 
1710
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1711
			customerReturnItem.setCreditNoteId(creditNote.getId());
1712
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1713
		}
23650 amit.gupta 1714
		//this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1715
 
23655 amit.gupta 1716
		return creditNote;
23650 amit.gupta 1717
	}
1718
 
23655 amit.gupta 1719
	@Override
1720
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1721
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1722
		return getCreditNotePdfModel(creditNote);
1723
	}
1724
 
1725
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote) throws ProfitMandiBusinessException {
1726
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
1727
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository.selectAllByCreditNoteId(creditNote.getId());
1728
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
1729
 
1730
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
1731
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoOrder.getFofoId())).get(fofoOrder.getFofoId());
1732
 
1733
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1734
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1735
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1736
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1737
 
1738
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1739
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1740
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1741
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
1742
 
1743
		if(ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())){
1744
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1745
					.collect(Collectors.toSet());
1746
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1747
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1748
			customFofoOrderItem.setDescription(
1749
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1750
		}
1751
 
1752
		customFofoOrderItem.setRate(taxableSellingPrice);
1753
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1754
		customFofoOrderItem.setQuantity(customerReturnItems.size());
1755
		customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
1756
 
1757
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1758
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1759
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1760
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1761
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1762
		customFofoOrderItem.setIgstAmount(igstAmount);
1763
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1764
		customFofoOrderItem.setCgstAmount(cgstAmount);
1765
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1766
		customFofoOrderItem.setSgstAmount(sgstAmount);
1767
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1768
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1769
		customerFofoOrderItems.add(customFofoOrderItem);
1770
 
23650 amit.gupta 1771
		PdfModel pdfModel = new PdfModel();
1772
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1773
		pdfModel.setCustomer(customCustomer);
1774
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1775
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1776
		pdfModel.setTitle("Credit Note");
1777
		pdfModel.setRetailer(customRetailer);
1778
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1779
		pdfModel.setOrderItems(customerFofoOrderItems);
1780
 
23650 amit.gupta 1781
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1782
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1783
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1784
		creditNotePdfModel.setPdfModel(pdfModel);
1785
		return creditNotePdfModel;
1786
	}
23638 amit.gupta 1787
 
22859 ashik.ali 1788
}