Subversion Repositories SmartDukaan

Rev

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