Subversion Repositories SmartDukaan

Rev

Rev 25793 | Rev 26332 | 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
149
	private RetailerService retailerService;
150
 
151
	@Autowired
22859 ashik.ali 152
	private CustomerRepository customerRepository;
23650 amit.gupta 153
 
23566 amit.gupta 154
	@Autowired
155
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
22859 ashik.ali 156
 
157
	@Autowired
158
	private AddressRepository addressRepository;
159
 
160
	@Autowired
161
	private FofoLineItemRepository fofoLineItemRepository;
162
 
163
	@Autowired
164
	private FofoOrderItemRepository fofoOrderItemRepository;
23650 amit.gupta 165
 
22859 ashik.ali 166
	@Autowired
167
	private PaymentOptionRepository paymentOptionRepository;
168
 
169
	@Autowired
23650 amit.gupta 170
	private CustomerReturnItemRepository customerReturnItemRepository;
171
 
172
	@Autowired
23781 ashik.ali 173
	@Qualifier("fofoScanRecordRepository")
22859 ashik.ali 174
	private ScanRecordRepository scanRecordRepository;
175
 
176
	@Autowired
177
	private FofoOrderRepository fofoOrderRepository;
178
 
179
	@Autowired
180
	private RetailerRepository retailerRepository;
181
 
182
	@Autowired
183
	private UserRepository userRepository;
184
 
185
	@Autowired
186
	private UserAccountRepository userAccountRepository;
187
 
188
	@Autowired
189
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
190
 
191
	@Autowired
192
	private CustomerAddressRepository customerAddressRepository;
193
 
194
	@Autowired
23781 ashik.ali 195
	@Qualifier("catalogItemRepository")
22859 ashik.ali 196
	private ItemRepository itemRepository;
23650 amit.gupta 197
 
22859 ashik.ali 198
	@Autowired
199
	private InsuranceProviderRepository insuranceProviderRepository;
23650 amit.gupta 200
 
22859 ashik.ali 201
	@Autowired
202
	private InsurancePolicyRepository insurancePolicyRepository;
24917 tejbeer 203
 
24854 amit.gupta 204
	@Autowired
205
	private StateRepository stateRepository;
23650 amit.gupta 206
 
22859 ashik.ali 207
	@Autowired
208
	private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
23650 amit.gupta 209
 
22859 ashik.ali 210
	@Autowired
211
	private PricingService pricingService;
23650 amit.gupta 212
 
22859 ashik.ali 213
	@Autowired
214
	private PrivateDealUserRepository privateDealUserRepository;
23650 amit.gupta 215
 
22859 ashik.ali 216
	@Autowired
24823 amit.gupta 217
	private TagListingRepository tagListingRepository;
218
 
219
	@Autowired
22859 ashik.ali 220
	private CounterRepository counterRepository;
23650 amit.gupta 221
 
22859 ashik.ali 222
	@Autowired
23202 ashik.ali 223
	private FofoStoreRepository fofoStoreRepository;
23650 amit.gupta 224
 
23202 ashik.ali 225
	@Autowired
23546 ashik.ali 226
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
23650 amit.gupta 227
 
23365 ashik.ali 228
	@Autowired
22859 ashik.ali 229
	private SchemeService schemeService;
23650 amit.gupta 230
 
23418 ashik.ali 231
	@Autowired
23781 ashik.ali 232
	@Qualifier("fofoInventoryService")
23418 ashik.ali 233
	private InventoryService inventoryService;
23650 amit.gupta 234
 
23418 ashik.ali 235
	@Autowired
23650 amit.gupta 236
	private CustomerCreditNoteRepository customerCreditNoteRepository;
237
 
24917 tejbeer 238
	@Autowired
239
	private OrderRepository orderRepository;
240
 
25640 tejbeer 241
	@Autowired
242
	private HygieneDataRepository hygieneDataRepository;
243
 
22859 ashik.ali 244
	@Override
24275 amit.gupta 245
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId, boolean accessoriesDeals)
246
			throws ProfitMandiBusinessException {
25724 amit.gupta 247
		LOGGER.info("fofoId -- {} Order Request -- {}", fofoId, createOrderRequest);
22872 ashik.ali 248
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
249
 
23650 amit.gupta 250
		if (!StringUtils.isValidEmailAddress(customCustomer.getEmailId())) {
22872 ashik.ali 251
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
23650 amit.gupta 252
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(),
253
					"VE_1016");
22872 ashik.ali 254
		}
255
 
23650 amit.gupta 256
		if (!StringUtils.isValidMobile(customCustomer.getMobileNumber())) {
22872 ashik.ali 257
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
23650 amit.gupta 258
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(),
259
					"VE_1071");
22872 ashik.ali 260
		}
23650 amit.gupta 261
 
262
		if (!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
23369 ashik.ali 263
			LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
23650 amit.gupta 264
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER,
265
					customCustomer.getGstNumber(), "VE_1072");
23369 ashik.ali 266
		}
23650 amit.gupta 267
 
268
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); // this is for error
22872 ashik.ali 269
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
23650 amit.gupta 270
		Map<Integer, Float> lineItemPrice = new HashMap<>(); // this is for pricing error
271
 
22859 ashik.ali 272
		float totalAmount = 0;
24226 amit.gupta 273
		boolean noGST = false;
23650 amit.gupta 274
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
275
			// itemIds.add(customFofoOrderItem.getItemId());
276
			Set<String> serialNumbers = this
277
					.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
278
			if (!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.size()) {
22859 ashik.ali 279
				itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
280
			}
