Subversion Repositories SmartDukaan

Rev

Rev 27522 | Rev 27734 | 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");
524
			LocalDate customerDateOfBirth = LocalDate.from(createOrderRequest.getCustomer().getDateOfBirth());
25724 amit.gupta 525
			fofoOrder.setDateOfBirth(customerDateOfBirth);
526
			for (InsuranceModel insuranceModel : insuredModels) {
527
				try {
528
					insuranceService.createInsurance(fofoOrder, insuranceModel);
529
				} catch (Exception e) {
530
					e.printStackTrace();
531
					throw new ProfitMandiBusinessException("Insurance creation", insuranceModel,
532
							"Failed to create insurance");
24440 amit.gupta 533
				}
22859 ashik.ali 534
			}
535
		}
25686 amit.gupta 536
		schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
22859 ashik.ali 537
		return fofoOrder.getId();
538
	}
23650 amit.gupta 539
 
25640 tejbeer 540
	private HygieneData createAndGetHygieneData(int id, int fofoId) {
541
		HygieneData hygieneData = new HygieneData();
542
		hygieneData.setOrderId(id);
543
		hygieneData.setFofoId(fofoId);
544
		hygieneData.setCreatedTimestamp(LocalDateTime.now());
545
		hygieneDataRepository.persist(hygieneData);
546
 
547
		return hygieneData;
548
	}
549
 
24807 amit.gupta 550
	@Override
551
	public String getInvoiceNumber(int fofoId, String fofoStoreCode) {
24236 amit.gupta 552
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
553
		try {
554
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
555
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
556
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
557
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
558
			invoiceNumberGenerationSequence.setFofoId(fofoId);
559
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
560
			invoiceNumberGenerationSequence.setSequence(1);
561
		}
562
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
563
		return invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence();
564
	}
24275 amit.gupta 565
 
566
	private String getSecurityDepositNumber(int fofoId, String fofoStoreCode) {
24226 amit.gupta 567
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
568
		try {
569
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
24275 amit.gupta 570
			invoiceNumberGenerationSequence
571
					.setChallanNumberSequence(invoiceNumberGenerationSequence.getChallanNumberSequence() + 1);
24226 amit.gupta 572
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
573
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
574
			invoiceNumberGenerationSequence.setFofoId(fofoId);
575
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
576
			invoiceNumberGenerationSequence.setChallanNumberSequence(1);
577
		}
578
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
24275 amit.gupta 579
		return invoiceNumberGenerationSequence.getPrefix() + "/SEC"
580
				+ invoiceNumberGenerationSequence.getChallanNumberSequence();
24226 amit.gupta 581
	}
582
 
23650 amit.gupta 583
	private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails) {
23377 ashik.ali 584
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 585
		for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
586
			if (serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
23377 ashik.ali 587
				serialNumbers.add(serialNumberDetail.getSerialNumber());
588
			}
589
		}
590
		return serialNumbers;
591
	}
23650 amit.gupta 592
 
22859 ashik.ali 593
	@Override
23596 ashik.ali 594
	public PdfModel getInvoicePdfModel(int orderId) throws ProfitMandiBusinessException {
595
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
596
		return this.getInvoicePdfModel(fofoOrder);
597
	}
23650 amit.gupta 598
 
27516 amit.gupta 599
	@Override
600
	@Cacheable(value = "order.dummymodel", cacheManager = "oneDayCacheManager")
601
	public PdfModel getDummyPdfModel(String serialNumber) throws ProfitMandiBusinessException {
602
		List<WarehouseInventoryItem> warehouseInventoryItems = warehouseInventoryItemRepository
603
				.selectWarehouseInventoryItemBySerailNumbers(Arrays.asList(serialNumber));
604
		if (warehouseInventoryItems.size() > 0) {
605
			WarehouseInventoryItem warehouseInventoryItem = warehouseInventoryItems.get(0);
606
			int currentQuantity = warehouseInventoryItems.get(0).getCurrentQuantity();
607
			if (currentQuantity > 0) {
608
				throw new ProfitMandiBusinessException("Serial Number", serialNumber,
609
						"Serial Number exist in our warehouse");
610
			} else {
611
				try {
612
					InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(serialNumber);
613
					if (inventoryItem.getGoodQuantity() > 0) {
614
						throw new ProfitMandiBusinessException("Serial Number", serialNumber,
615
								"Serial Number is not yet billed by the partner");
616
					} else {
617
						List<ScanRecord> scanRecords = scanRecordRepository
618
								.selectByInventoryItemId(inventoryItem.getId());
619
						Optional<ScanRecord> scanRecord = scanRecords.stream().filter(x -> x.getOrderId() != 0)
620
								.findFirst();
621
						if (scanRecord.isPresent()) {
622
							FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.get().getOrderId());
27522 amit.gupta 623
							orderIdsConsumed.add(fofoOrder.getId());
27516 amit.gupta 624
							return this.getInvoicePdfModel(fofoOrder);
625
						} else {
626
							throw new ProfitMandiBusinessException("Serial Number", serialNumber,
627
									"Serial Number returned by partner, but in transit");
628
						}
629
					}
630
				} catch (Exception e) {
631
					// Map this serialNumber for dummy billing
632
					int itemId = warehouseInventoryItem.getItemId();
633
					LocalDateTime grnDate = warehouseInventoryItem.getCreated();
634
					Random random = new Random();
635
					int randomDays = random.ints(2, 15).findFirst().getAsInt();
636
					LocalDateTime saleDate = grnDate.plusDays(randomDays);
27521 amit.gupta 637
					if(saleDate.isAfter(LocalDate.now().atStartOfDay())) {
638
						saleDate = LocalDateTime.now().minusDays(2);
639
					}
27522 amit.gupta 640
					Random offsetRandom = new Random();
641
					int offset = offsetRandom.ints(2, 100).findFirst().getAsInt();
642
					FofoOrder fofoOrder = fofoOrderRepository.selectFirstOrderAfterDate(saleDate, offset);
643
					while (orderIdsConsumed.contains(fofoOrder.getId())) {
644
						Random offsetRandom2 = new Random();
645
						int offset2 = offsetRandom2.ints(2, 100).findFirst().getAsInt();
646
						FofoOrder fofoOrder2 = fofoOrderRepository.selectFirstOrderAfterDate(saleDate, offset2);
647
						if(fofoOrder2 != null) {
648
							fofoOrder = fofoOrder2;
649
						}
650
					}
27516 amit.gupta 651
					PdfModel pdfModel = this.getInvoicePdfModel(fofoOrder.getId());
27523 amit.gupta 652
					orderIdsConsumed.add(fofoOrder.getId());
27516 amit.gupta 653
					this.modifyDummyModel(fofoOrder, pdfModel, itemId, serialNumber);
654
					return pdfModel;
655
 
656
				}
657
			}
658
		} else {
659
			throw new ProfitMandiBusinessException("Serial Number", serialNumber,
660
					"Serial Number does not exist in our warehouse");
661
		}
