Subversion Repositories SmartDukaan

Rev

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