Subversion Repositories SmartDukaan

Rev

Rev 23721 | Rev 23823 | 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
249
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) 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);
476
 
22872 ashik.ali 477
		this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
23650 amit.gupta 478
 
23202 ashik.ali 479
		String fofoStoreCode = this.getFofoStoreCode(fofoId);
22859 ashik.ali 480
 
23650 amit.gupta 481
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this
482
				.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);
483
 
22859 ashik.ali 484
		Customer customer = this.createAndGetCustomer(customCustomer);
23650 amit.gupta 485
 
23191 ashik.ali 486
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());
23650 amit.gupta 487
 
488
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId,
489
				invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
490
 
23612 amit.gupta 491
		this.createPaymentOptions(fofoOrder, createOrderRequest.getPaymentOptions());
23650 amit.gupta 492
 
493
		this.processPrebookingOrders(fofoId, fofoOrder.getId(), prebookingOrders, prebookingOrderItemIdQuantityMap,
494
				itemIdPrebookingListingMap);
495
 
23172 ashik.ali 496
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
23650 amit.gupta 497
 
23172 ashik.ali 498
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
23650 amit.gupta 499
 
23172 ashik.ali 500
		Integer stateId = null;
23650 amit.gupta 501
		if (customerAddress.getState().equals(retailerAddress.getState())) {
502
			try {
23172 ashik.ali 503
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
23650 amit.gupta 504
			} catch (Exception e) {
23172 ashik.ali 505
				LOGGER.error("Unable to get state rates");
506
			}
507
		}
23650 amit.gupta 508
 
509
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
510
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(),
511
					itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), stateId);
512
 
22859 ashik.ali 513
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
23650 amit.gupta 514
 
22859 ashik.ali 515
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
23650 amit.gupta 516
 
517
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(),
518
					customFofoOrderItem.getQuantity());
519
 
22859 ashik.ali 520
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
521
		}
23650 amit.gupta 522
 
22859 ashik.ali 523
		// insurance calculation is insurance flag is enabled
23650 amit.gupta 524
		if (!insuranceSerialNumberItemPrice.isEmpty()) {
22859 ashik.ali 525
			LOGGER.info("Processing for insurence for serialNumbers");
23650 amit.gupta 526
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(
527
					new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
528
			InsuranceProvider insuranceProvider = insuranceProviderRepository
529
					.selectByName(ProfitMandiConstants.GADGET_COPS);
530
 
531
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount,
532
					insurancePricesMap);
533
 
534
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap,
535
					itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
536
 
537
			LocalDate customerDateOfBirth = this
538
					.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
539
 
540
			for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
541
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this
542
						.createPolicyNumberGenerationSequence();
543
 
544
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(fofoOrder.getInvoiceNumber(), fofoId,
22859 ashik.ali 545
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
23650 amit.gupta 546
						insuranceSerialNumberSaleAmount.get(entry.getKey()), entry.getValue(), entry.getKey(),
547
						serialNumberModelName.get(entry.getKey()), serialNumberBrand.get(entry.getKey()),
548
						policyNumberGenerationSequence.getSequence(), insuranceProvider.getId(), customer,
549
						customerDateOfBirth, customerAddress);
550
 
551
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(
552
						serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()),
553
						entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
554
				String walletDescription = "Sale of " + insurancePolicy.getPolicyNumber() + " for "
555
						+ fofoOrder.getInvoiceNumber();
556
				walletService.consumeAmountFromWallet(fofoId, insurancePolicy.getId(),
23395 amit.gupta 557
						WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getPurchaseAmount());
23650 amit.gupta 558
 
559
				try {
22859 ashik.ali 560
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
561
					insurancePolicy.setPosted(true);
23650 amit.gupta 562
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
563
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(),
564
							profitMandiBusinessException);
22859 ashik.ali 565
				}
566
				insurancePolicyRepository.persist(insurancePolicy);
567
			}
568
		}
23365 ashik.ali 569
		schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
23650 amit.gupta 570
 
22859 ashik.ali 571
		return fofoOrder.getId();
572
	}
23650 amit.gupta 573
 
574
	private float calculatePrebookingOrdersAmount(List<PrebookingOrder> prebookingOrders,
575
			Map<Integer, Integer> prebookingOrderItemIdQuantityMap,
576
			Map<Integer, PrebookingListing> itemIdPrebookingListingMap) {
577
		// List<PrebookingOrder> prebookingOrders =
578
		// prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId,
579
		// customerMobileNumber, prebookingOrderItemIdQuantityMap.keySet());
23418 ashik.ali 580
		float totalAmount = 0;
23650 amit.gupta 581
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
23418 ashik.ali 582
			int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
583
			PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
23650 amit.gupta 584
			if (requestedQuantity < prebookingOrder.getAvailableQuantity()) {
585
				LOGGER.info("when requestedQuantity < then requestedQuantity [{}] * advanceAmount [{}]",
586
						requestedQuantity, prebookingListing.getAdvanceAmount());
23418 ashik.ali 587
				totalAmount = totalAmount + (requestedQuantity * prebookingListing.getAdvanceAmount());
23650 amit.gupta 588
			} else if (requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
589
				LOGGER.info("else requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity,
590
						prebookingListing.getAdvanceAmount());
591
				totalAmount = totalAmount
592
						+ (prebookingOrder.getAvailableQuantity() * prebookingListing.getAdvanceAmount());
23418 ashik.ali 593
			}
594
		}
595
		return totalAmount;
596
	}
23650 amit.gupta 597
 
