Subversion Repositories SmartDukaan

Rev

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