Subversion Repositories SmartDukaan

Rev

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