598
	private void processPrebookingOrders(int fofoId, int orderId, List<PrebookingOrder> prebookingOrders,
599
			Map<Integer, Integer> prebookingOrderItemIdQuantityMap,
600
			Map<Integer, PrebookingListing> itemIdPrebookingListingMap) throws ProfitMandiBusinessException {
601
		// Map<Integer, PrebookingOrder> prebookingOrderIdPrebookingOrderMap =
602
		// this.prebookingOrdersToPrebookingOrderIdPrebookingOrderMap(prebookingOrders);
603
 
604
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
605
			if (prebookingOrder.getCompleteTimestamp() == null) {
23418 ashik.ali 606
				int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
23650 amit.gupta 607
 
23418 ashik.ali 608
				PrebookingOrderItem prebookingOrderItem = new PrebookingOrderItem();
23650 amit.gupta 609
				if (requestedQuantity < prebookingOrder.getAvailableQuantity()) {
23418 ashik.ali 610
					prebookingOrder.setAvailableQuantity(prebookingOrder.getAvailableQuantity() - requestedQuantity);
611
					prebookingOrderItem.setQuantity(requestedQuantity);
23650 amit.gupta 612
				} else if (requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
23418 ashik.ali 613
					prebookingOrderItem.setQuantity(prebookingOrder.getAvailableQuantity());
614
					prebookingOrder.setAvailableQuantity(0);
615
				}
23650 amit.gupta 616
				if (prebookingOrder.getAvailableQuantity() == 0) {
23418 ashik.ali 617
					prebookingOrder.setCompleteTimestamp(LocalDateTime.now());
618
				}
619
				prebookingOrderRepository.persist(prebookingOrder);
23650 amit.gupta 620
 
23418 ashik.ali 621
				prebookingOrderItem.setOrderId(orderId);
622
				prebookingOrderItem.setItemId(prebookingOrder.getItemId());
623
				PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
624
				prebookingOrderItem.setAdvanceAmount(prebookingListing.getAdvanceAmount());
23650 amit.gupta 625
 
23418 ashik.ali 626
				prebookingOrderItemRepository.persist(prebookingOrderItem);
23650 amit.gupta 627
 
628
				walletService.addAmountToWallet(fofoId, prebookingOrder.getId(), WalletReferenceType.PREBOOKING_ORDER,
629
						"Advance Amount credited for Prebooking Order", prebookingListing.getAdvanceAmount());
23418 ashik.ali 630
			}
23650 amit.gupta 631
 
23418 ashik.ali 632
		}
633
	}
23650 amit.gupta 634
 
635
	private Map<Integer, PrebookingListing> prebookingListingsToItemIdPrebookingListingMap(
636
			List<PrebookingListing> prebookingListings) {
23418 ashik.ali 637
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
23650 amit.gupta 638
		for (PrebookingListing prebookingListing : prebookingListings) {
23418 ashik.ali 639
			itemIdPrebookingListingMap.put(prebookingListing.getItemId(), prebookingListing);
640
		}
641
		return itemIdPrebookingListingMap;
642
	}
23650 amit.gupta 643
 
644
	private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails) {
23377 ashik.ali 645
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 646
		for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
647
			if (serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
23377 ashik.ali 648
				serialNumbers.add(serialNumberDetail.getSerialNumber());
649
			}
650
		}
651
		return serialNumbers;
652
	}
23650 amit.gupta 653
 
22859 ashik.ali 654
	@Override
23596 ashik.ali 655
	public PdfModel getInvoicePdfModel(int orderId) throws ProfitMandiBusinessException {
656
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
657
		return this.getInvoicePdfModel(fofoOrder);
658
	}
23650 amit.gupta 659
 
660
	private PdfModel getInvoicePdfModel(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
661
 
662
		List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
663
				.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
664
 
23552 amit.gupta 665
		List<CustomPaymentOption> paymentOptions = new ArrayList<>();
666
 
22859 ashik.ali 667
		PdfModel pdfModel = new PdfModel();
23650 amit.gupta 668
 
669
		for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
23552 amit.gupta 670
			CustomPaymentOption cpi = new CustomPaymentOption();
671
			cpi.setAmount(paymentOptionTransaction.getAmount());
23650 amit.gupta 672
			cpi.setPaymentOption(
673
					paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());
23558 amit.gupta 674
			paymentOptions.add(cpi);
23552 amit.gupta 675
		}
676
		pdfModel.setPaymentOptions(paymentOptions);
22859 ashik.ali 677
		pdfModel.setAuther("profitmandi");
678
		pdfModel.setTitle("Retailer Invoice");
679
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
23650 amit.gupta 680
 
22859 ashik.ali 681
		// insurance calculation
23650 amit.gupta 682
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository
683
				.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
22859 ashik.ali 684
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
685
		final float totalInsuranceTaxRate = 18;
23650 amit.gupta 686
		for (InsurancePolicy insurancePolicy : insurancePolicies) {
22859 ashik.ali 687
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
688
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
23650 amit.gupta 689
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #"
690
					+ insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
22859 ashik.ali 691
			customInsurancePolicy.setHsnCode("998716");
692
			customInsurancePolicy.setRate(taxableInsurancePrice);
693
			customInsurancePolicy.setIgstRate(18);
23650 amit.gupta 694
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
22936 amit.gupta 695
			customInsurancePolicy.setCgstRate(9);
23650 amit.gupta 696
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
22859 ashik.ali 697
			customInsurancePolicy.setSgstRate(9);
23650 amit.gupta 698
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
22859 ashik.ali 699
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
700
			customInsurancePolicies.add(customInsurancePolicy);
701
		}
702
		pdfModel.setInsurancePolicies(customInsurancePolicies);
23001 amit.gupta 703
		List<String> tncs = new ArrayList<>();
704
		tncs.add("I agree that goods received are in good working condition");
705
		tncs.add("Goods once sold cannot be exchanged or taken back");
706
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
23650 amit.gupta 707
		if (pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
708
			tncs.add("Damage protection provided is the responisibility of Protection Provider only");
709
		}
23001 amit.gupta 710
		pdfModel.setTncs(tncs);
23655 amit.gupta 711
 
712
		pdfModel.setCustomer(getCustomCustomer(fofoOrder));
22859 ashik.ali 713
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
714
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
23650 amit.gupta 715
 
23596 ashik.ali 716
		Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
22859 ashik.ali 717
		PrivateDealUser privateDealUser = null;
23650 amit.gupta 718
		try {
22859 ashik.ali 719
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23650 amit.gupta 720
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 721
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
722
		}
23650 amit.gupta 723
 
22859 ashik.ali 724
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
725
		CustomRetailer customRetailer = new CustomRetailer();
