Subversion Repositories SmartDukaan

Rev

Rev 25101 | Rev 25103 | 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<>();
23650 amit.gupta 1084
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
22872 ashik.ali 1085
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
25102 amit.gupta 1086
			if (customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
22872 ashik.ali 1087
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 1088
			}
1089
		}
23650 amit.gupta 1090
 
1091
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1092
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
1093
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 1094
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 1095
		}
23650 amit.gupta 1096
 
22859 ashik.ali 1097
	}
23650 amit.gupta 1098
 
1099
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
24264 amit.gupta 1100
			Map<Integer, Integer> inventoryItemQuantityUsed, int fofoOrderId) {
23650 amit.gupta 1101
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1102
			inventoryItem.setLastScanType(ScanType.SALE);
1103
			inventoryItemRepository.persist(inventoryItem);
1104
			ScanRecord scanRecord = new ScanRecord();
1105
			scanRecord.setInventoryItemId(inventoryItem.getId());
1106
			scanRecord.setFofoId(fofoId);
24264 amit.gupta 1107
			scanRecord.setOrderId(fofoOrderId);
23650 amit.gupta 1108
			// correct this
22859 ashik.ali 1109
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1110
			scanRecord.setType(ScanType.SALE);
1111
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1112
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1113
 
22859 ashik.ali 1114
		}
1115
	}
23650 amit.gupta 1116
 
1117
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1118
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1119
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1120
			FofoLineItem fofoLineItem = new FofoLineItem();
1121
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1122
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1123
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1124
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1125
			fofoLineItemRepository.persist(fofoLineItem);
1126
		}
1127
	}
23650 amit.gupta 1128
 
1129
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1130
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1131
			throws ProfitMandiBusinessException {
22859 ashik.ali 1132
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1133
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1134
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1135
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1136
		fofoOrderItem.setOrderId(fofoOrderId);
24825 amit.gupta 1137
		fofoOrderItem.setDp(tagListingRepository.selectByItemId(customFofoOrderItem.getItemId()).getSellingPrice());
22859 ashik.ali 1138
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
24823 amit.gupta 1139
 
22859 ashik.ali 1140
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1141
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1142
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1143
		if (stateId != null) {
23172 ashik.ali 1144
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1145
		} else {
23172 ashik.ali 1146
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1147
		}
23650 amit.gupta 1148
		for (InventoryItem inventoryItem : inventoryItems) {
1149
			if (stateId == null) {
23172 ashik.ali 1150
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1151
			} else {
23172 ashik.ali 1152
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1153
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1154
			}
23650 amit.gupta 1155
 
22859 ashik.ali 1156
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1157
			break;
1158
		}
1159
		fofoOrderItem.setBrand(item.getBrand());
1160
		fofoOrderItem.setModelName(item.getModelName());
1161
		fofoOrderItem.setModelNumber(item.getModelNumber());
1162
		fofoOrderItem.setColor(item.getColor());
1163
		fofoOrderItemRepository.persist(fofoOrderItem);
1164
		return fofoOrderItem;
1165
	}
23650 amit.gupta 1166
 
1167
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1168
			int itemId, int quantity) throws ProfitMandiBusinessException {
1169
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1170
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1171
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1172
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1173
			}
1174
		}
1175
	}
23650 amit.gupta 1176
 
1177
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1178
			throws ProfitMandiBusinessException {
1179
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1180
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1181
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1182
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1183
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1184
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1185
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1186
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1187
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1188
			}
22859 ashik.ali 1189
		}
1190
	}
23650 amit.gupta 1191
 
24275 amit.gupta 1192
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber,
1193
			float totalAmount, int customerAddressId) {
22859 ashik.ali 1194
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1195
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1196
		fofoOrder.setCustomerId(customerId);
1197
		fofoOrder.setFofoId(fofoId);
24226 amit.gupta 1198
		fofoOrder.setInvoiceNumber(documentNumber);
22859 ashik.ali 1199
		fofoOrder.setTotalAmount(totalAmount);
1200
		fofoOrder.setCustomerAddressId(customerAddressId);
1201
		fofoOrderRepository.persist(fofoOrder);
1202
		return fofoOrder;
1203
	}
23650 amit.gupta 1204
 
