Subversion Repositories SmartDukaan

Rev

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