726
		customRetailer.setBusinessName(retailer.getName());
727
		customRetailer.setMobileNumber(user.getMobileNumber());
23650 amit.gupta 728
		// customRetailer.setTinNumber(retailer.getNumber());
729
		if (privateDealUser == null) {
22859 ashik.ali 730
			customRetailer.setGstNumber(null);
23650 amit.gupta 731
		} else {
732
			if (null != privateDealUser.getCounterId()) {
22859 ashik.ali 733
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
734
				customRetailer.setGstNumber(counter.getGstin());
23650 amit.gupta 735
			} else {
22859 ashik.ali 736
				customRetailer.setGstNumber(null);
737
			}
738
		}
23650 amit.gupta 739
		Address retailerAddress = addressRepository
740
				.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
22859 ashik.ali 741
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
742
		pdfModel.setRetailer(customRetailer);
22925 ashik.ali 743
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
23650 amit.gupta 744
 
22859 ashik.ali 745
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
23650 amit.gupta 746
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
22859 ashik.ali 747
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
23650 amit.gupta 748
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate()
749
					+ fofoOrderItem.getCgstRate();
22859 ashik.ali 750
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
751
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
23650 amit.gupta 752
 
22859 ashik.ali 753
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
23650 amit.gupta 754
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
755
					+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
23377 ashik.ali 756
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
23650 amit.gupta 757
			// LOGGER.info("serialNumbers {}", serialNumbers);
758
			// LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
759
			if (!serialNumbers.isEmpty()) {
760
				customFofoOrderItem.setDescription(
761
						customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
23377 ashik.ali 762
			}
22859 ashik.ali 763
			customFofoOrderItem.setRate(taxableSellingPrice);
764
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
765
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
23650 amit.gupta 766
			customFofoOrderItem.setNetAmount(
767
					(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
22859 ashik.ali 768
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
769
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
770
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
771
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
772
			customFofoOrderItem.setIgstAmount(igstAmount);
773
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
774
			customFofoOrderItem.setCgstAmount(cgstAmount);
775
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
776
			customFofoOrderItem.setSgstAmount(sgstAmount);
777
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
778
			customerFofoOrderItems.add(customFofoOrderItem);
779
		}
780
		pdfModel.setOrderItems(customerFofoOrderItems);
781
		return pdfModel;
23650 amit.gupta 782
 
22859 ashik.ali 783
	}
23650 amit.gupta 784
 
23655 amit.gupta 785
	private CustomCustomer getCustomCustomer(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
786
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
787
		CustomCustomer customCustomer = new CustomCustomer();
788
		customCustomer.setFirstName(customer.getFirstName());
789
		customCustomer.setLastName(customer.getLastName());
790
		customCustomer.setEmailId(customer.getEmailId());
791
		customCustomer.setMobileNumber(customer.getMobileNumber());
792
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
793
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
794
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
795
		return customCustomer;
796
	}
797
 
23596 ashik.ali 798
	@Override
799
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
800
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
801
		return this.getInvoicePdfModel(fofoOrder);
802
	}
23650 amit.gupta 803
 
22859 ashik.ali 804
	public String getBillingAddress(CustomerAddress customerAddress) {
805
		StringBuilder address = new StringBuilder();
806
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
807
			address.append(customerAddress.getLine1());
808
			address.append(", ");
809
		}
810
 
811
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
812
			address.append(customerAddress.getLine2());
813
			address.append(", ");
814
		}
815
 
816
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
817
			address.append(customerAddress.getLandmark());
818
			address.append(", ");
819
		}
820
 
821
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
822
			address.append(customerAddress.getCity());
823
			address.append(", ");
824
		}
825
 
826
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
827
			address.append(customerAddress.getState());
828
		}
829
 
830
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
831
			address.append("- ");
832
			address.append(customerAddress.getPinCode());
833
		}
834
 
835
		return address.toString();
836
	}
23650 amit.gupta 837
 
22859 ashik.ali 838
	@Override
23650 amit.gupta 839
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException {
840
		try {
22859 ashik.ali 841
			JSONObject cartObject = new JSONObject(cartJson);
842
			Iterator<?> keys = cartObject.keys();
23650 amit.gupta 843
 
22859 ashik.ali 844
			Set<Integer> itemIds = new HashSet<>();
845
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
23650 amit.gupta 846
 
847
			while (keys.hasNext()) {
848
				String key = (String) keys.next();
849
				if (cartObject.get(key) instanceof JSONObject) {
22859 ashik.ali 850
					LOGGER.info(cartObject.get(key).toString());
851
				}
852
				CartFofo cf = new CartFofo();
853
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
854
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
23650 amit.gupta 855
 
856
				if (cf.getQuantity() <= 0) {
22859 ashik.ali 857
					continue;
858
				}
859
				cartItems.add(cf);
860
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
861
			}
23650 amit.gupta 862
			Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
863
			if (itemIds.size() > 0) {
22859 ashik.ali 864
				List<Item> items = itemRepository.selectByIds(itemIds);
23650 amit.gupta 865
				for (Item i : items) {
22859 ashik.ali 866
					itemMap.put(i.getId(), i);
867
				}
23650 amit.gupta 868
 
22859 ashik.ali 869
			}
23650 amit.gupta 870
			for (CartFofo cf : cartItems) {
22859 ashik.ali 871
				Item i = itemMap.get(cf.getItemId());
23650 amit.gupta 872
				if (i == null) {
22859 ashik.ali 873
					continue;
874
				}
23650 amit.gupta 875
				cf.setDisplayName(getValidName(i.getBrand()) + " " + getValidName(i.getModelName()) + " "
876
						+ getValidName(i.getModelNumber()) + " " + getValidName(i.getColor()).replaceAll("\\s+", " "));
22859 ashik.ali 877
				cf.setItemType(i.getType());
878
			}
879
			return cartItems;
23650 amit.gupta 880
		} catch (Exception e) {
22859 ashik.ali 881
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 882
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 883
		}
884
	}
23650 amit.gupta 885
 
23202 ashik.ali 886
	@Override