662
	}
663
 
664
	void modifyDummyModel(FofoOrder fofoOrder, PdfModel pdfModel, int itemId, String serialNumber) throws ProfitMandiBusinessException {
665
 
666
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoOrder.getFofoId());
667
 
668
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
669
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
670
 
671
		CustomerAddress customerAddress = customer.getCustomerAddress().stream()
672
				.filter(x -> x.getId() == fofoOrder.getCustomerAddressId()).findFirst().get();
673
 
674
 
675
		Integer stateId = null;
676
		if (customerAddress.getState().equals(retailerAddress.getState())) {
677
			try {
678
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
679
			} catch (Exception e) {
680
				LOGGER.error("Unable to get state rates");
681
			}
682
		}
683
		CustomOrderItem cli = pdfModel.getOrderItems().stream().findFirst().get();
684
		List<FofoOrderItem> fofoOrderItems = Arrays.asList(this.getDummyFofoOrderItem(itemId, fofoOrder.getId(), serialNumber, stateId));
685
 
686
		CustomPaymentOption paymentOption = pdfModel.getPaymentOptions().get(0);
687
		paymentOption.setAmount(fofoOrderItems.get(0).getMop());
688
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
689
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
690
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
691
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate()
692
					+ fofoOrderItem.getCgstRate();
693
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
694
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
695
 
696
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
697
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
698
					+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
699
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
700
			// LOGGER.info("serialNumbers {}", serialNumbers);
701
			// LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