23650 amit.gupta 281
			if (!(customFofoOrderItem.getSellingPrice() > 0)) {
22859 ashik.ali 282
				lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
23650 amit.gupta 283
			} else {
22863 ashik.ali 284
				totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
285
				totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
23650 amit.gupta 286
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
24440 amit.gupta 287
					if (serialNumberDetail.getAmount() > 0) {
22859 ashik.ali 288
						totalAmount = totalAmount + serialNumberDetail.getAmount();
289
					}
290
				}
291
			}
23650 amit.gupta 292
 
22872 ashik.ali 293
			itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
22859 ashik.ali 294
		}
23650 amit.gupta 295
		if (!itemIdQuantity.isEmpty()) {
22859 ashik.ali 296
			// if item quantity does not match with given serialnumbers size
297
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
22925 ashik.ali 298
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
23650 amit.gupta 299
			// return "error";
22859 ashik.ali 300
		}
23650 amit.gupta 301
 
24275 amit.gupta 302
		this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
23650 amit.gupta 303
 
304
		if (!lineItemPrice.isEmpty()) {
22859 ashik.ali 305
			// given fofo line item price must be greater than zero
306
			LOGGER.error("requested itemId's selling price must greater than 0");
22925 ashik.ali 307
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
22859 ashik.ali 308
		}
309
 
23650 amit.gupta 310
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository
311
				.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
312
 
22872 ashik.ali 313
		this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 314
 
22872 ashik.ali 315
		List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
23650 amit.gupta 316
		if (items.size() != itemIdCustomFofoOrderItemMap.keySet().size()) {
22872 ashik.ali 317
			LOGGER.error("Requested ItemIds not found in catalog");
23650 amit.gupta 318
			// invalid itemIds
319
			throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(),
320
					"FFORDR_1003");
22872 ashik.ali 321
		}
23650 amit.gupta 322
 
323
		Map<Integer, Item> itemMap = this.toItemMap(items);
324
 
22859 ashik.ali 325
		Set<Integer> nonSerializedItemIds = new HashSet<>();
326
		Set<String> serialNumbers = new HashSet<>();
25724 amit.gupta 327
		List<InsuranceModel> insuredModels = new ArrayList<>();
23650 amit.gupta 328
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
22872 ashik.ali 329
			Item item = itemMap.get(customFofoOrderItem.getItemId());
24275 amit.gupta 330
			noGST = item.getHsnCode().equals("NOGST");
23650 amit.gupta 331
			if (item.getType().equals(ItemType.SERIALIZED)) {
332
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
22859 ashik.ali 333
					serialNumbers.add(serialNumberDetail.getSerialNumber());
24440 amit.gupta 334
					if (serialNumberDetail.getAmount() > 0) {
335
						InsuranceModel im = new InsuranceModel();
336
						im.setBrand(item.getBrand());
25724 amit.gupta 337
						im.setColor(item.getColor());
338
						im.setModelName(item.getModelName() + item.getModelNumber());
24440 amit.gupta 339
						im.setInsuranceAmount(serialNumberDetail.getAmount());
340
						im.setDeviceSellingPrice(customFofoOrderItem.getSellingPrice());
25724 amit.gupta 341
						im.setInsuranceId(serialNumberDetail.getInsurance());
342
						im.setSerialNumber(serialNumberDetail.getSerialNumber());
25793 amit.gupta 343
						im.setMemory(serialNumberDetail.getMemory());
344
						im.setRam(serialNumberDetail.getRam());
25778 amit.gupta 345
						im.setMfgDate(serialNumberDetail.getMfgDate());
25724 amit.gupta 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.");
26200 amit.gupta 645
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
646
		tncs.add("Tempered Glass Replacement will be done only for the Mobile Phone which was purchased from SmartDukaan");
647
		tncs.add("Customers requesting Tempered Glass Replacement will have to bring the broken tempered glass, either pasted on the phone or along with the phone");
648
		tncs.add("Service fee of Rs.20 will be chargeable for each Tempered Glass Replacement");
23650 amit.gupta 649
		if (pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
650
			tncs.add("Damage protection provided is the responisibility of Protection Provider only");
651
		}
23001 amit.gupta 652
		pdfModel.setTncs(tncs);
24275 amit.gupta 653
 
23655 amit.gupta 654
		pdfModel.setCustomer(getCustomCustomer(fofoOrder));
22859 ashik.ali 655
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
656
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
23650 amit.gupta 657
 
23596 ashik.ali 658
		Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
22859 ashik.ali 659
		PrivateDealUser privateDealUser = null;
23650 amit.gupta 660
		try {
22859 ashik.ali 661
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23650 amit.gupta 662
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 663
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
664
		}
23650 amit.gupta 665
 
22859 ashik.ali 666
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
667
		CustomRetailer customRetailer = new CustomRetailer();
668
		customRetailer.setBusinessName(retailer.getName());
669
		customRetailer.setMobileNumber(user.getMobileNumber());
23650 amit.gupta 670
		// customRetailer.setTinNumber(retailer.getNumber());
671
		if (privateDealUser == null) {
22859 ashik.ali 672
			customRetailer.setGstNumber(null);
23650 amit.gupta 673
		} else {
674
			if (null != privateDealUser.getCounterId()) {
22859 ashik.ali 675
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
676
				customRetailer.setGstNumber(counter.getGstin());
23650 amit.gupta 677
			} else {
22859 ashik.ali 678
				customRetailer.setGstNumber(null);
679
			}
680
		}
23650 amit.gupta 681
		Address retailerAddress = addressRepository
682
				.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
22859 ashik.ali 683
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
684
		pdfModel.setRetailer(customRetailer);
23650 amit.gupta 685
 
22859 ashik.ali 686
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
23650 amit.gupta 687
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
22859 ashik.ali 688
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
23650 amit.gupta 689
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate()
690
					+ fofoOrderItem.getCgstRate();
22859 ashik.ali 691
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
692
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
23650 amit.gupta 693
 
22859 ashik.ali 694
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
23650 amit.gupta 695
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
696
					+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
23377 ashik.ali 697
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
23650 amit.gupta 698
			// LOGGER.info("serialNumbers {}", serialNumbers);
699
			// LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
700
			if (!serialNumbers.isEmpty()) {
701
				customFofoOrderItem.setDescription(
702
						customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
23377 ashik.ali 703
			}
22859 ashik.ali 704
			customFofoOrderItem.setRate(taxableSellingPrice);
705
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
706
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
23650 amit.gupta 707
			customFofoOrderItem.setNetAmount(
708
					(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
22859 ashik.ali 709
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
710
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
711
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
712
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
713
			customFofoOrderItem.setIgstAmount(igstAmount);
714
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
715
			customFofoOrderItem.setCgstAmount(cgstAmount);
716
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
717
			customFofoOrderItem.setSgstAmount(sgstAmount);
718
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
719
			customerFofoOrderItems.add(customFofoOrderItem);
720
		}
721
		pdfModel.setOrderItems(customerFofoOrderItems);
24917 tejbeer 722
		String partnerAddressStateCode = stateRepository.selectByName(pdfModel.getRetailer().getAddress().getState())
723
				.getCode();
724
		String customerAddressStateCode = stateRepository.selectByName(pdfModel.getCustomer().getAddress().getState())
725
				.getCode();
24854 amit.gupta 726
		pdfModel.setPartnerAddressStateCode(partnerAddressStateCode);
727
		pdfModel.setCustomerAddressStateCode(customerAddressStateCode);
22859 ashik.ali 728
		return pdfModel;
23650 amit.gupta 729
 
22859 ashik.ali 730
	}
23650 amit.gupta 731
 
23655 amit.gupta 732
	private CustomCustomer getCustomCustomer(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
733
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
734
		CustomCustomer customCustomer = new CustomCustomer();
735
		customCustomer.setFirstName(customer.getFirstName());
736
		customCustomer.setLastName(customer.getLastName());
737
		customCustomer.setEmailId(customer.getEmailId());
738
		customCustomer.setMobileNumber(customer.getMobileNumber());
739
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
740
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
741
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
742
		return customCustomer;
743
	}
744
 
23596 ashik.ali 745
	@Override
746
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
747
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
748
		return this.getInvoicePdfModel(fofoOrder);
749
	}
23650 amit.gupta 750
 
22859 ashik.ali 751
	public String getBillingAddress(CustomerAddress customerAddress) {
752
		StringBuilder address = new StringBuilder();
753
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
754
			address.append(customerAddress.getLine1());
755
			address.append(", ");
756
		}
757
 
758
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
759
			address.append(customerAddress.getLine2());
760
			address.append(", ");
761
		}
762
 
763
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
764
			address.append(customerAddress.getLandmark());
765
			address.append(", ");
766
		}
