Subversion Repositories SmartDukaan

Rev

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