Subversion Repositories SmartDukaan

Rev

Rev 28091 | Rev 28093 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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