Subversion Repositories SmartDukaan

Rev

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