Subversion Repositories SmartDukaan

Rev

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