Subversion Repositories SmartDukaan

Rev

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