Subversion Repositories SmartDukaan

Rev

Rev 23823 | Rev 23891 | 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,
380
					serialNumbers);
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,
891
			String startTimeString, String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 892
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
893
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
894
		long countItems = 0;
895
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 896
 
897
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
898
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime,
899
					endDateTime, offset, limit);
900
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime,
901
					endDateTime);
902
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
903
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime,
904
					endDateTime, offset, limit);
23202 ashik.ali 905
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);
23650 amit.gupta 906
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
907
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime,
908
					endDateTime, offset, limit);
23202 ashik.ali 909
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);
23650 amit.gupta 910
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
911
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime,
912
					offset, limit);
23202 ashik.ali 913
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);
23650 amit.gupta 914
		} else {
23202 ashik.ali 915
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
23297 ashik.ali 916
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);
23202 ashik.ali 917
		}
918
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 919
 
23202 ashik.ali 920
		map.put("saleHistories", fofoOrders);
921
		map.put("start", offset + 1);
922
		map.put("size", countItems);
923
		map.put("searchType", searchType);
23351 ashik.ali 924
		map.put("searchTypes", SearchType.values());
23202 ashik.ali 925
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
926
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
23650 amit.gupta 927
		if (fofoOrders.size() < limit) {
23202 ashik.ali 928
			map.put("end", offset + fofoOrders.size());
23650 amit.gupta 929
		} else {
23202 ashik.ali 930
			map.put("end", offset + limit);
931
		}
932
		return map;
933
	}
934
 
935
	@Override
23650 amit.gupta 936
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue,
937
			String startTimeString, String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 938
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
939
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
940
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 941
 
942
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
943
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime,
944
					endDateTime, offset, limit);
945
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
946
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime,
947
					endDateTime, offset, limit);
948
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
949
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime,
950
					endDateTime, offset, limit);
951
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
952
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime,
953
					offset, limit);
954
		} else {
23202 ashik.ali 955
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
956
		}
957
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 958
 
23202 ashik.ali 959
		map.put("saleHistories", fofoOrders);
960
		return map;
961
	}
23650 amit.gupta 962
 
963
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
23202 ashik.ali 964
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 965
		return fofoStore.getCode();
23202 ashik.ali 966
	}
23650 amit.gupta 967
 
968
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId) {
23191 ashik.ali 969
		CustomerAddress customerAddress = null;
23650 amit.gupta 970
		try {
971
			// CustomAddress customAddress = customCustomer.getAddress();
972
			customerAddress = customerAddressRepository.selectByParams(customAddress.getName(),
973
					customAddress.getLine1(), customAddress.getLine2(), customAddress.getLandmark(),
974
					customAddress.getCity(), customAddress.getPinCode(), customAddress.getState(),
975
					customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
976
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 977
			LOGGER.warn("Customer address not found with [{}]", customAddress);
23191 ashik.ali 978
			customerAddress = new CustomerAddress();
979
			this.setCustomerAddress(customerAddress, customAddress);
980
			customerAddress.setCustomerId(customerId);
981
		}
982
		customerAddressRepository.persist(customerAddress);
983
		return customerAddress;
984
	}
23650 amit.gupta 985
 
986
	private String getValidName(String name) {
987
		return name != null ? name : "";
22859 ashik.ali 988
	}
23650 amit.gupta 989
 
990
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
23377 ashik.ali 991
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 992
		for (FofoLineItem fofoLineItem : fofoLineItems) {
993
			if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
23377 ashik.ali 994
				serialNumbers.add(fofoLineItem.getSerialNumber());
22955 ashik.ali 995
			}
23377 ashik.ali 996
		}
997
		return serialNumbers;
22859 ashik.ali 998
	}
23650 amit.gupta 999
 
1000
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence() {
22859 ashik.ali 1001
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
23650 amit.gupta 1002
		try {
22859 ashik.ali 1003
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
1004
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
1005
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
23650 amit.gupta 1006
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 1007
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
1008
			policyNumberGenerationSequence.setSequence(1);
1009
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
1010
		}
1011
		return policyNumberGenerationSequence;
1012
	}