767
 
768
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
769
			address.append(customerAddress.getCity());
770
			address.append(", ");
771
		}
772
 
773
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
774
			address.append(customerAddress.getState());
775
		}
776
 
777
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
778
			address.append("- ");
779
			address.append(customerAddress.getPinCode());
780
		}
781
 
782
		return address.toString();
783
	}
23650 amit.gupta 784
 
22859 ashik.ali 785
	@Override
23650 amit.gupta 786
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException {
787
		try {
22859 ashik.ali 788
			JSONObject cartObject = new JSONObject(cartJson);
789
			Iterator<?> keys = cartObject.keys();
23650 amit.gupta 790
 
22859 ashik.ali 791
			Set<Integer> itemIds = new HashSet<>();
792
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
23650 amit.gupta 793
 
794
			while (keys.hasNext()) {
795
				String key = (String) keys.next();
796
				if (cartObject.get(key) instanceof JSONObject) {
22859 ashik.ali 797
					LOGGER.info(cartObject.get(key).toString());
798
				}
799
				CartFofo cf = new CartFofo();
800
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
801
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
23650 amit.gupta 802
 
803
				if (cf.getQuantity() <= 0) {
22859 ashik.ali 804
					continue;
805
				}
806
				cartItems.add(cf);
807
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
808
			}
23650 amit.gupta 809
			Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
810
			if (itemIds.size() > 0) {
22859 ashik.ali 811
				List<Item> items = itemRepository.selectByIds(itemIds);
23650 amit.gupta 812
				for (Item i : items) {
22859 ashik.ali 813
					itemMap.put(i.getId(), i);
814
				}
23650 amit.gupta 815
 
22859 ashik.ali 816
			}
23650 amit.gupta 817
			for (CartFofo cf : cartItems) {
22859 ashik.ali 818
				Item i = itemMap.get(cf.getItemId());
23650 amit.gupta 819
				if (i == null) {
22859 ashik.ali 820
					continue;
821
				}
23650 amit.gupta 822
				cf.setDisplayName(getValidName(i.getBrand()) + " " + getValidName(i.getModelName()) + " "
823
						+ getValidName(i.getModelNumber()) + " " + getValidName(i.getColor()).replaceAll("\\s+", " "));
22859 ashik.ali 824
				cf.setItemType(i.getType());
825
			}
826
			return cartItems;
23650 amit.gupta 827
		} catch (Exception e) {
22859 ashik.ali 828
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 829
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 830
		}
831
	}
23650 amit.gupta 832
 
23202 ashik.ali 833
	@Override
23650 amit.gupta 834
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue,
23891 amit.gupta 835
			LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 836
		long countItems = 0;
837
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 838
 
839
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
24275 amit.gupta 840
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, null, null,
841
					offset, limit);
842
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, null, null);
23650 amit.gupta 843
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 844
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, null, null, offset,
845
					limit);
