Subversion Repositories SmartDukaan

Rev

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