23650 amit.gupta 887
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue,
888
			String startTimeString, String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 889
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
890
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
891
		long countItems = 0;
892
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 893
 
894
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
895
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime,
896
					endDateTime, offset, limit);
897
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime,
898
					endDateTime);
899
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
900
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime,
901
					endDateTime, offset, limit);
23202 ashik.ali 902
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);
23650 amit.gupta 903
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
904
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime,
905
					endDateTime, offset, limit);
23202 ashik.ali 906
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);
23650 amit.gupta 907
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
908
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime,
909
					offset, limit);
23202 ashik.ali 910
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);
23650 amit.gupta 911
		} else {
23202 ashik.ali 912
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
23297 ashik.ali 913
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);
23202 ashik.ali 914
		}
915
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 916
 
23202 ashik.ali 917
		map.put("saleHistories", fofoOrders);
918
		map.put("start", offset + 1);
919
		map.put("size", countItems);
920
		map.put("searchType", searchType);
23351 ashik.ali 921
		map.put("searchTypes", SearchType.values());
23202 ashik.ali 922
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
923
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
23650 amit.gupta 924
		if (fofoOrders.size() < limit) {
23202 ashik.ali 925
			map.put("end", offset + fofoOrders.size());
23650 amit.gupta 926
		} else {
23202 ashik.ali 927
			map.put("end", offset + limit);
928
		}
929
		return map;
930
	}
931
 
932
	@Override
23650 amit.gupta 933
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue,
934
			String startTimeString, String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 935
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
936
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
937
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 938
 
939
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
940
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime,
941
					endDateTime, offset, limit);
942
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
943
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime,
944
					endDateTime, offset, limit);
945
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
946
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime,
947
					endDateTime, offset, limit);
948
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
949
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime,
950
					offset, limit);
951
		} else {
23202 ashik.ali 952
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
953
		}
954
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 955
 
23202 ashik.ali 956
		map.put("saleHistories", fofoOrders);
957
		return map;
958
	}
23650 amit.gupta 959
 
960
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
23202 ashik.ali 961
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 962
		return fofoStore.getCode();
23202 ashik.ali 963
	}
23650 amit.gupta 964
 
965
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId) {
23191 ashik.ali 966
		CustomerAddress customerAddress = null;
23650 amit.gupta 967
		try {
968
			// CustomAddress customAddress = customCustomer.getAddress();
969
			customerAddress = customerAddressRepository.selectByParams(customAddress.getName(),
970
					customAddress.getLine1(), customAddress.getLine2(), customAddress.getLandmark(),
971
					customAddress.getCity(), customAddress.getPinCode(), customAddress.getState(),
972
					customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
973
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 974
			LOGGER.warn("Customer address not found with [{}]", customAddress);
23191 ashik.ali 975
			customerAddress = new CustomerAddress();
976
			this.setCustomerAddress(customerAddress, customAddress);
977
			customerAddress.setCustomerId(customerId);
978
		}
979
		customerAddressRepository.persist(customerAddress);
980
		return customerAddress;
981
	}
23650 amit.gupta 982
 
983
	private String getValidName(String name) {
984
		return name != null ? name : "";
22859 ashik.ali 985
	}
23650 amit.gupta 986
 
987
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
23377 ashik.ali 988
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 989
		for (FofoLineItem fofoLineItem : fofoLineItems) {
990
			if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
23377 ashik.ali 991
				serialNumbers.add(fofoLineItem.getSerialNumber());
22955 ashik.ali 992
			}
23377 ashik.ali 993
		}
994
		return serialNumbers;
22859 ashik.ali 995
	}
23650 amit.gupta 996
 
997
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence() {
22859 ashik.ali 998
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
23650 amit.gupta 999
		try {
22859 ashik.ali 1000
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
1001
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
1002
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
23650 amit.gupta 1003
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 1004
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
1005
			policyNumberGenerationSequence.setSequence(1);
1006
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
1007
		}
1008
		return policyNumberGenerationSequence;
1009
	}
23650 amit.gupta 1010
 
1011
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber,
1012
			LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress,
1013
			InsurancePolicy insurancePolicy) {
22859 ashik.ali 1014
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
1015
		gadgetCopsInsuranceModel.setBrand(brand);
1016
		gadgetCopsInsuranceModel.setModelName(modelName);
1017
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
1018
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
1019
		gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
1020
		gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
1021
		gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
1022
		gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
1023
		gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
1024
		gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
1025
		gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
1026
		gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
1027
		gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
1028
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
1029
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
1030
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
1031
		return gadgetCopsInsuranceModel;
1032
	}
23650 amit.gupta 1033
 
1034
	private InsurancePolicy createInsurancePolicy(String invoiceNumber, int retailerId, float purchaseAmount,
1035
			float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand,
1036
			int policyNumberGenerationSequence, int insuranceProviderId, Customer customer,
1037
			LocalDate customerDateOfBirth, CustomerAddress customerAddress) {
22859 ashik.ali 1038
		InsurancePolicy insurancePolicy = new InsurancePolicy();
23394 amit.gupta 1039
		insurancePolicy.setInvoiceNumber(invoiceNumber);
22859 ashik.ali 1040
		insurancePolicy.setRetailerId(retailerId);
1041
		insurancePolicy.setPurchaseAmount(purchaseAmount);
1042
		insurancePolicy.setSaleAmount(saleAmount);
1043
		insurancePolicy.setSellingPrice(sellingPrice);
1044
		insurancePolicy.setSerialNumber(serialNumber);
1045
		insurancePolicy.setModelName(modelName);
1046
		insurancePolicy.setBrand(brand);
23650 amit.gupta 1047
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX,
1048
				policyNumberGenerationSequence));
22859 ashik.ali 1049
		insurancePolicy.setProviderId(insuranceProviderId);
1050
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
1051
		insurancePolicy.setCustomerLastName(customer.getLastName());
1052
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
1053
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
1054
		insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
1055
		insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
1056
		insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
1057
		insurancePolicy.setCustomerCity(customerAddress.getCity());
1058
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
1059
		insurancePolicy.setCustomerState(customerAddress.getState());