702
			if (!serialNumbers.isEmpty()) {
703
				customFofoOrderItem.setDescription(
704
						customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
705
			}
706
			customFofoOrderItem.setRate(taxableSellingPrice);
707
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
708
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
709
			customFofoOrderItem.setNetAmount(
710
					(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
711
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
712
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
713
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
714
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
715
			customFofoOrderItem.setIgstAmount(igstAmount);
716
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
717
			customFofoOrderItem.setCgstAmount(cgstAmount);
718
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
719
			customFofoOrderItem.setSgstAmount(sgstAmount);
720
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
721
			customerFofoOrderItems.add(customFofoOrderItem);
722
		}
723
		pdfModel.setOrderItems(customerFofoOrderItems);
724
 
725
	}
726
 
23650 amit.gupta 727
	private PdfModel getInvoicePdfModel(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
728
 
729
		List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
730
				.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
731
 
23552 amit.gupta 732
		List<CustomPaymentOption> paymentOptions = new ArrayList<>();
733
 
22859 ashik.ali 734
		PdfModel pdfModel = new PdfModel();
24823 amit.gupta 735
		pdfModel.setCancelled(fofoOrder.getCancelledTimestamp() != null);
23650 amit.gupta 736
		for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
23552 amit.gupta 737
			CustomPaymentOption cpi = new CustomPaymentOption();
738
			cpi.setAmount(paymentOptionTransaction.getAmount());
23650 amit.gupta 739
			cpi.setPaymentOption(
740
					paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());
23558 amit.gupta 741
			paymentOptions.add(cpi);
23552 amit.gupta 742
		}
24215 amit.gupta 743
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
744
 
745
		pdfModel.setTitle("Retailer Invoice");
24275 amit.gupta 746
		if (fofoOrderItems.stream().findAny().get().getHsnCode().equals("NOGST")) {
24215 amit.gupta 747
			pdfModel.setTitle("Security Deposit Receipt");
748
		}
23552 amit.gupta 749
		pdfModel.setPaymentOptions(paymentOptions);
24215 amit.gupta 750
		pdfModel.setAuther("SmartDukaan");
24400 amit.gupta 751
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
23650 amit.gupta 752
 
22859 ashik.ali 753
		// insurance calculation
23650 amit.gupta 754
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository
755
				.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
22859 ashik.ali 756
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
757
		final float totalInsuranceTaxRate = 18;
23650 amit.gupta 758
		for (InsurancePolicy insurancePolicy : insurancePolicies) {
22859 ashik.ali 759
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
760
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
23650 amit.gupta 761
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #"
762
					+ insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
22859 ashik.ali 763
			customInsurancePolicy.setHsnCode("998716");
764
			customInsurancePolicy.setRate(taxableInsurancePrice);
765
			customInsurancePolicy.setIgstRate(18);
23650 amit.gupta 766
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
22936 amit.gupta 767
			customInsurancePolicy.setCgstRate(9);
23650 amit.gupta 768
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
22859 ashik.ali 769
			customInsurancePolicy.setSgstRate(9);
23650 amit.gupta 770
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
22859 ashik.ali 771
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
772
			customInsurancePolicies.add(customInsurancePolicy);
773
		}
774
		pdfModel.setInsurancePolicies(customInsurancePolicies);
23001 amit.gupta 775
		List<String> tncs = new ArrayList<>();
776
		tncs.add("I agree that goods received are in good working condition");
777
		tncs.add("Goods once sold cannot be exchanged or taken back");
778
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
27083 amit.gupta 779
		tncs.add(
780
				"Tempered Glass Replacement will be done only for the Mobile Phone which was purchased from SmartDukaan");
781
		tncs.add(
782
				"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 783
		tncs.add("Service fee of Rs.20 will be chargeable for each Tempered Glass Replacement");
23650 amit.gupta 784
		if (pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
785
			tncs.add("Damage protection provided is the responisibility of Protection Provider only");
786
		}
23001 amit.gupta 787
		pdfModel.setTncs(tncs);
24275 amit.gupta 788
 
23655 amit.gupta 789
		pdfModel.setCustomer(getCustomCustomer(fofoOrder));
22859 ashik.ali 790
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
791
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
23650 amit.gupta 792
 
23596 ashik.ali 793
		Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
22859 ashik.ali 794
		PrivateDealUser privateDealUser = null;
23650 amit.gupta 795
		try {
22859 ashik.ali 796
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23650 amit.gupta 797
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
22859 ashik.ali 798
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
799
		}
23650 amit.gupta 800
 
22859 ashik.ali 801
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
802
		CustomRetailer customRetailer = new CustomRetailer();
803
		customRetailer.setBusinessName(retailer.getName());
804
		customRetailer.setMobileNumber(user.getMobileNumber());
23650 amit.gupta 805
		// customRetailer.setTinNumber(retailer.getNumber());
806
		if (privateDealUser == null) {
22859 ashik.ali 807
			customRetailer.setGstNumber(null);
23650 amit.gupta 808
		} else {
809
			if (null != privateDealUser.getCounterId()) {
22859 ashik.ali 810
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
811
				customRetailer.setGstNumber(counter.getGstin());
23650 amit.gupta 812
			} else {
22859 ashik.ali 813
				customRetailer.setGstNumber(null);
814
			}
815
		}
23650 amit.gupta 816
		Address retailerAddress = addressRepository
817
				.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
22859 ashik.ali 818
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
819
		pdfModel.setRetailer(customRetailer);
23650 amit.gupta 820
 
22859 ashik.ali 821
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
23650 amit.gupta 822
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
22859 ashik.ali 823
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
23650 amit.gupta 824
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate()
825
					+ fofoOrderItem.getCgstRate();
22859 ashik.ali 826
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
827
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
23650 amit.gupta 828
 
22859 ashik.ali 829
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
23650 amit.gupta 830
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
831
					+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
23377 ashik.ali 832
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
23650 amit.gupta 833
			// LOGGER.info("serialNumbers {}", serialNumbers);
834
			// LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
835
			if (!serialNumbers.isEmpty()) {
836
				customFofoOrderItem.setDescription(
837
						customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
23377 ashik.ali 838
			}
22859 ashik.ali 839
			customFofoOrderItem.setRate(taxableSellingPrice);
840
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
841
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
23650 amit.gupta 842
			customFofoOrderItem.setNetAmount(
843
					(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
22859 ashik.ali 844
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
845
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
846
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
847
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
848
			customFofoOrderItem.setIgstAmount(igstAmount);
849
			customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
850
			customFofoOrderItem.setCgstAmount(cgstAmount);
851
			customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
852
			customFofoOrderItem.setSgstAmount(sgstAmount);
853
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
854
			customerFofoOrderItems.add(customFofoOrderItem);
855
		}
856
		pdfModel.setOrderItems(customerFofoOrderItems);
24917 tejbeer 857
		String partnerAddressStateCode = stateRepository.selectByName(pdfModel.getRetailer().getAddress().getState())
858
				.getCode();
859
		String customerAddressStateCode = stateRepository.selectByName(pdfModel.getCustomer().getAddress().getState())
860
				.getCode();
24854 amit.gupta 861
		pdfModel.setPartnerAddressStateCode(partnerAddressStateCode);
862
		pdfModel.setCustomerAddressStateCode(customerAddressStateCode);
22859 ashik.ali 863
		return pdfModel;
23650 amit.gupta 864
 
22859 ashik.ali 865
	}
23650 amit.gupta 866
 
23655 amit.gupta 867
	private CustomCustomer getCustomCustomer(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
868
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
869
		CustomCustomer customCustomer = new CustomCustomer();
870
		customCustomer.setFirstName(customer.getFirstName());
871
		customCustomer.setLastName(customer.getLastName());
872
		customCustomer.setEmailId(customer.getEmailId());
873
		customCustomer.setMobileNumber(customer.getMobileNumber());
874
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
875
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
876
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
877
		return customCustomer;
878
	}
879
 
23596 ashik.ali 880
	@Override
881
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
882
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
883
		return this.getInvoicePdfModel(fofoOrder);
884
	}
23650 amit.gupta 885
 
22859 ashik.ali 886
	public String getBillingAddress(CustomerAddress customerAddress) {
887
		StringBuilder address = new StringBuilder();
888
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
889
			address.append(customerAddress.getLine1());
890
			address.append(", ");
891
		}
892
 
893
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
894
			address.append(customerAddress.getLine2());
895
			address.append(", ");
896
		}
897
 
898
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
899
			address.append(customerAddress.getLandmark());
900
			address.append(", ");
901
		}
902
 
903
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
904
			address.append(customerAddress.getCity());
905
			address.append(", ");
906
		}
907
 
908
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
909
			address.append(customerAddress.getState());
910
		}
911
 
912
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
913
			address.append("- ");
914
			address.append(customerAddress.getPinCode());
915
		}
916
 
917
		return address.toString();
918
	}
23650 amit.gupta 919
 
22859 ashik.ali 920
	@Override
23650 amit.gupta 921
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException {
922
		try {
22859 ashik.ali 923
			JSONObject cartObject = new JSONObject(cartJson);
924
			Iterator<?> keys = cartObject.keys();
23650 amit.gupta 925
 
22859 ashik.ali 926
			Set<Integer> itemIds = new HashSet<>();
927
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
23650 amit.gupta 928
 
929
			while (keys.hasNext()) {
930
				String key = (String) keys.next();
931
				if (cartObject.get(key) instanceof JSONObject) {
22859 ashik.ali 932
					LOGGER.info(cartObject.get(key).toString());
933
				}
934
				CartFofo cf = new CartFofo();
935
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
936
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
23650 amit.gupta 937
 
938
				if (cf.getQuantity() <= 0) {
22859 ashik.ali 939
					continue;
940
				}
941
				cartItems.add(cf);
942
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
943
			}
23650 amit.gupta 944
			Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
945
			if (itemIds.size() > 0) {
22859 ashik.ali 946
				List<Item> items = itemRepository.selectByIds(itemIds);
23650 amit.gupta 947
				for (Item i : items) {
22859 ashik.ali 948
					itemMap.put(i.getId(), i);
949
				}
23650 amit.gupta 950
 
22859 ashik.ali 951
			}
23650 amit.gupta 952
			for (CartFofo cf : cartItems) {
22859 ashik.ali 953
				Item i = itemMap.get(cf.getItemId());
23650 amit.gupta 954
				if (i == null) {
22859 ashik.ali 955
					continue;
956
				}
23650 amit.gupta 957
				cf.setDisplayName(getValidName(i.getBrand()) + " " + getValidName(i.getModelName()) + " "
958
						+ getValidName(i.getModelNumber()) + " " + getValidName(i.getColor()).replaceAll("\\s+", " "));
22859 ashik.ali 959
				cf.setItemType(i.getType());
960
			}
961
			return cartItems;
23650 amit.gupta 962
		} catch (Exception e) {
22859 ashik.ali 963
			LOGGER.error("Unable to Prepare cart to place order...", e);
22925 ashik.ali 964
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
22859 ashik.ali 965
		}
966
	}
