Subversion Repositories SmartDukaan

Rev

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