Subversion Repositories SmartDukaan

Rev

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

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