23973 govind 846
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, null, null);
23650 amit.gupta 847
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
24275 amit.gupta 848
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, null, null, offset,
849
					limit);
23973 govind 850
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, null, null);
23650 amit.gupta 851
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 852
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, null, null, offset, limit);
853
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, null, null);
23953 amit.gupta 854
		} else if (searchType == SearchType.INVOICE_NUMBER && !searchValue.isEmpty()) {
855
			fofoOrders = Arrays.asList(fofoOrderRepository.selectByFofoIdAndInvoiceNumber(fofoId, searchValue));
856
			countItems = fofoOrders.size();
24275 amit.gupta 857
		} else if (searchType == SearchType.DATE_RANGE) {
23891 amit.gupta 858
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
859
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDate, endDate);
23202 ashik.ali 860
		}
861
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 862
 
23202 ashik.ali 863
		map.put("saleHistories", fofoOrders);
864
		map.put("start", offset + 1);
865
		map.put("size", countItems);
866
		map.put("searchType", searchType);
23351 ashik.ali 867
		map.put("searchTypes", SearchType.values());
23891 amit.gupta 868
		map.put("startDate", startDate);
23973 govind 869
		map.put("searchValue", searchValue);
23891 amit.gupta 870
		map.put(ProfitMandiConstants.END_TIME, endDate);
23650 amit.gupta 871
		if (fofoOrders.size() < limit) {
23202 ashik.ali 872
			map.put("end", offset + fofoOrders.size());
23650 amit.gupta 873
		} else {
23202 ashik.ali 874
			map.put("end", offset + limit);
875
		}
876
		return map;
877
	}
878
 
879
	@Override
23650 amit.gupta 880
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue,
23891 amit.gupta 881
			LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 882
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 883
 
884
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
23891 amit.gupta 885
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDate,
886
					endDate, offset, limit);
23650 amit.gupta 887
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 888
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDate, endDate,
889
					offset, limit);
23650 amit.gupta 890
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
24275 amit.gupta 891
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDate, endDate,
892
					offset, limit);
23650 amit.gupta 893
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 894
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDate, endDate, offset,
895
					limit);
896
 
897
		} else if (searchType == SearchType.DATE_RANGE) {
23891 amit.gupta 898
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
23202 ashik.ali 899
		}
900
		Map<String, Object> map = new HashMap<>();
901
		map.put("saleHistories", fofoOrders);
23973 govind 902
		map.put("searchType", searchType);
903
		map.put("searchTypes", SearchType.values());
904
		map.put("startDate", startDate);
905
		map.put("searchValue", searchValue);
906
		map.put(ProfitMandiConstants.END_TIME, endDate);
23202 ashik.ali 907
		return map;
908
	}
23650 amit.gupta 909
 
910
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
23202 ashik.ali 911
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 912
		return fofoStore.getCode();
23202 ashik.ali 913
	}
23650 amit.gupta 914
 
915
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId) {
23191 ashik.ali 916
		CustomerAddress customerAddress = null;
23650 amit.gupta 917
		try {
918
			// CustomAddress customAddress = customCustomer.getAddress();
919
			customerAddress = customerAddressRepository.selectByParams(customAddress.getName(),
920
					customAddress.getLine1(), customAddress.getLine2(), customAddress.getLandmark(),
921
					customAddress.getCity(), customAddress.getPinCode(), customAddress.getState(),
922
					customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
923
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23596 ashik.ali 924
			LOGGER.warn("Customer address not found with [{}]", customAddress);
23191 ashik.ali 925
			customerAddress = new CustomerAddress();
926
			this.setCustomerAddress(customerAddress, customAddress);
927
			customerAddress.setCustomerId(customerId);
24466 amit.gupta 928
			customerAddressRepository.persist(customerAddress);
23191 ashik.ali 929
		}
930
		return customerAddress;
931
	}
23650 amit.gupta 932
 
933
	private String getValidName(String name) {
934
		return name != null ? name : "";
22859 ashik.ali 935
	}
23650 amit.gupta 936
 
937
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
23377 ashik.ali 938
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 939
		for (FofoLineItem fofoLineItem : fofoLineItems) {
940
			if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
23377 ashik.ali 941
				serialNumbers.add(fofoLineItem.getSerialNumber());
22955 ashik.ali 942
			}
23377 ashik.ali 943
		}
944
		return serialNumbers;
22859 ashik.ali 945
	}
23650 amit.gupta 946
 
23823 amit.gupta 947
	private void validateDpPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
948
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
949
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoLineItemMap.entrySet()) {
950
			int itemId = entry.getKey();
951
			CustomFofoOrderItem customFofoOrderItem = entry.getValue();
952
			PriceModel priceModel = itemIdMopPriceMap.get(itemId);
25494 amit.gupta 953
			if (customFofoOrderItem.getSerialNumberDetails().stream()
25499 amit.gupta 954
					.filter(x -> org.apache.commons.lang.StringUtils.isNotEmpty(x.getSerialNumber()))
25494 amit.gupta 955
					.collect(Collectors.toList()).size() > 0) {
24275 amit.gupta 956
				if (priceModel.getPrice() > customFofoOrderItem.getSellingPrice()) {
25495 amit.gupta 957
					throw new ProfitMandiBusinessException("Selling Price for ",
24275 amit.gupta 958
							itemRepository.selectById(itemId).getItemDescription(), "FFORDR_1010");
23823 amit.gupta 959
				}
960
			} else {
24275 amit.gupta 961
				if (priceModel.getPurchasePrice() > customFofoOrderItem.getSellingPrice()) {
962
					throw new ProfitMandiBusinessException("Selling Price",
963
							itemRepository.selectById(itemId).getItemDescription(),
964
							"Selling Price should not be less than DP");
23823 amit.gupta 965
				}
966
			}
967
		}