23650 amit.gupta 967
 
23202 ashik.ali 968
	@Override
23650 amit.gupta 969
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue,
23891 amit.gupta 970
			LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 971
		long countItems = 0;
972
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 973
 
974
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
24275 amit.gupta 975
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, null, null,
976
					offset, limit);
977
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, null, null);
23650 amit.gupta 978
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 979
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, null, null, offset,
980
					limit);
23973 govind 981
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, null, null);
23650 amit.gupta 982
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
24275 amit.gupta 983
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, null, null, offset,
984
					limit);
23973 govind 985
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, null, null);
23650 amit.gupta 986
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 987
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, null, null, offset, limit);
988
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, null, null);
23953 amit.gupta 989
		} else if (searchType == SearchType.INVOICE_NUMBER && !searchValue.isEmpty()) {
990
			fofoOrders = Arrays.asList(fofoOrderRepository.selectByFofoIdAndInvoiceNumber(fofoId, searchValue));
991
			countItems = fofoOrders.size();
24275 amit.gupta 992
		} else if (searchType == SearchType.DATE_RANGE) {
23891 amit.gupta 993
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
994
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDate, endDate);
23202 ashik.ali 995
		}
996
		Map<String, Object> map = new HashMap<>();
23650 amit.gupta 997
 
23202 ashik.ali 998
		map.put("saleHistories", fofoOrders);
999
		map.put("start", offset + 1);
1000
		map.put("size", countItems);
1001
		map.put("searchType", searchType);
23351 ashik.ali 1002
		map.put("searchTypes", SearchType.values());
23891 amit.gupta 1003
		map.put("startDate", startDate);
23973 govind 1004
		map.put("searchValue", searchValue);
23891 amit.gupta 1005
		map.put(ProfitMandiConstants.END_TIME, endDate);
23650 amit.gupta 1006
		if (fofoOrders.size() < limit) {
23202 ashik.ali 1007
			map.put("end", offset + fofoOrders.size());
23650 amit.gupta 1008
		} else {
23202 ashik.ali 1009
			map.put("end", offset + limit);
1010
		}
1011
		return map;
1012
	}
1013
 
1014
	@Override
23650 amit.gupta 1015
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue,
23891 amit.gupta 1016
			LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
23202 ashik.ali 1017
		List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 1018
 
1019
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
23891 amit.gupta 1020
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDate,
1021
					endDate, offset, limit);
23650 amit.gupta 1022
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 1023
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDate, endDate,
1024
					offset, limit);
23650 amit.gupta 1025
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
24275 amit.gupta 1026
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDate, endDate,
1027
					offset, limit);
23650 amit.gupta 1028
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
24275 amit.gupta 1029
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDate, endDate, offset,
1030
					limit);
1031
 
1032
		} else if (searchType == SearchType.DATE_RANGE) {
23891 amit.gupta 1033
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
23202 ashik.ali 1034
		}
1035
		Map<String, Object> map = new HashMap<>();
1036
		map.put("saleHistories", fofoOrders);
23973 govind 1037
		map.put("searchType", searchType);
1038
		map.put("searchTypes", SearchType.values());
1039
		map.put("startDate", startDate);
1040
		map.put("searchValue", searchValue);
1041
		map.put(ProfitMandiConstants.END_TIME, endDate);
23202 ashik.ali 1042
		return map;
1043
	}
23650 amit.gupta 1044
 
1045
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
23202 ashik.ali 1046
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
23370 ashik.ali 1047
		return fofoStore.getCode();
23202 ashik.ali 1048
	}
23650 amit.gupta 1049
 
1050
	private String getValidName(String name) {
1051
		return name != null ? name : "";
22859 ashik.ali 1052
	}
23650 amit.gupta 1053
 
1054
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
23377 ashik.ali 1055
		Set<String> serialNumbers = new HashSet<>();
23650 amit.gupta 1056
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1057
			if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
23377 ashik.ali 1058
				serialNumbers.add(fofoLineItem.getSerialNumber());
22955 ashik.ali 1059
			}
23377 ashik.ali 1060
		}
1061
		return serialNumbers;
22859 ashik.ali 1062
	}
23650 amit.gupta 1063
 
23823 amit.gupta 1064
	private void validateDpPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1065
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
1066
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoLineItemMap.entrySet()) {
1067
			int itemId = entry.getKey();
1068
			CustomFofoOrderItem customFofoOrderItem = entry.getValue();
1069
			PriceModel priceModel = itemIdMopPriceMap.get(itemId);
25494 amit.gupta 1070
			if (customFofoOrderItem.getSerialNumberDetails().stream()
25499 amit.gupta 1071
					.filter(x -> org.apache.commons.lang.StringUtils.isNotEmpty(x.getSerialNumber()))
25494 amit.gupta 1072
					.collect(Collectors.toList()).size() > 0) {
24275 amit.gupta 1073
				if (priceModel.getPrice() > customFofoOrderItem.getSellingPrice()) {
25495 amit.gupta 1074
					throw new ProfitMandiBusinessException("Selling Price for ",
24275 amit.gupta 1075
							itemRepository.selectById(itemId).getItemDescription(), "FFORDR_1010");
23823 amit.gupta 1076
				}
1077
			} else {
24275 amit.gupta 1078
				if (priceModel.getPurchasePrice() > customFofoOrderItem.getSellingPrice()) {
1079
					throw new ProfitMandiBusinessException("Selling Price",
1080
							itemRepository.selectById(itemId).getItemDescription(),
1081
							"Selling Price should not be less than DP");
23823 amit.gupta 1082
				}
1083
			}
1084
		}
