Subversion Repositories SmartDukaan

Rev

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