23650 amit.gupta 1013
 
1014
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber,
1015
			LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress,
1016
			InsurancePolicy insurancePolicy) {
22859 ashik.ali 1017
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
1018
		gadgetCopsInsuranceModel.setBrand(brand);
1019
		gadgetCopsInsuranceModel.setModelName(modelName);
1020
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
1021
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
1022
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
1023
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
1024
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
1025
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
1026
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
1027
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
1028
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
1029
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
1030
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
1031
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
1032
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
1033
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
1034
		return gadgetCopsInsuranceModel;
1035
	}
23650 amit.gupta 1036
 
1037
	private InsurancePolicy createInsurancePolicy(String invoiceNumber, int retailerId, float purchaseAmount,
1038
			float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand,
1039
			int policyNumberGenerationSequence, int insuranceProviderId, Customer customer,
1040
			LocalDate customerDateOfBirth, CustomerAddress customerAddress) {
22859 ashik.ali 1041
		InsurancePolicy insurancePolicy = new InsurancePolicy();
23394 amit.gupta 1042
		insurancePolicy.setInvoiceNumber(invoiceNumber);
22859 ashik.ali 1043
		insurancePolicy.setRetailerId(retailerId);
1044
		insurancePolicy.setPurchaseAmount(purchaseAmount);
1045
		insurancePolicy.setSaleAmount(saleAmount);
1046
		insurancePolicy.setSellingPrice(sellingPrice);
1047
		insurancePolicy.setSerialNumber(serialNumber);
1048
		insurancePolicy.setModelName(modelName);
1049
		insurancePolicy.setBrand(brand);
23650 amit.gupta 1050
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX,
1051
				policyNumberGenerationSequence));
22859 ashik.ali 1052
		insurancePolicy.setProviderId(insuranceProviderId);
1053
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
1054
		insurancePolicy.setCustomerLastName(customer.getLastName());
1055
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
1056
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
1057
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
1058
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
1059
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
1060
		insurancePolicy.setCustomerCity(customerAddress.getCity());
1061
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
1062
		insurancePolicy.setCustomerState(customerAddress.getState());
1063
		return insurancePolicy;
1064
	}
23650 amit.gupta 1065
 
1066
	private void validateInsuranceMargin(Map<String, Float> insuranceSerialNumberItemPrice,
1067
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, Map<Integer, PriceModel> itemIdMopPriceMap,
1068
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap, Map<String, Float> insuranceSerialNumberSaleAmount)
1069
			throws ProfitMandiBusinessException {
22859 ashik.ali 1070
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
23650 amit.gupta 1071
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
22872 ashik.ali 1072
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 1073
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
1074
			float itemSellingPrice = entry.getValue();
1075
			float itemMargin = itemSellingPrice - itemPurchasePrice;
1076
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
1077
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
1078
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
23650 amit.gupta 1079
			if (insuranceMargin < (itemMargin * 30 / 100)) {
22859 ashik.ali 1080
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
1081
			}
1082
		}
23650 amit.gupta 1083
		if (!invalidInsuranceMarginAmount.isEmpty()) {
1084
			LOGGER.error(
1085
					"insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}",
1086
					invalidInsuranceMarginAmount);
1087
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount,
1088
					"FFORDR_1007");
22859 ashik.ali 1089
		}
1090
	}
23650 amit.gupta 1091
 
1092
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice,
1093
			Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap)
1094
			throws ProfitMandiBusinessException {
22859 ashik.ali 1095
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
1096
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
23650 amit.gupta 1097
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
1098
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue())
1099
					.getDealerPrice()) {
1100
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(),
1101
						insuranceSerialNumberSaleAmount.get(entry.getKey()));
22859 ashik.ali 1102
			}
23650 amit.gupta 1103
 