1085
	}
24275 amit.gupta 1086
 
23650 amit.gupta 1087
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1088
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
22859 ashik.ali 1089
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
23650 amit.gupta 1090
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
22872 ashik.ali 1091
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
25102 amit.gupta 1092
			if (customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
22872 ashik.ali 1093
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
22859 ashik.ali 1094
			}
1095
		}
23650 amit.gupta 1096
 
1097
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1098
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
1099
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
22925 ashik.ali 1100
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
22859 ashik.ali 1101
		}
23650 amit.gupta 1102
 
22859 ashik.ali 1103
	}
23650 amit.gupta 1104
 
1105
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
24264 amit.gupta 1106
			Map<Integer, Integer> inventoryItemQuantityUsed, int fofoOrderId) {
23650 amit.gupta 1107
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1108
			inventoryItem.setLastScanType(ScanType.SALE);
1109
			inventoryItemRepository.persist(inventoryItem);
1110
			ScanRecord scanRecord = new ScanRecord();
1111
			scanRecord.setInventoryItemId(inventoryItem.getId());
1112
			scanRecord.setFofoId(fofoId);
24264 amit.gupta 1113
			scanRecord.setOrderId(fofoOrderId);
23650 amit.gupta 1114
			// correct this
22859 ashik.ali 1115
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1116
			scanRecord.setType(ScanType.SALE);
1117
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1118
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1119
 
22859 ashik.ali 1120
		}
1121
	}
23650 amit.gupta 1122
 
1123
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1124
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1125
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1126
			FofoLineItem fofoLineItem = new FofoLineItem();
1127
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1128
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1129
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1130
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1131
			fofoLineItemRepository.persist(fofoLineItem);
1132
		}
1133
	}
23650 amit.gupta 1134
 
1135
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1136
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1137
			throws ProfitMandiBusinessException {
22859 ashik.ali 1138
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1139
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1140
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1141
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1142
		fofoOrderItem.setOrderId(fofoOrderId);
25103 amit.gupta 1143
		TagListing tl = tagListingRepository.selectByItemId(customFofoOrderItem.getItemId());
25162 amit.gupta 1144
		// In case listing gets removed rebill it using the selling price
1145
		if (tl != null) {
25103 amit.gupta 1146
			fofoOrderItem.setDp(tl.getSellingPrice());
26332 amit.gupta 1147
			fofoOrderItem.setMop(tl.getMop());
25103 amit.gupta 1148
		} else {
1149
			fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
26332 amit.gupta 1150
			fofoOrderItem.setMop(customFofoOrderItem.getSellingPrice());
25103 amit.gupta 1151
		}
22859 ashik.ali 1152
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
24823 amit.gupta 1153
 
22859 ashik.ali 1154
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1155
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1156
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1157
		if (stateId != null) {
26817 amit.gupta 1158
			itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1159
		} else {
26817 amit.gupta 1160
			itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
23172 ashik.ali 1161
		}
23650 amit.gupta 1162
		for (InventoryItem inventoryItem : inventoryItems) {
1163
			if (stateId == null) {
23172 ashik.ali 1164
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1165
			} else {
23172 ashik.ali 1166
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1167
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1168
			}
23650 amit.gupta 1169
 
22859 ashik.ali 1170
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1171
			break;
1172
		}
1173
		fofoOrderItem.setBrand(item.getBrand());
1174
		fofoOrderItem.setModelName(item.getModelName());
1175
		fofoOrderItem.setModelNumber(item.getModelNumber());
1176
		fofoOrderItem.setColor(item.getColor());
1177
		fofoOrderItemRepository.persist(fofoOrderItem);
1178
		return fofoOrderItem;
1179
	}
23650 amit.gupta 1180
 
27516 amit.gupta 1181
	private FofoOrderItem getDummyFofoOrderItem(int itemId, int fofoOrderId,
1182
			String serialNumber, Integer stateId) throws ProfitMandiBusinessException {
1183
		Item item = itemRepository.selectById(itemId);
1184
		TagListing tl = tagListingRepository.selectByItemId(itemId);
1185
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1186
		fofoOrderItem.setItemId(itemId);
1187
		fofoOrderItem.setQuantity(1);
1188
		fofoOrderItem.setSellingPrice(tl.getMop());
1189
		fofoOrderItem.setOrderId(fofoOrderId);
1190
		// In case listing gets removed rebill it using the selling price
1191
		fofoOrderItem.setDp(tl.getSellingPrice());
1192
		fofoOrderItem.setMop(tl.getMop());
1193
		fofoOrderItem.setDiscount(0);
1194
 
1195
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1196
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
1197
		if (stateId != null) {
1198
			itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(Arrays.asList(itemId), stateId);
1199
		} else {
1200
			itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId));
1201
		}
1202
 
1203
		if (stateId == null) {
1204
			fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(itemId));
1205
		} else {
1206
			fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(itemId).getCgstRate());
1207
			fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(itemId).getSgstRate());
1208
		}
1209
 
1210
		fofoOrderItem.setHsnCode(item.getHsnCode());
1211
		fofoOrderItem.setBrand(item.getBrand());
1212
		fofoOrderItem.setModelName(item.getModelName());
1213
		fofoOrderItem.setModelNumber(item.getModelNumber());
1214
		fofoOrderItem.setColor(item.getColor());
1215
 
1216
		Set<FofoLineItem> fofoLineItems = new HashSet<>();
1217
		FofoLineItem fli = new FofoLineItem();
1218
		fli.setQuantity(1);
1219
		fli.setSerialNumber(serialNumber);
1220
		fofoLineItems.add(fli);
1221
		fofoOrderItem.setFofoLineItems(fofoLineItems);
1222
 
1223
		return fofoOrderItem;
1224
	}
1225
 
23650 amit.gupta 1226
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1227
			int itemId, int quantity) throws ProfitMandiBusinessException {
1228
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1229
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1230
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1231
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1232
			}
1233
		}
1234
	}
23650 amit.gupta 1235
 
1236
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1237
			throws ProfitMandiBusinessException {
1238
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1239
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1240
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1241
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1242
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1243
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1244
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1245
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1246
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1247
			}
22859 ashik.ali 1248
		}
1249
	}
23650 amit.gupta 1250
 