968
	}
24275 amit.gupta 969
 
23650 amit.gupta 970
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
971
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
22859 ashik.ali 972
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
23650 amit.gupta 973
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
22872 ashik.ali 974
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
25102 amit.gupta 975
			if (customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
22872 ashik.ali 976
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 977
			}
978
		}
23650 amit.gupta 979
 
980
		if (!invalidMopItemIdPriceMap.isEmpty()) {
981
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
982
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 983
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 984
		}
23650 amit.gupta 985
 
22859 ashik.ali 986
	}
23650 amit.gupta 987
 
988
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
24264 amit.gupta 989
			Map<Integer, Integer> inventoryItemQuantityUsed, int fofoOrderId) {
23650 amit.gupta 990
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 991
			inventoryItem.setLastScanType(ScanType.SALE);
992
			inventoryItemRepository.persist(inventoryItem);
993
			ScanRecord scanRecord = new ScanRecord();
994
			scanRecord.setInventoryItemId(inventoryItem.getId());
995
			scanRecord.setFofoId(fofoId);
24264 amit.gupta 996
			scanRecord.setOrderId(fofoOrderId);
23650 amit.gupta 997
			// correct this
22859 ashik.ali 998
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
999
			scanRecord.setType(ScanType.SALE);
1000
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1001
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1002
 
22859 ashik.ali 1003
		}
1004
	}
23650 amit.gupta 1005
 
1006
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1007
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1008
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1009
			FofoLineItem fofoLineItem = new FofoLineItem();
1010
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1011
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1012
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1013
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1014
			fofoLineItemRepository.persist(fofoLineItem);
1015
		}
1016
	}
23650 amit.gupta 1017
 
1018
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1019
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1020
			throws ProfitMandiBusinessException {
22859 ashik.ali 1021
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1022
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1023
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1024
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1025
		fofoOrderItem.setOrderId(fofoOrderId);
25103 amit.gupta 1026
		TagListing tl = tagListingRepository.selectByItemId(customFofoOrderItem.getItemId());
25162 amit.gupta 1027
		// In case listing gets removed rebill it using the selling price
1028
		if (tl != null) {
25103 amit.gupta 1029
			fofoOrderItem.setDp(tl.getSellingPrice());
1030
		} else {
1031
			fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1032
		}
22859 ashik.ali 1033
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
24823 amit.gupta 1034
 
22859 ashik.ali 1035
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1036
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1037
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1038
		if (stateId != null) {
23172 ashik.ali 1039
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1040
		} else {
23172 ashik.ali 1041
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1042
		}
23650 amit.gupta 1043
		for (InventoryItem inventoryItem : inventoryItems) {
1044
			if (stateId == null) {
23172 ashik.ali 1045
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1046
			} else {
23172 ashik.ali 1047
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1048
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1049
			}
23650 amit.gupta 1050
 
22859 ashik.ali 1051
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1052
			break;
1053
		}
1054
		fofoOrderItem.setBrand(item.getBrand());
1055
		fofoOrderItem.setModelName(item.getModelName());
1056
		fofoOrderItem.setModelNumber(item.getModelNumber());
1057
		fofoOrderItem.setColor(item.getColor());
1058
		fofoOrderItemRepository.persist(fofoOrderItem);
1059
		return fofoOrderItem;
1060
	}
23650 amit.gupta 1061
 
1062
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1063
			int itemId, int quantity) throws ProfitMandiBusinessException {
1064
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1065
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1066
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1067
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1068
			}
1069
		}
1070
	}
23650 amit.gupta 1071
 
1072
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1073
			throws ProfitMandiBusinessException {
1074
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1075
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1076
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1077
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1078
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1079
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1080
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1081
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1082
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1083
			}
22859 ashik.ali 1084
		}
1085
	}
23650 amit.gupta 1086
 
24275 amit.gupta 1087
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber,
1088
			float totalAmount, int customerAddressId) {
22859 ashik.ali 1089
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1090
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1091
		fofoOrder.setCustomerId(customerId);
1092
		fofoOrder.setFofoId(fofoId);
24226 amit.gupta 1093
		fofoOrder.setInvoiceNumber(documentNumber);
22859 ashik.ali 1094
		fofoOrder.setTotalAmount(totalAmount);
1095
		fofoOrder.setCustomerAddressId(customerAddressId);
1096
		fofoOrderRepository.persist(fofoOrder);
1097
		return fofoOrder;
1098
	}
23650 amit.gupta 1099
 
1100
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException {
25169 amit.gupta 1101
		List<Customer> customers = customerRepository.selectAllByMobileNumber(customCustomer.getMobileNumber());
1102
		List<Customer> filtered = customers.stream()
1103
				.filter(x -> x.getEmailId().equals(customCustomer.getEmailId())
1104
						&& x.getFirstName().equals(customCustomer.getFirstName())
1105
						&& x.getLastName().equals(customCustomer.getLastName()))
1106
				.collect(Collectors.toList());
1107
		if (filtered.size() > 0) {
1108
			return filtered.get(0);
22859 ashik.ali 1109
		}
25169 amit.gupta 1110
		Customer customer = new Customer();
23190 ashik.ali 1111
		customer.setFirstName(customCustomer.getFirstName());
1112
		customer.setLastName(customCustomer.getLastName());
1113
		customer.setEmailId(customCustomer.getEmailId());
1114
		customer.setMobileNumber(customCustomer.getMobileNumber());
1115
		customerRepository.persist(customer);
22859 ashik.ali 1116
		return customer;
1117
	}
23650 amit.gupta 1118
 
