Subversion Repositories SmartDukaan

Rev

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