1060
		return insurancePolicy;
1061
	}
23650 amit.gupta 1062
 
1063
	private void validateInsuranceMargin(Map<String, Float> insuranceSerialNumberItemPrice,
1064
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, Map<Integer, PriceModel> itemIdMopPriceMap,
1065
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap, Map<String, Float> insuranceSerialNumberSaleAmount)
1066
			throws ProfitMandiBusinessException {
22859 ashik.ali 1067
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
23650 amit.gupta 1068
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
22872 ashik.ali 1069
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
22859 ashik.ali 1070
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
1071
			float itemSellingPrice = entry.getValue();
1072
			float itemMargin = itemSellingPrice - itemPurchasePrice;
1073
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
1074
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
1075
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
23650 amit.gupta 1076
			if (insuranceMargin < (itemMargin * 30 / 100)) {
22859 ashik.ali 1077
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
1078
			}
1079
		}
23650 amit.gupta 1080
		if (!invalidInsuranceMarginAmount.isEmpty()) {
1081
			LOGGER.error(
1082
					"insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}",
1083
					invalidInsuranceMarginAmount);
1084
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount,
1085
					"FFORDR_1007");
22859 ashik.ali 1086
		}
1087
	}
23650 amit.gupta 1088
 
1089
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice,
1090
			Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap)
1091
			throws ProfitMandiBusinessException {
22859 ashik.ali 1092
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
1093
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
23650 amit.gupta 1094
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
1095
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue())
1096
					.getDealerPrice()) {
1097
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(),
1098
						insuranceSerialNumberSaleAmount.get(entry.getKey()));
22859 ashik.ali 1099
			}
23650 amit.gupta 1100
 
1101
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue())
1102
					.getSellingPrice()) {
1103
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()),
1104
						insurancePricesMap.get(entry.getValue()).getDealerPrice());
22859 ashik.ali 1105
			}
1106
		}
23650 amit.gupta 1107
 
22859 ashik.ali 1108
		// insurance sale amount can not be lesser than insurance purchase amount
23650 amit.gupta 1109
		if (!invalidInsurancePurchaseSaleAmount.isEmpty()) {
1110
			LOGGER.error(
1111
					"Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount",
1112
					invalidInsurancePurchaseSaleAmount);
1113
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount",
1114
					invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
22859 ashik.ali 1115
		}
23650 amit.gupta 1116
 
1117
		if (!invalidInsuranceSalePurchaseAmount.isEmpty()) {
1118
			LOGGER.error(
1119
					"Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount",
1120
					invalidInsuranceSalePurchaseAmount);
1121
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount",
1122
					invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
22859 ashik.ali 1123
		}
1124
	}
23650 amit.gupta 1125
 
1126
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1127
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
22859 ashik.ali 1128
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
1129
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
23650 amit.gupta 1130
		// Map<Integer, PriceModel> itemIdMopPriceMap =
1131
		// pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
1132
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
22872 ashik.ali 1133
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
23650 amit.gupta 1134
			if (entry.getValue().getPrice() < Float.MAX_VALUE
1135
					&& customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
22872 ashik.ali 1136
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 1137
			}
23650 amit.gupta 1138
			if (entry.getValue().isMop()
1139
					&& customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()) {
22872 ashik.ali 1140
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
1141
			}
22859 ashik.ali 1142
		}
23650 amit.gupta 1143
 
1144
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1145
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
1146
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 1147
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 1148
		}
23650 amit.gupta 1149
 
1150
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1151
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}",
1152
					invalidDiscountAmountMap, itemIdMopPriceMap);
22925 ashik.ali 1153
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
22859 ashik.ali 1154
		}
1155
	}
23650 amit.gupta 1156
 
1157
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString)
1158
			throws ProfitMandiBusinessException {
22859 ashik.ali 1159
		LocalDate customerDateOfBirth = null;
23650 amit.gupta 1160
		try {
22859 ashik.ali 1161
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
23650 amit.gupta 1162
		} catch (DateTimeException dateTimeException) {
23596 ashik.ali 1163
			LOGGER.error("Unable to parse dateOfBirth message {}", dateTimeException.getMessage());
22925 ashik.ali 1164
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
22859 ashik.ali 1165
		}
1166
		return customerDateOfBirth;
1167
	}
23650 amit.gupta 1168
 
1169
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
1170
			Map<Integer, Integer> inventoryItemQuantityUsed) {
1171
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1172
			inventoryItem.setLastScanType(ScanType.SALE);
1173
			inventoryItemRepository.persist(inventoryItem);
1174
			ScanRecord scanRecord = new ScanRecord();
1175
			scanRecord.setInventoryItemId(inventoryItem.getId());
1176
			scanRecord.setFofoId(fofoId);
23650 amit.gupta 1177
			// correct this
22859 ashik.ali 1178
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1179
			scanRecord.setType(ScanType.SALE);
1180
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1181
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1182
 
22859 ashik.ali 1183
		}
1184
	}
23650 amit.gupta 1185
 
1186
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1187
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1188
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1189
			FofoLineItem fofoLineItem = new FofoLineItem();
1190
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1191
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1192
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1193
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1194
			fofoLineItemRepository.persist(fofoLineItem);
1195
		}
1196
	}
23650 amit.gupta 1197
 
