Subversion Repositories SmartDukaan

Rev

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