1104
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue())
1105
					.getSellingPrice()) {
1106
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()),
1107
						insurancePricesMap.get(entry.getValue()).getDealerPrice());
22859 ashik.ali 1108
			}
1109
		}
23650 amit.gupta 1110
 
22859 ashik.ali 1111
		// insurance sale amount can not be lesser than insurance purchase amount
23650 amit.gupta 1112
		if (!invalidInsurancePurchaseSaleAmount.isEmpty()) {
1113
			LOGGER.error(
1114
					"Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount",
1115
					invalidInsurancePurchaseSaleAmount);
1116
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount",
1117
					invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 1118
		}
23650 amit.gupta 1119
 
1120
		if (!invalidInsuranceSalePurchaseAmount.isEmpty()) {
1121
			LOGGER.error(
1122
					"Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount",
1123
					invalidInsuranceSalePurchaseAmount);
1124
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount",
1125
					invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 1126
		}
1127
	}
23823 amit.gupta 1128
	private void validateDpPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1129
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
1130
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoLineItemMap.entrySet()) {
1131
			int itemId = entry.getKey();
1132
			CustomFofoOrderItem customFofoOrderItem = entry.getValue();
1133
			PriceModel priceModel = itemIdMopPriceMap.get(itemId);
1134
			if(customFofoOrderItem.getSerialNumberDetails().size() > 0) {
23857 amit.gupta 1135
				if(priceModel.getPrice() > customFofoOrderItem.getSellingPrice()) {
23823 amit.gupta 1136
					throw new ProfitMandiBusinessException("Selling Price", itemRepository.selectById(itemId).getItemDescription(), "FFORDR_1010");
1137
				}
1138
			} else {
23857 amit.gupta 1139
				if(priceModel.getPurchasePrice() > customFofoOrderItem.getSellingPrice()) {
23823 amit.gupta 1140
					throw new ProfitMandiBusinessException("Selling Price", itemRepository.selectById(itemId).getItemDescription(), "Selling Price should not be less than DP");
1141
				}
1142
			}
1143
		}
1144
	}
23650 amit.gupta 1145
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1146
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
22859 ashik.ali 1147
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
1148
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
23650 amit.gupta 1149
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
22872 ashik.ali 1150
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
23650 amit.gupta 1151
			if (entry.getValue().getPrice() < Float.MAX_VALUE
1152
					&& customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
22872 ashik.ali 1153
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 1154
			}
23650 amit.gupta 1155
			if (entry.getValue().isMop()
1156
					&& customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()) {
22872 ashik.ali 1157
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
1158
			}
22859 ashik.ali 1159
		}
23650 amit.gupta 1160
 
1161
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1162
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
1163
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 1164
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 1165
		}
23650 amit.gupta 1166
 
23857 amit.gupta 1167
		if (!invalidDiscountAmountMap.isEmpty()) {
23650 amit.gupta 1168
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}",
1169
					invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 1170
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 1171
		}
1172
	}
23650 amit.gupta 1173
 
1174
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString)
1175
			throws ProfitMandiBusinessException {
22859 ashik.ali 1176
		LocalDate customerDateOfBirth = null;
23650 amit.gupta 1177
		try {
22859 ashik.ali 1178
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
23650 amit.gupta 1179
		} catch (DateTimeException dateTimeException) {
23596 ashik.ali 1180
			LOGGER.error("Unable to parse dateOfBirth message {}", dateTimeException.getMessage());
22925 ashik.ali 1181
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 1182
		}
1183
		return customerDateOfBirth;
1184
	}
23650 amit.gupta 1185
 
1186
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
1187
			Map<Integer, Integer> inventoryItemQuantityUsed) {
1188
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1189
			inventoryItem.setLastScanType(ScanType.SALE);
1190
			inventoryItemRepository.persist(inventoryItem);
1191
			ScanRecord scanRecord = new ScanRecord();
1192
			scanRecord.setInventoryItemId(inventoryItem.getId());
1193
			scanRecord.setFofoId(fofoId);
23650 amit.gupta 1194
			// correct this
22859 ashik.ali 1195
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1196
			scanRecord.setType(ScanType.SALE);
1197
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1198
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1199
 
22859 ashik.ali 1200
		}