1119
	private void validateItemsSerializedNonSerialized(List<Item> items,
1120
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1121
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1122
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1123
		for (Item i : items) {
22872 ashik.ali 1124
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1125
			if (i.getType().equals(ItemType.SERIALIZED)) {
1126
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1127
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1128
				}
23650 amit.gupta 1129
			} else {
1130
				Set<String> serialNumbers = this
1131
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1132
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1133
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1134
				}
1135
			}
1136
		}
1137
 
23650 amit.gupta 1138
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1139
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1140
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1141
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1142
					"FFORDR_1013");
22859 ashik.ali 1143
		}
1144
 
23650 amit.gupta 1145
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1146
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1147
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1148
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1149
					"FFORDR_1014");
22859 ashik.ali 1150
		}
1151
	}
23650 amit.gupta 1152
 
1153
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1154
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1155
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1156
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1157
		}
23650 amit.gupta 1158
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1159
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1160
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1161
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1162
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1163
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1164
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1165
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1166
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1167
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1168
				Quantity quantity = new Quantity();
1169
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1170
				quantity.setRequested(customFofoOrderItem.getQuantity());
1171
				itemIdQuantityAvailability.setQuantity(quantity);
1172
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1173
			}
22859 ashik.ali 1174
		}
1175
 
23650 amit.gupta 1176
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1177
			// itemIdQuantity request is not valid
23650 amit.gupta 1178
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1179
					itemIdQuantityAvailabilities);
1180
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1181
					"FFORDR_1015");
22859 ashik.ali 1182
		}
1183
	}
23650 amit.gupta 1184
 
1185
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1186
			String serialNumber) {
22872 ashik.ali 1187
		int itemId = 0;
23650 amit.gupta 1188
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1189
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1190
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1191
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1192
					itemId = entry.getKey();
1193
					break;
1194
				}
22859 ashik.ali 1195
			}
1196
		}
22872 ashik.ali 1197
		return itemId;
22859 ashik.ali 1198
	}
23650 amit.gupta 1199
 
1200
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1201
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1202
			@Override
1203
			public Integer apply(Item item) {
1204
				return item.getId();
1205
			}
1206
		};
1207
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1208
			@Override
1209
			public Item apply(Item item) {
1210
				return item;
1211
			}
1212
		};
1213
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1214
	}
1215
 
23650 amit.gupta 1216
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1217
		customerAddress.setName(customAddress.getName());
1218
		customerAddress.setLine1(customAddress.getLine1());
1219
		customerAddress.setLine2(customAddress.getLine2());
1220
		customerAddress.setLandmark(customAddress.getLandmark());
1221
		customerAddress.setCity(customAddress.getCity());
1222
		customerAddress.setPinCode(customAddress.getPinCode());
1223
		customerAddress.setState(customAddress.getState());
1224
		customerAddress.setCountry(customAddress.getCountry());
1225
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1226
	}
1227
 
23650 amit.gupta 1228
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1229
		CustomAddress customAddress = new CustomAddress();
1230
		customAddress.setName(address.getName());
1231
		customAddress.setLine1(address.getLine1());
1232
		customAddress.setLine2(address.getLine2());
1233
		customAddress.setLandmark(address.getLandmark());
1234
		customAddress.setCity(address.getCity());
1235
		customAddress.setPinCode(address.getPinCode());
1236
		customAddress.setState(address.getState());
1237
		customAddress.setCountry(address.getCountry());
1238
		customAddress.setPhoneNumber(address.getPhoneNumber());
1239
		return customAddress;
1240
	}
1241
 
23650 amit.gupta 1242
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1243
		CustomAddress customAddress = new CustomAddress();
1244
		customAddress.setName(customerAddress.getName());
1245
		customAddress.setLine1(customerAddress.getLine1());
1246
		customAddress.setLine2(customerAddress.getLine2());
1247
		customAddress.setLandmark(customerAddress.getLandmark());
1248
		customAddress.setCity(customerAddress.getCity());
1249
		customAddress.setPinCode(customerAddress.getPinCode());
1250
		customAddress.setState(customerAddress.getState());
1251
		customAddress.setCountry(customerAddress.getCountry());
1252
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1253
		return customAddress;
1254
	}
1255
 
23650 amit.gupta 1256
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1257
			throws ProfitMandiBusinessException {
23365 ashik.ali 1258
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1259
 
22859 ashik.ali 1260
		float calculatedAmount = 0;
23650 amit.gupta 1261
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1262
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1263
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1264
		}
23650 amit.gupta 1265
		if (calculatedAmount != totalAmount) {
1266
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
1267
					calculatedAmount, totalAmount);
1268
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1269
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1270
		}
23650 amit.gupta 1271
 
23365 ashik.ali 1272
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1273
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1274
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1275
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1276
					"FFORDR_1017");
23365 ashik.ali 1277
		}
22859 ashik.ali 1278
	}
23650 amit.gupta 1279
 
22925 ashik.ali 1280
	@Override
1281
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1282
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1283
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1284
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1285
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1286
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1287
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1288
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1289
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1290
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1291
				newFofoOrderItems.add(fofoOrderItem);
1292
				fofoOrderItemsIterator.remove();
1293
			}
1294
			fofoOrderItems = newFofoOrderItems;
1295
		}
1296
		return fofoOrderItems;
1297
	}
23650 amit.gupta 1298
 
1299
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1300
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1301
			@Override
1302
			public Integer apply(FofoOrderItem fofoOrderItem) {
1303
				return fofoOrderItem.getId();
1304
			}
1305
		};
1306
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1307
	}
23650 amit.gupta 1308
 
1309
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1310
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1311
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1312
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1313
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1314
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1315
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1316
				fofoLineItems2.add(fofoLineItem);
1317
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1318
			} else {
22925 ashik.ali 1319
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1320
			}