24275 amit.gupta 1251
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber,
1252
			float totalAmount, int customerAddressId) {
22859 ashik.ali 1253
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1254
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1255
		fofoOrder.setCustomerId(customerId);
1256
		fofoOrder.setFofoId(fofoId);
24226 amit.gupta 1257
		fofoOrder.setInvoiceNumber(documentNumber);
22859 ashik.ali 1258
		fofoOrder.setTotalAmount(totalAmount);
1259
		fofoOrder.setCustomerAddressId(customerAddressId);
1260
		fofoOrderRepository.persist(fofoOrder);
1261
		return fofoOrder;
1262
	}
23650 amit.gupta 1263
 
1264
	private void validateItemsSerializedNonSerialized(List<Item> items,
1265
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1266
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1267
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1268
		for (Item i : items) {
22872 ashik.ali 1269
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1270
			if (i.getType().equals(ItemType.SERIALIZED)) {
1271
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1272
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1273
				}
23650 amit.gupta 1274
			} else {
1275
				Set<String> serialNumbers = this
1276
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1277
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1278
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1279
				}
1280
			}
1281
		}
1282
 
23650 amit.gupta 1283
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1284
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1285
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1286
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1287
					"FFORDR_1013");
22859 ashik.ali 1288
		}
1289
 
23650 amit.gupta 1290
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1291
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1292
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1293
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1294
					"FFORDR_1014");
22859 ashik.ali 1295
		}
1296
	}
23650 amit.gupta 1297
 
1298
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1299
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1300
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1301
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1302
		}
23650 amit.gupta 1303
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1304
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1305
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1306
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1307
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1308
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1309
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1310
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1311
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1312
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1313
				Quantity quantity = new Quantity();
1314
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1315
				quantity.setRequested(customFofoOrderItem.getQuantity());
1316
				itemIdQuantityAvailability.setQuantity(quantity);
1317
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1318
			}
22859 ashik.ali 1319
		}
1320
 
23650 amit.gupta 1321
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1322
			// itemIdQuantity request is not valid
23650 amit.gupta 1323
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1324
					itemIdQuantityAvailabilities);
1325
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1326
					"FFORDR_1015");
22859 ashik.ali 1327
		}
1328
	}
23650 amit.gupta 1329
 
1330
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1331
			String serialNumber) {
22872 ashik.ali 1332
		int itemId = 0;
23650 amit.gupta 1333
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1334
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1335
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1336
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1337
					itemId = entry.getKey();
1338
					break;
1339
				}
22859 ashik.ali 1340
			}
1341
		}
22872 ashik.ali 1342
		return itemId;
22859 ashik.ali 1343
	}
23650 amit.gupta 1344
 
1345
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1346
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1347
			@Override
1348
			public Integer apply(Item item) {
1349
				return item.getId();
1350
			}
1351
		};
1352
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1353
			@Override
1354
			public Item apply(Item item) {
1355
				return item;
1356
			}
1357
		};
1358
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1359
	}
1360
 
23650 amit.gupta 1361
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1362
		customerAddress.setName(customAddress.getName());
1363
		customerAddress.setLine1(customAddress.getLine1());
1364
		customerAddress.setLine2(customAddress.getLine2());
1365
		customerAddress.setLandmark(customAddress.getLandmark());
1366
		customerAddress.setCity(customAddress.getCity());
1367
		customerAddress.setPinCode(customAddress.getPinCode());
1368
		customerAddress.setState(customAddress.getState());
1369
		customerAddress.setCountry(customAddress.getCountry());
1370
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1371
	}
1372
 
23650 amit.gupta 1373
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1374
		CustomAddress customAddress = new CustomAddress();
1375
		customAddress.setName(address.getName());
1376
		customAddress.setLine1(address.getLine1());
1377
		customAddress.setLine2(address.getLine2());
1378
		customAddress.setLandmark(address.getLandmark());
1379
		customAddress.setCity(address.getCity());
1380
		customAddress.setPinCode(address.getPinCode());
1381
		customAddress.setState(address.getState());
1382
		customAddress.setCountry(address.getCountry());
1383
		customAddress.setPhoneNumber(address.getPhoneNumber());
1384
		return customAddress;
1385
	}
1386
 
23650 amit.gupta 1387
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1388
		CustomAddress customAddress = new CustomAddress();
1389
		customAddress.setName(customerAddress.getName());
26817 amit.gupta 1390
		customAddress.setLastName(customerAddress.getLastName());
22859 ashik.ali 1391
		customAddress.setLine1(customerAddress.getLine1());
1392
		customAddress.setLine2(customerAddress.getLine2());
1393
		customAddress.setLandmark(customerAddress.getLandmark());
1394
		customAddress.setCity(customerAddress.getCity());
1395
		customAddress.setPinCode(customerAddress.getPinCode());
1396
		customAddress.setState(customerAddress.getState());
1397
		customAddress.setCountry(customerAddress.getCountry());
1398
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1399
		return customAddress;
1400
	}
1401
 
23650 amit.gupta 1402
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1403
			throws ProfitMandiBusinessException {
23365 ashik.ali 1404
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1405
 
22859 ashik.ali 1406
		float calculatedAmount = 0;
23650 amit.gupta 1407
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1408
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1409
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1410
		}
23650 amit.gupta 1411
		if (calculatedAmount != totalAmount) {
1412
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
1413
					calculatedAmount, totalAmount);
1414
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1415
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1416
		}
23650 amit.gupta 1417
 
23365 ashik.ali 1418
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1419
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1420
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1421
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1422
					"FFORDR_1017");
23365 ashik.ali 1423
		}
22859 ashik.ali 1424
	}
23650 amit.gupta 1425
 
22925 ashik.ali 1426
	@Override
1427
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1428
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1429
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1430
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1431
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1432
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1433
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1434
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1435
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1436
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1437
				newFofoOrderItems.add(fofoOrderItem);
1438
				fofoOrderItemsIterator.remove();
1439
			}
1440
			fofoOrderItems = newFofoOrderItems;
1441
		}
1442
		return fofoOrderItems;
1443
	}
23650 amit.gupta 1444
 
1445
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1446
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1447
			@Override
1448
			public Integer apply(FofoOrderItem fofoOrderItem) {
1449
				return fofoOrderItem.getId();
1450
			}
1451
		};
