Subversion Repositories SmartDukaan

Rev

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