Subversion Repositories SmartDukaan

Rev

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