1201
	}
23650 amit.gupta 1202
 
1203
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1204
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1205
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1206
			FofoLineItem fofoLineItem = new FofoLineItem();
1207
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1208
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1209
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1210
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1211
			fofoLineItemRepository.persist(fofoLineItem);
1212
		}
1213
	}
23650 amit.gupta 1214
 
1215
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1216
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1217
			throws ProfitMandiBusinessException {
22859 ashik.ali 1218
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1219
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1220
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1221
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1222
		fofoOrderItem.setOrderId(fofoOrderId);
1223
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1224
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
1225
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1226
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1227
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1228
		if (stateId != null) {
23172 ashik.ali 1229
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1230
		} else {
23172 ashik.ali 1231
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1232
		}
23393 amit.gupta 1233
		float cost = 0;
23650 amit.gupta 1234
		for (InventoryItem inventoryItem : inventoryItems) {
1235
			if (stateId == null) {
23172 ashik.ali 1236
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1237
			} else {
23172 ashik.ali 1238
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1239
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1240
			}
23650 amit.gupta 1241
 
22859 ashik.ali 1242
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1243
			break;
1244
		}
23650 amit.gupta 1245
		for (InventoryItem inventoryItem : inventoryItems) {
1246
			if (inventoryItem.getSerialNumber() != null) {
23393 amit.gupta 1247
				cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
1248
			} else {
1249
				cost += inventoryItem.getUnitPrice();
23382 amit.gupta 1250
			}
1251
		}
23650 amit.gupta 1252
		cost = cost / customFofoOrderItem.getQuantity();
23382 amit.gupta 1253
		fofoOrderItem.setCost(cost);
22859 ashik.ali 1254
		fofoOrderItem.setBrand(item.getBrand());
1255
		fofoOrderItem.setModelName(item.getModelName());
1256
		fofoOrderItem.setModelNumber(item.getModelNumber());
1257
		fofoOrderItem.setColor(item.getColor());
1258
		fofoOrderItemRepository.persist(fofoOrderItem);
1259
		return fofoOrderItem;
1260
	}
23650 amit.gupta 1261
 
1262
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1263
			int itemId, int quantity) throws ProfitMandiBusinessException {
1264
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1265
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1266
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1267
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1268
			}
1269
		}
1270
	}
23650 amit.gupta 1271
 
1272
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1273
			throws ProfitMandiBusinessException {
1274
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1275
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1276
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1277
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1278
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1279
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1280
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1281
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1282
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1283
			}
22859 ashik.ali 1284
		}
1285
	}
23650 amit.gupta 1286
 
1287
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId,
1288
			InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId) {
22859 ashik.ali 1289
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1290
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1291
		fofoOrder.setCustomerId(customerId);
1292
		fofoOrder.setFofoId(fofoId);
23650 amit.gupta 1293
		fofoOrder.setInvoiceNumber(
1294
				invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
22859 ashik.ali 1295
		fofoOrder.setTotalAmount(totalAmount);
1296
		fofoOrder.setCustomerAddressId(customerAddressId);
1297
		fofoOrderRepository.persist(fofoOrder);
1298
		return fofoOrder;
1299
	}
23650 amit.gupta 1300
 
1301
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException {
22859 ashik.ali 1302
		Customer customer = null;
23650 amit.gupta 1303
		try {
22859 ashik.ali 1304
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
23650 amit.gupta 1305
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 1306
			LOGGER.error("Customer not found with mobileNumber [{}]", customCustomer.getMobileNumber());
22859 ashik.ali 1307
			customer = new Customer();
1308
		}
23190 ashik.ali 1309
		customer.setFirstName(customCustomer.getFirstName());
1310
		customer.setLastName(customCustomer.getLastName());
1311
		customer.setEmailId(customCustomer.getEmailId());
1312
		customer.setMobileNumber(customCustomer.getMobileNumber());
1313
		customerRepository.persist(customer);
22859 ashik.ali 1314
		return customer;
1315
	}
23650 amit.gupta 1316
 
1317
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId,
1318
			String fofoStoreCode) {
22859 ashik.ali 1319
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
23650 amit.gupta 1320
		try {
22859 ashik.ali 1321
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1322
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
23650 amit.gupta 1323
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 1324
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1325
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23370 ashik.ali 1326
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
22859 ashik.ali 1327
			invoiceNumberGenerationSequence.setSequence(1);
1328
		}
1329
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1330
		return invoiceNumberGenerationSequence;
1331
	}