1205
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException {
22859 ashik.ali 1206
		Customer customer = null;
23650 amit.gupta 1207
		try {
22859 ashik.ali 1208
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
23650 amit.gupta 1209
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 1210
			LOGGER.error("Customer not found with mobileNumber [{}]", customCustomer.getMobileNumber());
22859 ashik.ali 1211
			customer = new Customer();
1212
		}
23190 ashik.ali 1213
		customer.setFirstName(customCustomer.getFirstName());
1214
		customer.setLastName(customCustomer.getLastName());
1215
		customer.setEmailId(customCustomer.getEmailId());
1216
		customer.setMobileNumber(customCustomer.getMobileNumber());
1217
		customerRepository.persist(customer);
22859 ashik.ali 1218
		return customer;
1219
	}
23650 amit.gupta 1220
 
1221
	private void validateItemsSerializedNonSerialized(List<Item> items,
1222
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1223
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1224
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1225
		for (Item i : items) {
22872 ashik.ali 1226
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1227
			if (i.getType().equals(ItemType.SERIALIZED)) {
1228
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1229
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1230
				}
23650 amit.gupta 1231
			} else {
1232
				Set<String> serialNumbers = this
1233
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1234
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1235
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1236
				}
1237
			}
1238
		}
1239
 
23650 amit.gupta 1240
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1241
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1242
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1243
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1244
					"FFORDR_1013");
22859 ashik.ali 1245
		}
1246
 
23650 amit.gupta 1247
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1248
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1249
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1250
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1251
					"FFORDR_1014");
22859 ashik.ali 1252
		}
1253
	}
23650 amit.gupta 1254
 
1255
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1256
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1257
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1258
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1259
		}
23650 amit.gupta 1260
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1261
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1262
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1263
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1264
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1265
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1266
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1267
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1268
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1269
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1270
				Quantity quantity = new Quantity();
1271
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1272
				quantity.setRequested(customFofoOrderItem.getQuantity());
1273
				itemIdQuantityAvailability.setQuantity(quantity);
1274
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1275
			}
22859 ashik.ali 1276
		}
1277
 
23650 amit.gupta 1278
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1279
			// itemIdQuantity request is not valid
23650 amit.gupta 1280
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1281
					itemIdQuantityAvailabilities);
1282
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1283
					"FFORDR_1015");
22859 ashik.ali 1284
		}
1285
	}
23650 amit.gupta 1286
 
1287
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1288
			String serialNumber) {
22872 ashik.ali 1289
		int itemId = 0;
23650 amit.gupta 1290
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1291
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1292
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1293
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1294
					itemId = entry.getKey();
1295
					break;
1296
				}
22859 ashik.ali 1297
			}
1298
		}
22872 ashik.ali 1299
		return itemId;
22859 ashik.ali 1300
	}
23650 amit.gupta 1301
 
1302
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1303
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1304
			@Override
1305
			public Integer apply(Item item) {
1306
				return item.getId();
1307
			}
1308
		};
1309
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1310
			@Override
1311
			public Item apply(Item item) {
1312
				return item;
1313
			}
1314
		};
1315
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1316
	}
1317
 
23650 amit.gupta 1318
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1319
		customerAddress.setName(customAddress.getName());
1320
		customerAddress.setLine1(customAddress.getLine1());
1321
		customerAddress.setLine2(customAddress.getLine2());
1322
		customerAddress.setLandmark(customAddress.getLandmark());
1323
		customerAddress.setCity(customAddress.getCity());
1324
		customerAddress.setPinCode(customAddress.getPinCode());
1325
		customerAddress.setState(customAddress.getState());
1326
		customerAddress.setCountry(customAddress.getCountry());
1327
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1328
	}
1329
 
23650 amit.gupta 1330
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1331
		CustomAddress customAddress = new CustomAddress();
1332
		customAddress.setName(address.getName());
1333
		customAddress.setLine1(address.getLine1());
1334
		customAddress.setLine2(address.getLine2());
1335
		customAddress.setLandmark(address.getLandmark());
1336
		customAddress.setCity(address.getCity());
1337
		customAddress.setPinCode(address.getPinCode());
1338
		customAddress.setState(address.getState());
1339
		customAddress.setCountry(address.getCountry());
1340
		customAddress.setPhoneNumber(address.getPhoneNumber());
1341
		return customAddress;
1342
	}
1343
 
23650 amit.gupta 1344
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1345
		CustomAddress customAddress = new CustomAddress();
1346
		customAddress.setName(customerAddress.getName());
1347
		customAddress.setLine1(customerAddress.getLine1());
1348
		customAddress.setLine2(customerAddress.getLine2());
1349
		customAddress.setLandmark(customerAddress.getLandmark());
1350
		customAddress.setCity(customerAddress.getCity());