1321
		}
1322
		return fofoOrderItemIdFofoLineItemsMap;
1323
	}
23650 amit.gupta 1324
 
23418 ashik.ali 1325
	@Override
23650 amit.gupta 1326
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1327
			throws ProfitMandiBusinessException {
23582 ashik.ali 1328
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1329
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1330
		customer.setFirstName(customCustomer.getFirstName());
1331
		customer.setLastName(customCustomer.getLastName());
24121 govind 1332
		customer.setMobileNumber(customCustomer.getMobileNumber());
1333
		customer.setEmailId(customCustomer.getEmailId());
23582 ashik.ali 1334
		customerRepository.persist(customer);
1335
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
25101 amit.gupta 1336
		if (!customerAddress.getState().equals(customCustomer.getAddress().getState())) {
1337
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1338
			resetTaxation(fofoOrder.getFofoId(), customerAddress, fofoOrderItems);
1339
		}
23582 ashik.ali 1340
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1341
		customerAddressRepository.persist(customerAddress);
24121 govind 1342
		fofoOrder.setCustomerGstNumber(customCustomer.getGstNumber());
23582 ashik.ali 1343
	}
23418 ashik.ali 1344
 
25101 amit.gupta 1345
	private void resetTaxation(int fofoId, CustomerAddress customerAddress, List<FofoOrderItem> fofoOrderItems)
1346
			throws ProfitMandiBusinessException {
1347
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
1348
 
1349
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
1350
 
1351
		Integer stateId = null;
1352
		if (customerAddress.getState().equals(retailerAddress.getState())) {
1353
			try {
1354
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
1355
			} catch (Exception e) {
1356
				LOGGER.error("Unable to get state rates");
1357
			}
1358
		}
1359
		List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
1360
		final Map<Integer, GstRate> gstRates;
1361
		if (stateId != null) {
1362
			gstRates = Utils.getStateTaxRate(itemIds, stateId);
1363
		} else {
1364
			gstRates = new HashMap<>();
1365
			Utils.getIgstTaxRate(itemIds).entrySet().forEach(x -> {
1366
				GstRate gstRate = new GstRate();
1367
				gstRate.setIgstRate(x.getValue());
1368
				gstRate.setCgstRate(0f);
1369
				gstRate.setSgstRate(0f);
1370
				gstRates.put(x.getKey(), gstRate);
1371
 
1372
			});
1373
		}
1374
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1375
			GstRate rate = gstRates.get(fofoOrderItem.getItemId());
1376
			fofoOrderItem.setCgstRate(rate.getCgstRate());
1377
			fofoOrderItem.setSgstRate(rate.getSgstRate());
1378
			fofoOrderItem.setIgstRate(rate.getIgstRate());
1379
		}
1380
	}
1381
 
23638 amit.gupta 1382
	@Override
24275 amit.gupta 1383
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest)
1384
			throws ProfitMandiBusinessException {
23655 amit.gupta 1385
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1386
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1387
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1388
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1389
		}
23655 amit.gupta 1390
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
24275 amit.gupta 1391
		if (foiBadReturnRequest.getMarkedBadArr().size() > billedQty) {
23655 amit.gupta 1392
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1393
		}
23650 amit.gupta 1394
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1395
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1396
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1397
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1398
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
24264 amit.gupta 1399
			customerReturnItem.setFofoOrderId(fofoOrder.getId());
23655 amit.gupta 1400
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1401
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1402
			customerReturnItem.setQuantity(1);
1403
			customerReturnItem.setType(ReturnType.BAD);
24275 amit.gupta 1404
			// customerReturnItemRepository.persist(customerReturnItem);
23650 amit.gupta 1405
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1406
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1407
		}
23655 amit.gupta 1408
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
24275 amit.gupta 1409
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1410
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(),
1411
					ReturnType.BAD);
23655 amit.gupta 1412
		}
24275 amit.gupta 1413
		return creditNote;
23638 amit.gupta 1414
	}
1415
 
24275 amit.gupta 1416
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems)
1417
			throws ProfitMandiBusinessException {
23650 amit.gupta 1418
 
23638 amit.gupta 1419
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1420
				.selectByFofoId(fofoOrder.getFofoId());
1421
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1422
		invoiceNumberGenerationSequenceRepository.persist(sequence);
24275 amit.gupta 1423
 
23655 amit.gupta 1424
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1425
		CustomerCreditNote creditNote = new CustomerCreditNote();
1426
		creditNote.setCreditNoteNumber(creditNoteNumber);
1427
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1428
		creditNote.setFofoOrderId(fofoOrder.getId());
1429
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1430
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1431
		customerCreditNoteRepository.persist(creditNote);
24275 amit.gupta 1432
 
23650 amit.gupta 1433
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1434
			customerReturnItem.setCreditNoteId(creditNote.getId());
1435
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1436
		}
24275 amit.gupta 1437
		// this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1438
 
23655 amit.gupta 1439
		return creditNote;
23650 amit.gupta 1440
	}
24275 amit.gupta 1441
 
23655 amit.gupta 1442
	@Override
1443
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1444
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1445
		return getCreditNotePdfModel(creditNote);
1446
	}
24275 amit.gupta 1447
 
1448
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote)
1449
			throws ProfitMandiBusinessException {
23655 amit.gupta 1450
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
24275 amit.gupta 1451
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository
1452
				.selectAllByCreditNoteId(creditNote.getId());
23655 amit.gupta 1453
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
24275 amit.gupta 1454
 
23655 amit.gupta 1455
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
24275 amit.gupta 1456
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoOrder.getFofoId()))
1457
				.get(fofoOrder.getFofoId());
23655 amit.gupta 1458
 