23650 amit.gupta 1332
 
1333
	private void validateItemsSerializedNonSerialized(List<Item> items,
1334
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1335
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1336
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1337
		for (Item i : items) {
22872 ashik.ali 1338
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1339
			if (i.getType().equals(ItemType.SERIALIZED)) {
1340
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1341
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1342
				}
23650 amit.gupta 1343
			} else {
1344
				Set<String> serialNumbers = this
1345
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1346
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1347
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1348
				}
1349
			}
1350
		}
1351
 
23650 amit.gupta 1352
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1353
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1354
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1355
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1356
					"FFORDR_1013");
22859 ashik.ali 1357
		}
1358
 
23650 amit.gupta 1359
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1360
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1361
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1362
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1363
					"FFORDR_1014");
22859 ashik.ali 1364
		}
1365
	}
23650 amit.gupta 1366
 
1367
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1368
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1369
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1370
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1371
		}
23650 amit.gupta 1372
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1373
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1374
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1375
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1376
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1377
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1378
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1379
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1380
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1381
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1382
				Quantity quantity = new Quantity();
1383
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1384
				quantity.setRequested(customFofoOrderItem.getQuantity());
1385
				itemIdQuantityAvailability.setQuantity(quantity);
1386
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1387
			}
22859 ashik.ali 1388
		}
1389
 
23650 amit.gupta 1390
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1391
			// itemIdQuantity request is not valid
23650 amit.gupta 1392
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1393
					itemIdQuantityAvailabilities);
1394
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1395
					"FFORDR_1015");
22859 ashik.ali 1396
		}
1397
	}
23650 amit.gupta 1398
 
1399
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1400
			String serialNumber) {
22872 ashik.ali 1401
		int itemId = 0;
23650 amit.gupta 1402
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1403
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1404
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1405
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1406
					itemId = entry.getKey();
1407
					break;
1408
				}
22859 ashik.ali 1409
			}
1410
		}
22872 ashik.ali 1411
		return itemId;
22859 ashik.ali 1412
	}
23650 amit.gupta 1413
 
1414
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1415
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1416
			@Override
1417
			public Integer apply(Item item) {
1418
				return item.getId();
1419
			}
1420
		};
1421
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1422
			@Override
1423
			public Item apply(Item item) {
1424
				return item;
1425
			}
1426
		};
1427
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1428
	}
1429
 
23650 amit.gupta 1430
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1431
		customerAddress.setName(customAddress.getName());
1432
		customerAddress.setLine1(customAddress.getLine1());
1433
		customerAddress.setLine2(customAddress.getLine2());
1434
		customerAddress.setLandmark(customAddress.getLandmark());
1435
		customerAddress.setCity(customAddress.getCity());
1436
		customerAddress.setPinCode(customAddress.getPinCode());
1437
		customerAddress.setState(customAddress.getState());
1438
		customerAddress.setCountry(customAddress.getCountry());
1439
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1440
	}
1441
 
23650 amit.gupta 1442
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1443
		CustomAddress customAddress = new CustomAddress();
1444
		customAddress.setName(address.getName());
1445
		customAddress.setLine1(address.getLine1());
1446
		customAddress.setLine2(address.getLine2());