1351
		customAddress.setPinCode(customerAddress.getPinCode());
1352
		customAddress.setState(customerAddress.getState());
1353
		customAddress.setCountry(customerAddress.getCountry());
1354
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1355
		return customAddress;
1356
	}
1357
 
23650 amit.gupta 1358
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1359
			throws ProfitMandiBusinessException {
23365 ashik.ali 1360
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1361
 
22859 ashik.ali 1362
		float calculatedAmount = 0;
23650 amit.gupta 1363
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1364
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1365
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1366
		}
23650 amit.gupta 1367
		if (calculatedAmount != totalAmount) {
1368
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
1369
					calculatedAmount, totalAmount);
1370
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1371
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1372
		}
23650 amit.gupta 1373
 
23365 ashik.ali 1374
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1375
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1376
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1377
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1378
					"FFORDR_1017");
23365 ashik.ali 1379
		}
22859 ashik.ali 1380
	}
23650 amit.gupta 1381
 
22925 ashik.ali 1382
	@Override
1383
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1384
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1385
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1386
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1387
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1388
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1389
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1390
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1391
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1392
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1393
				newFofoOrderItems.add(fofoOrderItem);
1394
				fofoOrderItemsIterator.remove();
1395
			}
1396
			fofoOrderItems = newFofoOrderItems;
1397
		}
1398
		return fofoOrderItems;
1399
	}
23650 amit.gupta 1400
 
1401
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1402
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1403
			@Override
1404
			public Integer apply(FofoOrderItem fofoOrderItem) {
1405
				return fofoOrderItem.getId();
1406
			}
1407
		};
1408
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1409
	}
23650 amit.gupta 1410
 
1411
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1412
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1413
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1414
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1415
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1416
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1417
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1418
				fofoLineItems2.add(fofoLineItem);
1419
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1420
			} else {
22925 ashik.ali 1421
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1422
			}
1423
		}
1424
		return fofoOrderItemIdFofoLineItemsMap;
1425
	}
23650 amit.gupta 1426
 
23418 ashik.ali 1427
	@Override
23650 amit.gupta 1428
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1429
			throws ProfitMandiBusinessException {
23582 ashik.ali 1430
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1431
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1432
		customer.setFirstName(customCustomer.getFirstName());
1433
		customer.setLastName(customCustomer.getLastName());
24121 govind 1434
		customer.setMobileNumber(customCustomer.getMobileNumber());
1435
		customer.setEmailId(customCustomer.getEmailId());
23582 ashik.ali 1436
		customerRepository.persist(customer);
1437
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
25101 amit.gupta 1438
		if (!customerAddress.getState().equals(customCustomer.getAddress().getState())) {
1439
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1440
			resetTaxation(fofoOrder.getFofoId(), customerAddress, fofoOrderItems);
1441
		}
23582 ashik.ali 1442
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1443
		customerAddressRepository.persist(customerAddress);
24121 govind 1444
		fofoOrder.setCustomerGstNumber(customCustomer.getGstNumber());
23582 ashik.ali 1445
	}
23418 ashik.ali 1446
 
25101 amit.gupta 1447
	private void resetTaxation(int fofoId, CustomerAddress customerAddress, List<FofoOrderItem> fofoOrderItems)
1448
			throws ProfitMandiBusinessException {
1449
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
1450
 
1451
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
1452
 
1453
		Integer stateId = null;
1454
		if (customerAddress.getState().equals(retailerAddress.getState())) {
1455
			try {
1456
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
1457
			} catch (Exception e) {
1458
				LOGGER.error("Unable to get state rates");
1459
			}
1460
		}
1461
		List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
1462
		final Map<Integer, GstRate> gstRates;
1463
		if (stateId != null) {
1464
			gstRates = Utils.getStateTaxRate(itemIds, stateId);
1465
		} else {
1466
			gstRates = new HashMap<>();
1467
			Utils.getIgstTaxRate(itemIds).entrySet().forEach(x -> {
1468
				GstRate gstRate = new GstRate();
1469
				gstRate.setIgstRate(x.getValue());
1470
				gstRate.setCgstRate(0f);
1471
				gstRate.setSgstRate(0f);
1472
				gstRates.put(x.getKey(), gstRate);
1473
 
1474
			});
1475
		}
1476
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1477
			GstRate rate = gstRates.get(fofoOrderItem.getItemId());
1478
			fofoOrderItem.setCgstRate(rate.getCgstRate());
1479
			fofoOrderItem.setSgstRate(rate.getSgstRate());
1480
			fofoOrderItem.setIgstRate(rate.getIgstRate());
1481
		}