1459
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1460
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1461
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1462
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1463
 
1464
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1465
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1466
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1467
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
24275 amit.gupta 1468
 
1469
		if (ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())) {
23655 amit.gupta 1470
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1471
					.collect(Collectors.toSet());
1472
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1473
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1474
			customFofoOrderItem.setDescription(
1475
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1476
		}
24275 amit.gupta 1477
 
23655 amit.gupta 1478
		customFofoOrderItem.setRate(taxableSellingPrice);
1479
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1480
		customFofoOrderItem.setQuantity(customerReturnItems.size());
24275 amit.gupta 1481
		customFofoOrderItem.setNetAmount(
1482
				(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
23655 amit.gupta 1483
 
1484
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1485
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1486
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1487
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1488
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1489
		customFofoOrderItem.setIgstAmount(igstAmount);
1490
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1491
		customFofoOrderItem.setCgstAmount(cgstAmount);
1492
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1493
		customFofoOrderItem.setSgstAmount(sgstAmount);
1494
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1495
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1496
		customerFofoOrderItems.add(customFofoOrderItem);
24275 amit.gupta 1497
 
23650 amit.gupta 1498
		PdfModel pdfModel = new PdfModel();
1499
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1500
		pdfModel.setCustomer(customCustomer);
1501
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1502
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1503
		pdfModel.setTitle("Credit Note");
1504
		pdfModel.setRetailer(customRetailer);
1505
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1506
		pdfModel.setOrderItems(customerFofoOrderItems);
24275 amit.gupta 1507
 
23650 amit.gupta 1508
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1509
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1510
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1511
		creditNotePdfModel.setPdfModel(pdfModel);
1512
		return creditNotePdfModel;
1513
	}
23638 amit.gupta 1514
 
24275 amit.gupta 1515
	// This will remove the order and maintain order record and reverse inventory
1516
	// and scheme
24264 amit.gupta 1517
	@Override
1518
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
24275 amit.gupta 1519
		for (String invoiceNumber : invoiceNumbers) {
24264 amit.gupta 1520
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1521
			fofoOrder.setCancelledTimestamp(LocalDateTime.now());
1522
			fofoOrderRepository.persist(fofoOrder);
24275 amit.gupta 1523
			List<PaymentOptionTransaction> paymentTransactions = paymentOptionTransactionRepository
1524
					.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
24264 amit.gupta 1525
			for (PaymentOptionTransaction paymentOptionTransaction : paymentTransactions) {
1526
				paymentOptionTransactionRepository.delete(paymentOptionTransaction);
1527
			}
1528
			List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1529
			List<InventoryItem> inventoryItems = new ArrayList<>();
24275 amit.gupta 1530
			fois.stream().forEach(x -> {
1531
				x.getFofoLineItems().stream().forEach(y -> {
24264 amit.gupta 1532
					inventoryService.rollbackInventory(y.getInventoryItemId(), y.getQuantity(), fofoOrder.getFofoId());
1533
					inventoryItems.add(inventoryItemRepository.selectById(y.getInventoryItemId()));
1534
				});
1535
			});
1536
			String reversalReason = "Order Rolledback/Cancelled for Invoice Number " + invoiceNumber;
1537
			schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, SchemeType.OUT);
1538
		}
1539
	}
1540
 
24271 amit.gupta 1541
	@Override
1542
	public float getSales(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
24287 amit.gupta 1543
		Float sales = fofoOrderRepository.selectSaleSumGroupByFofoIds(startDate, endDate).get(fofoId);
24285 amit.gupta 1544
		return sales == null ? 0f : sales;
24271 amit.gupta 1545
	}
1546
 
1547
	@Override
1548
	public float getSales(int fofoId, LocalDate onDate) {
24285 amit.gupta 1549
		LocalDateTime startTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT);
1550
		LocalDateTime endTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT).plusDays(1);
1551
		return this.getSales(fofoId, startTime, endTime);
24271 amit.gupta 1552
	}
1553
 
1554
	@Override
1555
	public float getSales(LocalDateTime onDate) {
1556
		// TODO Auto-generated method stub
1557
		return 0;
1558
	}
1559
 
1560
	@Override
1561
	public float getSales(LocalDateTime startDate, LocalDateTime endDate) {
1562
		// TODO Auto-generated method stub
1563
		return 0;
1564
	}
1565
 
24917 tejbeer 1566
	@Override
1567
	public boolean notifyColorChange(int orderId, int itemId) throws ProfitMandiBusinessException {
1568
		Order order = orderRepository.selectById(orderId);
25724 amit.gupta 1569
		inventoryService.reservationCountByColor(itemId, order);
25101 amit.gupta 1570
 
1571
		order.getLineItem().setItemId(itemId);
1572
		Item item = itemRepository.selectById(itemId);
24917 tejbeer 1573
		order.getLineItem().setColor(item.getColor());
1574
		return true;
1575
	}
1576
 
25083 amit.gupta 1577
	@Override
1578
	public FofoOrder getOrderByInventoryItemId(int inventoryItemId) throws Exception {
1579
		List<FofoLineItem> lineItems = fofoLineItemRepository.selectByInventoryItemId(inventoryItemId);
25101 amit.gupta 1580
		if (lineItems.size() > 0) {
25083 amit.gupta 1581
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(lineItems.get(0).getFofoOrderItemId());
1582
			fofoOrderItem.setFofoLineItems(new HashSet<>(lineItems));
1583
			FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderItem.getOrderId());
1584
			fofoOrder.setOrderItem(fofoOrderItem);
1585
			return fofoOrder;
1586
		} else {
1587
			throw new Exception(String.format("Could not find inventoryItemId - %s", inventoryItemId));
1588
		}
1589
	}
25724 amit.gupta 1590
}