1447
		customAddress.setLandmark(address.getLandmark());
1448
		customAddress.setCity(address.getCity());
1449
		customAddress.setPinCode(address.getPinCode());
1450
		customAddress.setState(address.getState());
1451
		customAddress.setCountry(address.getCountry());
1452
		customAddress.setPhoneNumber(address.getPhoneNumber());
1453
		return customAddress;
1454
	}
1455
 
23650 amit.gupta 1456
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1457
		CustomAddress customAddress = new CustomAddress();
1458
		customAddress.setName(customerAddress.getName());
1459
		customAddress.setLine1(customerAddress.getLine1());
1460
		customAddress.setLine2(customerAddress.getLine2());
1461
		customAddress.setLandmark(customerAddress.getLandmark());
1462
		customAddress.setCity(customerAddress.getCity());
1463
		customAddress.setPinCode(customerAddress.getPinCode());
1464
		customAddress.setState(customerAddress.getState());
1465
		customAddress.setCountry(customerAddress.getCountry());
1466
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1467
		return customAddress;
1468
	}
1469
 
23650 amit.gupta 1470
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1471
			throws ProfitMandiBusinessException {
23365 ashik.ali 1472
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1473
 
22859 ashik.ali 1474
		float calculatedAmount = 0;
23650 amit.gupta 1475
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1476
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1477
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1478
		}
23650 amit.gupta 1479
		if (calculatedAmount != totalAmount) {
1480
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
1481
					calculatedAmount, totalAmount);
1482
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1483
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1484
		}
23650 amit.gupta 1485
 
23365 ashik.ali 1486
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1487
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1488
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1489
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1490
					"FFORDR_1017");
23365 ashik.ali 1491
		}
22859 ashik.ali 1492
	}
23650 amit.gupta 1493
 
22925 ashik.ali 1494
	@Override
1495
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1496
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1497
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1498
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1499
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1500
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1501
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1502
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1503
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1504
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1505
				newFofoOrderItems.add(fofoOrderItem);
1506
				fofoOrderItemsIterator.remove();
1507
			}
1508
			fofoOrderItems = newFofoOrderItems;
1509
		}
1510
		return fofoOrderItems;
1511
	}
23650 amit.gupta 1512
 
1513
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1514
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1515
			@Override
1516
			public Integer apply(FofoOrderItem fofoOrderItem) {
1517
				return fofoOrderItem.getId();
1518
			}
1519
		};
1520
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1521
	}
23650 amit.gupta 1522
 
1523
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1524
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1525
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1526
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1527
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1528
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1529
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1530
				fofoLineItems2.add(fofoLineItem);
1531
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1532
			} else {
22925 ashik.ali 1533
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1534
			}
1535
		}
1536
		return fofoOrderItemIdFofoLineItemsMap;
1537
	}
23650 amit.gupta 1538
 
1539
	private String getOtpString() {
23418 ashik.ali 1540
		Random rndm_method = new Random();
23650 amit.gupta 1541
		String numbers = "0123456789";
23418 ashik.ali 1542
		char[] otp = new char[5];
22859 ashik.ali 1543
 
23650 amit.gupta 1544
		for (int i = 0; i < 5; i++) {
23418 ashik.ali 1545
			otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
1546
		}
1547
		return String.valueOf(otp);
1548
	}
23650 amit.gupta 1549
 
1550
	private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount) {
1551
		Map<Integer, String> itemIdDescriptionMap = inventoryService
1552
				.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());
23418 ashik.ali 1553
		StringBuilder itemIdAdvanceAmountString = new StringBuilder();
1554
		int index = 0;
23650 amit.gupta 1555
		for (Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {
23418 ashik.ali 1556
			itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));
1557
			itemIdAdvanceAmountString.append("'s Advance amount [");
1558
			itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());
1559
			itemIdAdvanceAmountString.append("]");
23650 amit.gupta 1560
			if (index + 1 < itemIdAdvanceAmount.size()) {
23418 ashik.ali 1561
				itemIdAdvanceAmountString.append(", ");
1562
			}