1482
	}
1483
 
23638 amit.gupta 1484
	@Override
24275 amit.gupta 1485
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest)
1486
			throws ProfitMandiBusinessException {
23655 amit.gupta 1487
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1488
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1489
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1490
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1491
		}
23655 amit.gupta 1492
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
24275 amit.gupta 1493
		if (foiBadReturnRequest.getMarkedBadArr().size() > billedQty) {
23655 amit.gupta 1494
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1495
		}
23650 amit.gupta 1496
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1497
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1498
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1499
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1500
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
24264 amit.gupta 1501
			customerReturnItem.setFofoOrderId(fofoOrder.getId());
23655 amit.gupta 1502
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1503
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1504
			customerReturnItem.setQuantity(1);
1505
			customerReturnItem.setType(ReturnType.BAD);
24275 amit.gupta 1506
			// customerReturnItemRepository.persist(customerReturnItem);
23650 amit.gupta 1507
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1508
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1509
		}
23655 amit.gupta 1510
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
24275 amit.gupta 1511
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1512
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(),
1513
					ReturnType.BAD);
23655 amit.gupta 1514
		}
24275 amit.gupta 1515
		return creditNote;
23638 amit.gupta 1516
	}
1517
 
24275 amit.gupta 1518
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems)
1519
			throws ProfitMandiBusinessException {
23650 amit.gupta 1520
 
23638 amit.gupta 1521
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1522
				.selectByFofoId(fofoOrder.getFofoId());
1523
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1524
		invoiceNumberGenerationSequenceRepository.persist(sequence);
24275 amit.gupta 1525
 
23655 amit.gupta 1526
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1527
		CustomerCreditNote creditNote = new CustomerCreditNote();
1528
		creditNote.setCreditNoteNumber(creditNoteNumber);
1529
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1530
		creditNote.setFofoOrderId(fofoOrder.getId());
1531
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1532
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1533
		customerCreditNoteRepository.persist(creditNote);
24275 amit.gupta 1534
 
23650 amit.gupta 1535
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1536
			customerReturnItem.setCreditNoteId(creditNote.getId());
1537
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1538
		}
24275 amit.gupta 1539
		// this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1540
 
23655 amit.gupta 1541
		return creditNote;
23650 amit.gupta 1542
	}
24275 amit.gupta 1543
 
23655 amit.gupta 1544
	@Override
1545
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1546
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1547
		return getCreditNotePdfModel(creditNote);
1548
	}
24275 amit.gupta 1549
 
1550
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote)
1551
			throws ProfitMandiBusinessException {
23655 amit.gupta 1552
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
24275 amit.gupta 1553
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository
1554
				.selectAllByCreditNoteId(creditNote.getId());
23655 amit.gupta 1555
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
24275 amit.gupta 1556
 
23655 amit.gupta 1557
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
24275 amit.gupta 1558
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoOrder.getFofoId()))
1559
				.get(fofoOrder.getFofoId());
23655 amit.gupta 1560
 
1561
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1562
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1563
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1564
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1565
 
1566
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1567
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1568
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1569
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
24275 amit.gupta 1570
 
