Subversion Repositories SmartDukaan

Rev

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