1563
			index++;
1564
		}
1565
		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 1566
		LOGGER.info("OTP to Customer Successfully sends" + text);
23418 ashik.ali 1567
		String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);
1568
		try {
1569
			Utils.sendSms(msg, phone);
1570
		} catch (URISyntaxException e) {
1571
			// TODO Auto-generated catch block
1572
			e.printStackTrace();
1573
		} catch (IOException e) {
1574
			// TODO Auto-generated catch block
1575
			e.printStackTrace();
1576
		}
23650 amit.gupta 1577
 
23418 ashik.ali 1578
	}
23650 amit.gupta 1579
 
23418 ashik.ali 1580
	@Override
23650 amit.gupta 1581
	public int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber,
1582
			Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {
1583
		if (!StringUtils.isValidEmailAddress(customerEmailId)) {
23418 ashik.ali 1584
			LOGGER.error("invalid customer emailId {} ", customerEmailId);
1585
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");
1586
		}
1587
 
23650 amit.gupta 1588
		if (!StringUtils.isValidMobile(customerMobileNumber)) {
23418 ashik.ali 1589
			LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);
1590
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");
1591
		}
23650 amit.gupta 1592
 
23418 ashik.ali 1593
		List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);
1594
		String otp = null;
23650 amit.gupta 1595
		if (otps.size() >= 5) {
1596
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId,
1597
					"FFORDR_1019");
23418 ashik.ali 1598
		}
23650 amit.gupta 1599
		if (!otps.isEmpty()) {
1600
			if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))) {
23418 ashik.ali 1601
				return otps.get(0).getId();
23650 amit.gupta 1602
			} else if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))) {
23418 ashik.ali 1603
				otp = otps.get(0).getOtp();
1604
			}
1605
		}
23650 amit.gupta 1606
		if (otp == null || otp.isEmpty()) {
23418 ashik.ali 1607
			otp = getOtpString();
1608
		}
23650 amit.gupta 1609
 
23418 ashik.ali 1610
		this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);
23650 amit.gupta 1611
 
23418 ashik.ali 1612
		Otp otp_bean = new Otp();
1613
		otp_bean.setEmail(customerEmailId);
1614
		otp_bean.setMobile(customerMobileNumber);
1615
		otp_bean.setOtp(otp);
1616
		otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);
1617
		otp_bean.setCreatedOn(LocalDateTime.now());
1618
		otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
1619
		otpRepository.persist(otp_bean);
23650 amit.gupta 1620
 
23418 ashik.ali 1621
		return otp_bean.getId();
1622
	}
23650 amit.gupta 1623
 
23418 ashik.ali 1624
	@Override
1625
	public String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)
1626
			throws ProfitMandiBusinessException {
1627
		Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);
1628
		otp.setTryCount(otp.getTryCount() + 1);
23650 amit.gupta 1629
		if (!otp.getOtp().equalsIgnoreCase(otpValue)) {
23418 ashik.ali 1630
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");
1631
		}
23650 amit.gupta 1632
		if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
23418 ashik.ali 1633
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");
1634
		}
23650 amit.gupta 1635
		if (otp.getTryCount() > 5) {
23418 ashik.ali 1636
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");
1637
		}
1638
		otp.setExpired(true);
1639
		otp.setVerified(true);
1640
		otpRepository.persist(otp);
23650 amit.gupta 1641
 
23418 ashik.ali 1642
		return ResponseCodeHolder.getMessage("FFORDR_OK_1002");
1643
	}
23650 amit.gupta 1644
 
23582 ashik.ali 1645
	@Override
23650 amit.gupta 1646
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1647
			throws ProfitMandiBusinessException {
23582 ashik.ali 1648
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1649
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1650
		customer.setFirstName(customCustomer.getFirstName());
1651
		customer.setLastName(customCustomer.getLastName());
1652
		customerRepository.persist(customer);
1653
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1654
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1655
		customerAddressRepository.persist(customerAddress);
1656
	}
