Subversion Repositories SmartDukaan

Rev

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