Subversion Repositories SmartDukaan

Rev

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