Subversion Repositories SmartDukaan

Rev

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