1571
		if (ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())) {
23655 amit.gupta 1572
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1573
					.collect(Collectors.toSet());
1574
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1575
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1576
			customFofoOrderItem.setDescription(
1577
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1578
		}
24275 amit.gupta 1579
 
23655 amit.gupta 1580
		customFofoOrderItem.setRate(taxableSellingPrice);
1581
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1582
		customFofoOrderItem.setQuantity(customerReturnItems.size());
24275 amit.gupta 1583
		customFofoOrderItem.setNetAmount(
1584
				(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
23655 amit.gupta 1585
 
1586
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1587
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1588
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1589
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1590
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1591
		customFofoOrderItem.setIgstAmount(igstAmount);
1592
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1593
		customFofoOrderItem.setCgstAmount(cgstAmount);
1594
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1595
		customFofoOrderItem.setSgstAmount(sgstAmount);
1596
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1597
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1598
		customerFofoOrderItems.add(customFofoOrderItem);
24275 amit.gupta 1599
 
23650 amit.gupta 1600
		PdfModel pdfModel = new PdfModel();
1601
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1602
		pdfModel.setCustomer(customCustomer);
1603
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1604
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1605
		pdfModel.setTitle("Credit Note");
1606
		pdfModel.setRetailer(customRetailer);
1607
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1608
		pdfModel.setOrderItems(customerFofoOrderItems);
24275 amit.gupta 1609
 
23650 amit.gupta 1610
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1611
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1612
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1613
		creditNotePdfModel.setPdfModel(pdfModel);
1614
		return creditNotePdfModel;
1615
	}
23638 amit.gupta 1616
 
24275 amit.gupta 1617
	// This will remove the order and maintain order record and reverse inventory
1618
	// and scheme
24264 amit.gupta 1619
	@Override
1620
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
24275 amit.gupta 1621
		for (String invoiceNumber : invoiceNumbers) {
24264 amit.gupta 1622
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1623
			fofoOrder.setCancelledTimestamp(LocalDateTime.now());
1624
			fofoOrderRepository.persist(fofoOrder);
24275 amit.gupta 1625
			List<PaymentOptionTransaction> paymentTransactions = paymentOptionTransactionRepository
1626
					.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
24264 amit.gupta 1627
			for (PaymentOptionTransaction paymentOptionTransaction : paymentTransactions) {
1628
				paymentOptionTransactionRepository.delete(paymentOptionTransaction);
1629
			}
1630
			List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1631
			List<InventoryItem> inventoryItems = new ArrayList<>();
24275 amit.gupta 1632
			fois.stream().forEach(x -> {
1633
				x.getFofoLineItems().stream().forEach(y -> {
24264 amit.gupta 1634
					inventoryService.rollbackInventory(y.getInventoryItemId(), y.getQuantity(), fofoOrder.getFofoId());
1635
					inventoryItems.add(inventoryItemRepository.selectById(y.getInventoryItemId()));
1636
				});
1637
			});
1638
			String reversalReason = "Order Rolledback/Cancelled for Invoice Number " + invoiceNumber;
1639
			schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, SchemeType.OUT);
1640
		}
1641
	}
1642
 
24271 amit.gupta 1643
	@Override
1644
	public float getSales(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
24287 amit.gupta 1645
		Float sales = fofoOrderRepository.selectSaleSumGroupByFofoIds(startDate, endDate).get(fofoId);
24285 amit.gupta 1646
		return sales == null ? 0f : sales;
24271 amit.gupta 1647
	}
1648
 
1649
	@Override
1650
	public float getSales(int fofoId, LocalDate onDate) {
24285 amit.gupta 1651
		LocalDateTime startTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT);
1652
		LocalDateTime endTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT).plusDays(1);
1653
		return this.getSales(fofoId, startTime, endTime);
24271 amit.gupta 1654
	}
1655
 
1656
	@Override
1657
	public float getSales(LocalDateTime onDate) {
1658
		// TODO Auto-generated method stub
1659
		return 0;
1660
	}
1661
 
1662
	@Override
1663
	public float getSales(LocalDateTime startDate, LocalDateTime endDate) {
1664
		// TODO Auto-generated method stub
1665
		return 0;
1666
	}
1667
 
24917 tejbeer 1668
	@Override
1669
	public boolean notifyColorChange(int orderId, int itemId) throws ProfitMandiBusinessException {
1670
		Order order = orderRepository.selectById(orderId);
25101 amit.gupta 1671
		inventoryService.reservationCount(itemId, order.getLineItem().getItemId(), order.getFulfilmentWarehouseId(),
1672
				order.getLineItem().getQuantity());
1673
 
1674
		order.getLineItem().setItemId(itemId);
1675
		Item item = itemRepository.selectById(itemId);
24917 tejbeer 1676
		order.getLineItem().setColor(item.getColor());
1677
		return true;
1678
	}
1679
 
25083 amit.gupta 1680
	@Override
1681
	public FofoOrder getOrderByInventoryItemId(int inventoryItemId) throws Exception {
1682
		List<FofoLineItem> lineItems = fofoLineItemRepository.selectByInventoryItemId(inventoryItemId);
25101 amit.gupta 1683
		if (lineItems.size() > 0) {
25083 amit.gupta 1684
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(lineItems.get(0).getFofoOrderItemId());
1685
			fofoOrderItem.setFofoLineItems(new HashSet<>(lineItems));
1686
			FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderItem.getOrderId());
1687
			fofoOrder.setOrderItem(fofoOrderItem);
1688
			return fofoOrder;
1689
		} else {
1690
			throw new Exception(String.format("Could not find inventoryItemId - %s", inventoryItemId));
1691
		}
1692
	}
1693
 
22859 ashik.ali 1694
}