Subversion Repositories SmartDukaan

Rev

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