1452
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1453
	}
23650 amit.gupta 1454
 
1455
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1456
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1457
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1458
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1459
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1460
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1461
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1462
				fofoLineItems2.add(fofoLineItem);
1463
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1464
			} else {
22925 ashik.ali 1465
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1466
			}
1467
		}
1468
		return fofoOrderItemIdFofoLineItemsMap;
1469
	}
23650 amit.gupta 1470
 
23418 ashik.ali 1471
	@Override
23650 amit.gupta 1472
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1473
			throws ProfitMandiBusinessException {
23582 ashik.ali 1474
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1475
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1476
		customer.setFirstName(customCustomer.getFirstName());
1477
		customer.setLastName(customCustomer.getLastName());
24121 govind 1478
		customer.setMobileNumber(customCustomer.getMobileNumber());
1479
		customer.setEmailId(customCustomer.getEmailId());
23582 ashik.ali 1480
		customerRepository.persist(customer);
1481
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
27411 amit.gupta 1482
		if (!customerAddress.getState().equalsIgnoreCase(customCustomer.getAddress().getState())) {
25101 amit.gupta 1483
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1484
			resetTaxation(fofoOrder.getFofoId(), customerAddress, fofoOrderItems);
1485
		}
23582 ashik.ali 1486
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1487
		customerAddressRepository.persist(customerAddress);
24121 govind 1488
		fofoOrder.setCustomerGstNumber(customCustomer.getGstNumber());
23582 ashik.ali 1489
	}
23418 ashik.ali 1490
 
25101 amit.gupta 1491
	private void resetTaxation(int fofoId, CustomerAddress customerAddress, List<FofoOrderItem> fofoOrderItems)
1492
			throws ProfitMandiBusinessException {
1493
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
1494
 
1495
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
1496
 
1497
		Integer stateId = null;
27411 amit.gupta 1498
		if (customerAddress.getState().equalsIgnoreCase(retailerAddress.getState())) {
25101 amit.gupta 1499
			try {
1500
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
1501
			} catch (Exception e) {
1502
				LOGGER.error("Unable to get state rates");
1503
			}
1504
		}
1505
		List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
1506
		final Map<Integer, GstRate> gstRates;
1507
		if (stateId != null) {
26817 amit.gupta 1508
			gstRates = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
25101 amit.gupta 1509
		} else {
1510
			gstRates = new HashMap<>();
26817 amit.gupta 1511
			stateGstRateRepository.getIgstTaxRate(itemIds).entrySet().forEach(x -> {
25101 amit.gupta 1512
				GstRate gstRate = new GstRate();
1513
				gstRate.setIgstRate(x.getValue());
1514
				gstRate.setCgstRate(0f);
1515
				gstRate.setSgstRate(0f);
1516
				gstRates.put(x.getKey(), gstRate);
1517
 
1518
			});
1519
		}
1520
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1521
			GstRate rate = gstRates.get(fofoOrderItem.getItemId());
1522
			fofoOrderItem.setCgstRate(rate.getCgstRate());
1523
			fofoOrderItem.setSgstRate(rate.getSgstRate());
1524
			fofoOrderItem.setIgstRate(rate.getIgstRate());
1525
		}
1526
	}
1527
 
23638 amit.gupta 1528
	@Override
24275 amit.gupta 1529
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest)
1530
			throws ProfitMandiBusinessException {
23655 amit.gupta 1531
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1532
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1533
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1534
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1535
		}
23655 amit.gupta 1536
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
24275 amit.gupta 1537
		if (foiBadReturnRequest.getMarkedBadArr().size() > billedQty) {
23655 amit.gupta 1538
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1539
		}
23650 amit.gupta 1540
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1541
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1542
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1543
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1544
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
24264 amit.gupta 1545
			customerReturnItem.setFofoOrderId(fofoOrder.getId());
23655 amit.gupta 1546
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1547
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1548
			customerReturnItem.setQuantity(1);
1549
			customerReturnItem.setType(ReturnType.BAD);
24275 amit.gupta 1550
			// customerReturnItemRepository.persist(customerReturnItem);
23650 amit.gupta 1551
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1552
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1553
		}
23655 amit.gupta 1554
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
24275 amit.gupta 1555
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1556
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(),
1557
					ReturnType.BAD);
23655 amit.gupta 1558
		}
27516 amit.gupta 1559
		// This should cancel the order
27409 amit.gupta 1560
		fofoOrder.setCancelledTimestamp(LocalDateTime.now());
24275 amit.gupta 1561
		return creditNote;
23638 amit.gupta 1562
	}
1563
 
24275 amit.gupta 1564
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems)
1565
			throws ProfitMandiBusinessException {
23650 amit.gupta 1566
 
23638 amit.gupta 1567
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1568
				.selectByFofoId(fofoOrder.getFofoId());
1569
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1570
		invoiceNumberGenerationSequenceRepository.persist(sequence);
24275 amit.gupta 1571
 
23655 amit.gupta 1572
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1573
		CustomerCreditNote creditNote = new CustomerCreditNote();
1574
		creditNote.setCreditNoteNumber(creditNoteNumber);
1575
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1576
		creditNote.setFofoOrderId(fofoOrder.getId());
1577
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1578
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1579
		customerCreditNoteRepository.persist(creditNote);
24275 amit.gupta 1580
 
23650 amit.gupta 1581
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1582
			customerReturnItem.setCreditNoteId(creditNote.getId());
1583
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1584
		}
24275 amit.gupta 1585
		// this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1586
 
23655 amit.gupta 1587
		return creditNote;
23650 amit.gupta 1588
	}
24275 amit.gupta 1589
 
23655 amit.gupta 1590
	@Override
1591
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1592
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1593
		return getCreditNotePdfModel(creditNote);
1594
	}
24275 amit.gupta 1595
 
1596
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote)
1597
			throws ProfitMandiBusinessException {
23655 amit.gupta 1598
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
24275 amit.gupta 1599
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository
1600
				.selectAllByCreditNoteId(creditNote.getId());
23655 amit.gupta 1601
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
24275 amit.gupta 1602
 
23655 amit.gupta 1603
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
24275 amit.gupta 1604
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoOrder.getFofoId()))
1605
				.get(fofoOrder.getFofoId());
23655 amit.gupta 1606
 
