Subversion Repositories SmartDukaan

Rev

Rev 28458 | Rev 28969 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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