Subversion Repositories SmartDukaan

Rev

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