1607
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1608
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1609
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1610
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1611
 
1612
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1613
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1614
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1615
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
24275 amit.gupta 1616
 
1617
		if (ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())) {
23655 amit.gupta 1618
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1619
					.collect(Collectors.toSet());
1620
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1621
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1622
			customFofoOrderItem.setDescription(
1623
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1624
		}
24275 amit.gupta 1625
 
23655 amit.gupta 1626
		customFofoOrderItem.setRate(taxableSellingPrice);
1627
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1628
		customFofoOrderItem.setQuantity(customerReturnItems.size());
24275 amit.gupta 1629
		customFofoOrderItem.setNetAmount(
1630
				(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
23655 amit.gupta 1631
 
1632
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1633
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1634
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1635
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1636
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1637
		customFofoOrderItem.setIgstAmount(igstAmount);
1638
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1639
		customFofoOrderItem.setCgstAmount(cgstAmount);
1640
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1641
		customFofoOrderItem.setSgstAmount(sgstAmount);
1642
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1643
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1644
		customerFofoOrderItems.add(customFofoOrderItem);
24275 amit.gupta 1645
 
23650 amit.gupta 1646
		PdfModel pdfModel = new PdfModel();
1647
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1648
		pdfModel.setCustomer(customCustomer);
1649
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1650
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1651
		pdfModel.setTitle("Credit Note");
1652
		pdfModel.setRetailer(customRetailer);
1653
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1654
		pdfModel.setOrderItems(customerFofoOrderItems);
24275 amit.gupta 1655
 
23650 amit.gupta 1656
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1657
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1658
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1659
		creditNotePdfModel.setPdfModel(pdfModel);
1660
		return creditNotePdfModel;
1661
	}
23638 amit.gupta 1662
 
24275 amit.gupta 1663
	// This will remove the order and maintain order record and reverse inventory
1664
	// and scheme
24264 amit.gupta 1665
	@Override
1666
	public void cancelOrder(List<String> invoiceNumbers) throws Exception {
24275 amit.gupta 1667
		for (String invoiceNumber : invoiceNumbers) {
24264 amit.gupta 1668
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1669
			fofoOrder.setCancelledTimestamp(LocalDateTime.now());
1670
			fofoOrderRepository.persist(fofoOrder);
24275 amit.gupta 1671
			List<PaymentOptionTransaction> paymentTransactions = paymentOptionTransactionRepository
1672
					.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
24264 amit.gupta 1673
			for (PaymentOptionTransaction paymentOptionTransaction : paymentTransactions) {
1674
				paymentOptionTransactionRepository.delete(paymentOptionTransaction);
1675
			}
1676
			List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1677
			List<InventoryItem> inventoryItems = new ArrayList<>();
24275 amit.gupta 1678
			fois.stream().forEach(x -> {
1679
				x.getFofoLineItems().stream().forEach(y -> {
24264 amit.gupta 1680
					inventoryService.rollbackInventory(y.getInventoryItemId(), y.getQuantity(), fofoOrder.getFofoId());
1681
					inventoryItems.add(inventoryItemRepository.selectById(y.getInventoryItemId()));
1682
				});
1683
			});
1684
			String reversalReason = "Order Rolledback/Cancelled for Invoice Number " + invoiceNumber;
1685
			schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, SchemeType.OUT);
27377 amit.gupta 1686
			schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, SchemeType.ACTIVATION);
24264 amit.gupta 1687
		}
1688
	}
1689
 
24271 amit.gupta 1690
	@Override
1691
	public float getSales(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
24287 amit.gupta 1692
		Float sales = fofoOrderRepository.selectSaleSumGroupByFofoIds(startDate, endDate).get(fofoId);
24285 amit.gupta 1693
		return sales == null ? 0f : sales;
24271 amit.gupta 1694
	}
1695
 
1696
	@Override
27083 amit.gupta 1697
	public LocalDateTime getMaxSalesDate(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
1698
		LocalDateTime dateTime = fofoOrderRepository.selectMaxSaleDateGroupByFofoIds(startDate, endDate).get(fofoId);
1699
		return dateTime;
1700
	}
1701
 
1702
	@Override
27516 amit.gupta 1703
	// Only being used internally
24271 amit.gupta 1704
	public float getSales(int fofoId, LocalDate onDate) {
24285 amit.gupta 1705
		LocalDateTime startTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT);
1706
		LocalDateTime endTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT).plusDays(1);
1707
		return this.getSales(fofoId, startTime, endTime);
24271 amit.gupta 1708
	}
1709
 
1710
	@Override
1711
	public float getSales(LocalDateTime onDate) {
1712
		// TODO Auto-generated method stub
1713
		return 0;
1714
	}
1715
 
1716
	@Override
1717
	public float getSales(LocalDateTime startDate, LocalDateTime endDate) {
1718
		// TODO Auto-generated method stub
1719
		return 0;
1720
	}
1721
 
24917 tejbeer 1722
	@Override
1723
	public boolean notifyColorChange(int orderId, int itemId) throws ProfitMandiBusinessException {
1724
		Order order = orderRepository.selectById(orderId);
26891 amit.gupta 1725
		saholicInventoryService.reservationCountByColor(itemId, order);
25101 amit.gupta 1726
 
1727
		order.getLineItem().setItemId(itemId);
1728
		Item item = itemRepository.selectById(itemId);
24917 tejbeer 1729
		order.getLineItem().setColor(item.getColor());
1730
		return true;
1731
	}
1732
 
25083 amit.gupta 1733
	@Override
1734
	public FofoOrder getOrderByInventoryItemId(int inventoryItemId) throws Exception {
1735
		List<FofoLineItem> lineItems = fofoLineItemRepository.selectByInventoryItemId(inventoryItemId);
25101 amit.gupta 1736
		if (lineItems.size() > 0) {
25083 amit.gupta 1737
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(lineItems.get(0).getFofoOrderItemId());
1738
			fofoOrderItem.setFofoLineItems(new HashSet<>(lineItems));
1739
			FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderItem.getOrderId());
1740
			fofoOrder.setOrderItem(fofoOrderItem);
1741
			return fofoOrder;
1742
		} else {
1743
			throw new Exception(String.format("Could not find inventoryItemId - %s", inventoryItemId));
1744
		}
1745
	}
25724 amit.gupta 1746
}