23418 ashik.ali 1657
 
23638 amit.gupta 1658
	@Override
23655 amit.gupta 1659
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest) throws ProfitMandiBusinessException {
1660
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1661
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1662
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1663
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1664
		}
23655 amit.gupta 1665
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
1666
		if(foiBadReturnRequest.getMarkedBadArr().size() > billedQty ) {
1667
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1668
		}
23650 amit.gupta 1669
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1670
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1671
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1672
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1673
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
1674
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1675
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1676
			customerReturnItem.setQuantity(1);
1677
			customerReturnItem.setType(ReturnType.BAD);
1678
			//customerReturnItemRepository.persist(customerReturnItem);
1679
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1680
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1681
		}
23655 amit.gupta 1682
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
1683
		for (CustomerReturnItem customerReturnItem: customerReturnItems) {
1684
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(), ReturnType.BAD);
1685
		}
1686
        return creditNote;
23638 amit.gupta 1687
	}
1688
 
23655 amit.gupta 1689
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems) throws ProfitMandiBusinessException {
23650 amit.gupta 1690
 
23638 amit.gupta 1691
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1692
				.selectByFofoId(fofoOrder.getFofoId());
1693
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1694
		invoiceNumberGenerationSequenceRepository.persist(sequence);
23650 amit.gupta 1695
 
23655 amit.gupta 1696
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1697
		CustomerCreditNote creditNote = new CustomerCreditNote();
1698
		creditNote.setCreditNoteNumber(creditNoteNumber);
1699
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1700
		creditNote.setFofoOrderId(fofoOrder.getId());
1701
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1702
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1703
		customerCreditNoteRepository.persist(creditNote);
1704
 
1705
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1706
			customerReturnItem.setCreditNoteId(creditNote.getId());
1707
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1708
		}
23650 amit.gupta 1709
		//this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1710
 
23655 amit.gupta 1711
		return creditNote;
23650 amit.gupta 1712
	}
1713
 
23655 amit.gupta 1714
	@Override
1715
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1716
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1717
		return getCreditNotePdfModel(creditNote);
1718
	}
1719
 
1720
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote) throws ProfitMandiBusinessException {
1721
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
1722
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository.selectAllByCreditNoteId(creditNote.getId());
1723
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
1724
 
1725
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
1726
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoOrder.getFofoId())).get(fofoOrder.getFofoId());
1727
 
1728
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1729
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1730
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1731
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1732
 
1733
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1734
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1735
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1736
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
1737
 
1738
		if(ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())){
1739
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1740
					.collect(Collectors.toSet());
1741
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1742
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1743
			customFofoOrderItem.setDescription(
1744
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1745
		}
1746
 
1747
		customFofoOrderItem.setRate(taxableSellingPrice);
1748
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1749
		customFofoOrderItem.setQuantity(customerReturnItems.size());
1750
		customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
1751
 
1752
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1753
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1754
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1755
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1756
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1757
		customFofoOrderItem.setIgstAmount(igstAmount);
1758
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1759
		customFofoOrderItem.setCgstAmount(cgstAmount);
1760
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1761
		customFofoOrderItem.setSgstAmount(sgstAmount);
1762
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1763
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1764
		customerFofoOrderItems.add(customFofoOrderItem);
1765
 
23650 amit.gupta 1766
		PdfModel pdfModel = new PdfModel();
1767
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1768
		pdfModel.setCustomer(customCustomer);
1769
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1770
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1771
		pdfModel.setTitle("Credit Note");
1772
		pdfModel.setRetailer(customRetailer);
1773
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1774
		pdfModel.setOrderItems(customerFofoOrderItems);
1775
 
23650 amit.gupta 1776
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1777
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1778
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1779
		creditNotePdfModel.setPdfModel(pdfModel);
1780
		return creditNotePdfModel;
1781
	}
23638 amit.gupta 1782
 
22859 ashik.ali 1783
}