Subversion Repositories SmartDukaan

Rev

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