1198
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1199
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1200
			throws ProfitMandiBusinessException {
22859 ashik.ali 1201
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1202
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1203
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1204
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1205
		fofoOrderItem.setOrderId(fofoOrderId);
1206
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1207
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
1208
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1209
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1210
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1211
		if (stateId != null) {
23172 ashik.ali 1212
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1213
		} else {
23172 ashik.ali 1214
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1215
		}
23393 amit.gupta 1216
		float cost = 0;
23650 amit.gupta 1217
		for (InventoryItem inventoryItem : inventoryItems) {
1218
			if (stateId == null) {
23172 ashik.ali 1219
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1220
			} else {
23172 ashik.ali 1221
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1222
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1223
			}
23650 amit.gupta 1224
 
22859 ashik.ali 1225
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1226
			break;
1227
		}
23650 amit.gupta 1228
		for (InventoryItem inventoryItem : inventoryItems) {
1229
			if (inventoryItem.getSerialNumber() != null) {
23393 amit.gupta 1230
				cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
1231
			} else {
1232
				cost += inventoryItem.getUnitPrice();
23382 amit.gupta 1233
			}
1234
		}
23650 amit.gupta 1235
		cost = cost / customFofoOrderItem.getQuantity();
23382 amit.gupta 1236
		fofoOrderItem.setCost(cost);
22859 ashik.ali 1237
		fofoOrderItem.setBrand(item.getBrand());
1238
		fofoOrderItem.setModelName(item.getModelName());
1239
		fofoOrderItem.setModelNumber(item.getModelNumber());
1240
		fofoOrderItem.setColor(item.getColor());
1241
		fofoOrderItemRepository.persist(fofoOrderItem);
1242
		return fofoOrderItem;
1243
	}
23650 amit.gupta 1244
 
1245
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1246
			int itemId, int quantity) throws ProfitMandiBusinessException {
1247
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1248
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1249
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1250
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1251
			}
1252
		}
1253
	}
23650 amit.gupta 1254
 
1255
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1256
			throws ProfitMandiBusinessException {
1257
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1258
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1259
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1260
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1261
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1262
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1263
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1264
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1265
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1266
			}
22859 ashik.ali 1267
		}
1268
	}
23650 amit.gupta 1269
 
1270
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId,
1271
			InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId) {
22859 ashik.ali 1272
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1273
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1274
		fofoOrder.setCustomerId(customerId);
1275
		fofoOrder.setFofoId(fofoId);
23650 amit.gupta 1276
		fofoOrder.setInvoiceNumber(
1277
				invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
22859 ashik.ali 1278
		fofoOrder.setTotalAmount(totalAmount);
1279
		fofoOrder.setCustomerAddressId(customerAddressId);
1280
		fofoOrderRepository.persist(fofoOrder);
1281
		return fofoOrder;
1282
	}
23650 amit.gupta 1283
 
1284
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException {
22859 ashik.ali 1285
		Customer customer = null;
23650 amit.gupta 1286
		try {
22859 ashik.ali 1287
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
23650 amit.gupta 1288
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 1289
			LOGGER.error("Customer not found with mobileNumber [{}]", customCustomer.getMobileNumber());
22859 ashik.ali 1290
			customer = new Customer();
1291
		}
23190 ashik.ali 1292
		customer.setFirstName(customCustomer.getFirstName());
1293
		customer.setLastName(customCustomer.getLastName());
1294
		customer.setEmailId(customCustomer.getEmailId());
1295
		customer.setMobileNumber(customCustomer.getMobileNumber());
1296
		customerRepository.persist(customer);
22859 ashik.ali 1297
		return customer;
1298
	}
23650 amit.gupta 1299
 
1300
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId,
1301
			String fofoStoreCode) {
22859 ashik.ali 1302
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
23650 amit.gupta 1303
		try {
22859 ashik.ali 1304
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1305
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
23650 amit.gupta 1306
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 1307
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1308
			invoiceNumberGenerationSequence.setFofoId(fofoId);
23370 ashik.ali 1309
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
22859 ashik.ali 1310
			invoiceNumberGenerationSequence.setSequence(1);
1311
		}
1312
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1313
		return invoiceNumberGenerationSequence;
1314
	}
23650 amit.gupta 1315
 
1316
	private void validateItemsSerializedNonSerialized(List<Item> items,
1317
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1318
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1319
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1320
		for (Item i : items) {
22872 ashik.ali 1321
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1322
			if (i.getType().equals(ItemType.SERIALIZED)) {
1323
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1324
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1325
				}
23650 amit.gupta 1326
			} else {
1327
				Set<String> serialNumbers = this
1328
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1329
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1330
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1331
				}
1332
			}
1333
		}
1334
 
23650 amit.gupta 1335
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1336
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1337
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1338
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1339
					"FFORDR_1013");
22859 ashik.ali 1340
		}
1341
 
23650 amit.gupta 1342
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1343
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1344
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1345
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1346
					"FFORDR_1014");
22859 ashik.ali 1347
		}
1348
	}
23650 amit.gupta 1349
 
1350
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1351
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1352
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1353
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1354
		}
23650 amit.gupta 1355
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1356
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1357
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1358
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1359
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1360
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1361
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1362
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1363
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1364
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1365
				Quantity quantity = new Quantity();
1366
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1367
				quantity.setRequested(customFofoOrderItem.getQuantity());
1368
				itemIdQuantityAvailability.setQuantity(quantity);
1369
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1370
			}
22859 ashik.ali 1371
		}
1372
 
23650 amit.gupta 1373
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1374
			// itemIdQuantity request is not valid
23650 amit.gupta 1375
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1376
					itemIdQuantityAvailabilities);
1377
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1378
					"FFORDR_1015");
22859 ashik.ali 1379
		}
1380
	}
23650 amit.gupta 1381
 
1382
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1383
			String serialNumber) {
22872 ashik.ali 1384
		int itemId = 0;
23650 amit.gupta 1385
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1386
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1387
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1388
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1389
					itemId = entry.getKey();
1390
					break;
1391
				}
22859 ashik.ali 1392
			}
1393
		}
22872 ashik.ali 1394
		return itemId;
22859 ashik.ali 1395
	}
23650 amit.gupta 1396
 
1397
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1398
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1399
			@Override
1400
			public Integer apply(Item item) {
1401
				return item.getId();
1402
			}
1403
		};
1404
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1405
			@Override
1406
			public Item apply(Item item) {
1407
				return item;
1408
			}
1409
		};
1410
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1411
	}
1412
 
23650 amit.gupta 1413
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1414
		customerAddress.setName(customAddress.getName());
1415
		customerAddress.setLine1(customAddress.getLine1());
1416
		customerAddress.setLine2(customAddress.getLine2());
1417
		customerAddress.setLandmark(customAddress.getLandmark());
1418
		customerAddress.setCity(customAddress.getCity());
1419
		customerAddress.setPinCode(customAddress.getPinCode());
