Subversion Repositories SmartDukaan

Rev

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