1420
		customerAddress.setState(customAddress.getState());
1421
		customerAddress.setCountry(customAddress.getCountry());
1422
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1423
	}
1424
 
23650 amit.gupta 1425
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1426
		CustomAddress customAddress = new CustomAddress();
1427
		customAddress.setName(address.getName());
1428
		customAddress.setLine1(address.getLine1());
1429
		customAddress.setLine2(address.getLine2());
1430
		customAddress.setLandmark(address.getLandmark());
1431
		customAddress.setCity(address.getCity());
1432
		customAddress.setPinCode(address.getPinCode());
1433
		customAddress.setState(address.getState());
1434
		customAddress.setCountry(address.getCountry());
1435
		customAddress.setPhoneNumber(address.getPhoneNumber());
1436
		return customAddress;
1437
	}
1438
 
23650 amit.gupta 1439
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1440
		CustomAddress customAddress = new CustomAddress();
1441
		customAddress.setName(customerAddress.getName());
1442
		customAddress.setLine1(customerAddress.getLine1());
1443
		customAddress.setLine2(customerAddress.getLine2());
1444
		customAddress.setLandmark(customerAddress.getLandmark());
1445
		customAddress.setCity(customerAddress.getCity());
1446
		customAddress.setPinCode(customerAddress.getPinCode());
1447
		customAddress.setState(customerAddress.getState());
1448
		customAddress.setCountry(customerAddress.getCountry());
1449
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1450
		return customAddress;
1451
	}
1452
 
23650 amit.gupta 1453
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1454
			throws ProfitMandiBusinessException {
23365 ashik.ali 1455
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1456
 
22859 ashik.ali 1457
		float calculatedAmount = 0;
23650 amit.gupta 1458
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1459
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1460
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1461
		}
23650 amit.gupta 1462
		if (calculatedAmount != totalAmount) {
1463
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
1464
					calculatedAmount, totalAmount);
1465
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1466
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1467
		}
23650 amit.gupta 1468
 
23365 ashik.ali 1469
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1470
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1471
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1472
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1473
					"FFORDR_1017");
23365 ashik.ali 1474
		}
22859 ashik.ali 1475
	}
23650 amit.gupta 1476
 
22925 ashik.ali 1477
	@Override
1478
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1479
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1480
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1481
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1482
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1483
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1484
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1485
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1486
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1487
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1488
				newFofoOrderItems.add(fofoOrderItem);
1489
				fofoOrderItemsIterator.remove();
1490
			}
1491
			fofoOrderItems = newFofoOrderItems;
1492
		}
1493
		return fofoOrderItems;
1494
	}
23650 amit.gupta 1495
 
1496
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1497
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1498
			@Override
1499
			public Integer apply(FofoOrderItem fofoOrderItem) {
1500
				return fofoOrderItem.getId();
1501
			}
1502
		};
1503
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1504
	}
23650 amit.gupta 1505
 
1506
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1507
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1508
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1509
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1510
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1511
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1512
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1513
				fofoLineItems2.add(fofoLineItem);
1514
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1515
			} else {
22925 ashik.ali 1516
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1517
			}
1518
		}
1519
		return fofoOrderItemIdFofoLineItemsMap;
1520
	}
23650 amit.gupta 1521
 
1522
	private String getOtpString() {
23418 ashik.ali 1523
		Random rndm_method = new Random();
23650 amit.gupta 1524
		String numbers = "0123456789";
23418 ashik.ali 1525
		char[] otp = new char[5];
22859 ashik.ali 1526
 
23650 amit.gupta 1527
		for (int i = 0; i < 5; i++) {
23418 ashik.ali 1528
			otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
1529
		}
1530
		return String.valueOf(otp);
1531
	}
23650 amit.gupta 1532
 
1533
	private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount) {
1534
		Map<Integer, String> itemIdDescriptionMap = inventoryService
1535
				.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());
23418 ashik.ali 1536
		StringBuilder itemIdAdvanceAmountString = new StringBuilder();
1537
		int index = 0;
23650 amit.gupta 1538
		for (Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {
23418 ashik.ali 1539
			itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));
1540
			itemIdAdvanceAmountString.append("'s Advance amount [");
1541
			itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());
1542
			itemIdAdvanceAmountString.append("]");
23650 amit.gupta 1543
			if (index + 1 < itemIdAdvanceAmount.size()) {
23418 ashik.ali 1544
				itemIdAdvanceAmountString.append(", ");
1545
			}
1546
			index++;
1547
		}
1548
		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 1549
		LOGGER.info("OTP to Customer Successfully sends" + text);
23418 ashik.ali 1550
		String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);
1551
		try {
1552
			Utils.sendSms(msg, phone);
1553
		} catch (URISyntaxException e) {
1554
			// TODO Auto-generated catch block
1555
			e.printStackTrace();
1556
		} catch (IOException e) {
1557
			// TODO Auto-generated catch block
1558
			e.printStackTrace();
1559
		}
23650 amit.gupta 1560
 
23418 ashik.ali 1561
	}
23650 amit.gupta 1562
 
23418 ashik.ali 1563
	@Override
23650 amit.gupta 1564
	public int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber,
1565
			Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {
1566
		if (!StringUtils.isValidEmailAddress(customerEmailId)) {
23418 ashik.ali 1567
			LOGGER.error("invalid customer emailId {} ", customerEmailId);
1568
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");
1569
		}
1570
 
23650 amit.gupta 1571
		if (!StringUtils.isValidMobile(customerMobileNumber)) {
23418 ashik.ali 1572
			LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);
1573
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");
1574
		}
23650 amit.gupta 1575
 
23418 ashik.ali 1576
		List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);
1577
		String otp = null;
23650 amit.gupta 1578
		if (otps.size() >= 5) {
1579
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId,
1580
					"FFORDR_1019");
23418 ashik.ali 1581
		}
23650 amit.gupta 1582
		if (!otps.isEmpty()) {
1583
			if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))) {
23418 ashik.ali 1584
				return otps.get(0).getId();
23650 amit.gupta 1585
			} else if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))) {
23418 ashik.ali 1586
				otp = otps.get(0).getOtp();
1587
			}
1588
		}
23650 amit.gupta 1589
		if (otp == null || otp.isEmpty()) {
23418 ashik.ali 1590
			otp = getOtpString();
1591
		}
23650 amit.gupta 1592
 
23418 ashik.ali 1593
		this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);
23650 amit.gupta 1594
 
23418 ashik.ali 1595
		Otp otp_bean = new Otp();
1596
		otp_bean.setEmail(customerEmailId);
1597
		otp_bean.setMobile(customerMobileNumber);
1598
		otp_bean.setOtp(otp);
1599
		otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);
1600
		otp_bean.setCreatedOn(LocalDateTime.now());
1601
		otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
1602
		otpRepository.persist(otp_bean);
23650 amit.gupta 1603
 
23418 ashik.ali 1604
		return otp_bean.getId();
1605
	}
23650 amit.gupta 1606
 
23418 ashik.ali 1607
	@Override
1608
	public String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)
1609
			throws ProfitMandiBusinessException {
1610
		Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);
1611
		otp.setTryCount(otp.getTryCount() + 1);
23650 amit.gupta 1612
		if (!otp.getOtp().equalsIgnoreCase(otpValue)) {
23418 ashik.ali 1613
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");
1614
		}
23650 amit.gupta 1615
		if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
23418 ashik.ali 1616
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");
1617
		}
23650 amit.gupta 1618
		if (otp.getTryCount() > 5) {
23418 ashik.ali 1619
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");
1620
		}
1621
		otp.setExpired(true);
1622
		otp.setVerified(true);
1623
		otpRepository.persist(otp);
23650 amit.gupta 1624
 
23418 ashik.ali 1625
		return ResponseCodeHolder.getMessage("FFORDR_OK_1002");
1626
	}
23650 amit.gupta 1627
 
23582 ashik.ali 1628
	@Override
23650 amit.gupta 1629
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1630
			throws ProfitMandiBusinessException {
23582 ashik.ali 1631
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1632
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1633
		customer.setFirstName(customCustomer.getFirstName());
1634
		customer.setLastName(customCustomer.getLastName());
1635
		customerRepository.persist(customer);
1636
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1637
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1638
		customerAddressRepository.persist(customerAddress);
1639
	}
23418 ashik.ali 1640
 
23638 amit.gupta 1641
	@Override
23655 amit.gupta 1642
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest) throws ProfitMandiBusinessException {
1643
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1644
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1645
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1646
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1647
		}
23655 amit.gupta 1648
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
1649
		if(foiBadReturnRequest.getMarkedBadArr().size() > billedQty ) {
1650
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1651
		}
23650 amit.gupta 1652
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1653
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1654
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1655
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1656
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
1657
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1658
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1659
			customerReturnItem.setQuantity(1);
1660
			customerReturnItem.setType(ReturnType.BAD);
1661
			//customerReturnItemRepository.persist(customerReturnItem);
1662
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1663
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1664
		}
23655 amit.gupta 1665
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
1666
		for (CustomerReturnItem customerReturnItem: customerReturnItems) {
1667
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(), ReturnType.BAD);
1668
		}
1669
        return creditNote;
23638 amit.gupta 1670
	}
1671
 
23655 amit.gupta 1672
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems) throws ProfitMandiBusinessException {
23650 amit.gupta 1673
 
23638 amit.gupta 1674
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1675
				.selectByFofoId(fofoOrder.getFofoId());
1676
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1677
		invoiceNumberGenerationSequenceRepository.persist(sequence);
23650 amit.gupta 1678
 
23655 amit.gupta 1679
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1680
		CustomerCreditNote creditNote = new CustomerCreditNote();
1681
		creditNote.setCreditNoteNumber(creditNoteNumber);
1682
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1683
		creditNote.setFofoOrderId(fofoOrder.getId());
1684
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1685
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1686
		customerCreditNoteRepository.persist(creditNote);
1687
 
1688
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1689
			customerReturnItem.setCreditNoteId(creditNote.getId());
1690
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1691
		}
23650 amit.gupta 1692
		//this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1693
 
23655 amit.gupta 1694
		return creditNote;
23650 amit.gupta 1695
	}
1696
 
23655 amit.gupta 1697
	@Override
1698
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1699
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1700
		return getCreditNotePdfModel(creditNote);
1701
	}
1702
 
1703
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote) throws ProfitMandiBusinessException {
1704
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
1705
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository.selectAllByCreditNoteId(creditNote.getId());
1706
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
1707
 
1708
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
1709
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoOrder.getFofoId())).get(fofoOrder.getFofoId());
1710
 
1711
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1712
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1713
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1714
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1715
 
1716
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1717
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1718
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1719
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
1720
 
1721
		if(ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())){
1722
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1723
					.collect(Collectors.toSet());
1724
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1725
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1726
			customFofoOrderItem.setDescription(
1727
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1728
		}
1729
 
1730
		customFofoOrderItem.setRate(taxableSellingPrice);
1731
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1732
		customFofoOrderItem.setQuantity(customerReturnItems.size());
1733
		customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
1734
 
1735
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1736
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1737
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1738
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1739
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1740
		customFofoOrderItem.setIgstAmount(igstAmount);
1741
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1742
		customFofoOrderItem.setCgstAmount(cgstAmount);
1743
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1744
		customFofoOrderItem.setSgstAmount(sgstAmount);
1745
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1746
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1747
		customerFofoOrderItems.add(customFofoOrderItem);
1748
 
23650 amit.gupta 1749
		PdfModel pdfModel = new PdfModel();
1750
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1751
		pdfModel.setCustomer(customCustomer);
1752
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1753
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1754
		pdfModel.setTitle("Credit Note");
1755
		pdfModel.setRetailer(customRetailer);
1756
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1757
		pdfModel.setOrderItems(customerFofoOrderItems);
1758
 
23650 amit.gupta 1759
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1760
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1761
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1762
		creditNotePdfModel.setPdfModel(pdfModel);
1763
		return creditNotePdfModel;
1764
	}
23638 amit.gupta 1765
 
22859 ashik.ali 1766
}