Subversion Repositories SmartDukaan

Rev

Rev 30527 | Rev 30957 | 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
1275
							|| item.getCategoryId() == ProfitMandiConstants.TABLET_CATEGORY_ID)
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
			inventoryItemRepository.persist(inventoryItem);
1322
			ScanRecord scanRecord = new ScanRecord();
1323
			scanRecord.setInventoryItemId(inventoryItem.getId());
1324
			scanRecord.setFofoId(fofoId);
24264 amit.gupta 1325
			scanRecord.setOrderId(fofoOrderId);
23650 amit.gupta 1326
			// correct this
22859 ashik.ali 1327
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1328
			scanRecord.setType(ScanType.SALE);
1329
			scanRecordRepository.persist(scanRecord);
23566 amit.gupta 1330
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1331
 
22859 ashik.ali 1332
		}
1333
	}
23650 amit.gupta 1334
 
1335
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
1336
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1337
		for (InventoryItem inventoryItem : inventoryItems) {
22859 ashik.ali 1338
			FofoLineItem fofoLineItem = new FofoLineItem();
1339
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1340
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1341
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1342
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1343
			fofoLineItemRepository.persist(fofoLineItem);
1344
		}
1345
	}
23650 amit.gupta 1346
 
1347
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
1348
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
1349
			throws ProfitMandiBusinessException {
22859 ashik.ali 1350
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1351
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1352
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1353
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1354
		fofoOrderItem.setOrderId(fofoOrderId);
25103 amit.gupta 1355
		TagListing tl = tagListingRepository.selectByItemId(customFofoOrderItem.getItemId());
25162 amit.gupta 1356
		// In case listing gets removed rebill it using the selling price
1357
		if (tl != null) {
25103 amit.gupta 1358
			fofoOrderItem.setDp(tl.getSellingPrice());
26332 amit.gupta 1359
			fofoOrderItem.setMop(tl.getMop());
25103 amit.gupta 1360
		} else {
1361
			fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
26332 amit.gupta 1362
			fofoOrderItem.setMop(customFofoOrderItem.getSellingPrice());
25103 amit.gupta 1363
		}
22859 ashik.ali 1364
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
24823 amit.gupta 1365
 
22859 ashik.ali 1366
		Item item = itemMap.get(customFofoOrderItem.getItemId());
23172 ashik.ali 1367
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1368
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
23650 amit.gupta 1369
		if (stateId != null) {
26817 amit.gupta 1370
			itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
23650 amit.gupta 1371
		} else {
26817 amit.gupta 1372
			itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
23172 ashik.ali 1373
		}
23650 amit.gupta 1374
		for (InventoryItem inventoryItem : inventoryItems) {
1375
			if (stateId == null) {
23172 ashik.ali 1376
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
23650 amit.gupta 1377
			} else {
23172 ashik.ali 1378
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1379
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1380
			}
23650 amit.gupta 1381
 
22859 ashik.ali 1382
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1383
			break;
1384
		}
1385
		fofoOrderItem.setBrand(item.getBrand());
1386
		fofoOrderItem.setModelName(item.getModelName());
1387
		fofoOrderItem.setModelNumber(item.getModelNumber());
1388
		fofoOrderItem.setColor(item.getColor());
1389
		fofoOrderItemRepository.persist(fofoOrderItem);
1390
		return fofoOrderItem;
1391
	}
23650 amit.gupta 1392
 
28166 tejbeer 1393
	private FofoOrderItem getDummyFofoOrderItem(int itemId, int fofoOrderId, String serialNumber, Integer stateId)
1394
			throws ProfitMandiBusinessException {
27516 amit.gupta 1395
		Item item = itemRepository.selectById(itemId);
1396
		TagListing tl = tagListingRepository.selectByItemId(itemId);
1397
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1398
		fofoOrderItem.setItemId(itemId);
1399
		fofoOrderItem.setQuantity(1);
1400
		fofoOrderItem.setSellingPrice(tl.getMop());
1401
		fofoOrderItem.setOrderId(fofoOrderId);
1402
		// In case listing gets removed rebill it using the selling price
1403
		fofoOrderItem.setDp(tl.getSellingPrice());
1404
		fofoOrderItem.setMop(tl.getMop());
1405
		fofoOrderItem.setDiscount(0);
1406
 
1407
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1408
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
1409
		if (stateId != null) {
1410
			itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(Arrays.asList(itemId), stateId);
1411
		} else {
1412
			itemIdIgstTaxRateMap = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId));
1413
		}
1414
 
1415
		if (stateId == null) {
1416
			fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(itemId));
1417
		} else {
1418
			fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(itemId).getCgstRate());
1419
			fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(itemId).getSgstRate());
1420
		}
1421
 
1422
		fofoOrderItem.setHsnCode(item.getHsnCode());
1423
		fofoOrderItem.setBrand(item.getBrand());
1424
		fofoOrderItem.setModelName(item.getModelName());
1425
		fofoOrderItem.setModelNumber(item.getModelNumber());
1426
		fofoOrderItem.setColor(item.getColor());
1427
 
1428
		Set<FofoLineItem> fofoLineItems = new HashSet<>();
1429
		FofoLineItem fli = new FofoLineItem();
1430
		fli.setQuantity(1);
1431
		fli.setSerialNumber(serialNumber);
1432
		fofoLineItems.add(fli);
1433
		fofoOrderItem.setFofoLineItems(fofoLineItems);
1434
 
1435
		return fofoOrderItem;
1436
	}
1437
 
23650 amit.gupta 1438
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
1439
			int itemId, int quantity) throws ProfitMandiBusinessException {
1440
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1441
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1442
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
1443
						currentInventorySnapshot.getAvailability() - quantity);
22859 ashik.ali 1444
			}
1445
		}
1446
	}
23650 amit.gupta 1447
 
1448
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
1449
			throws ProfitMandiBusinessException {
1450
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1451
			if (customPaymentOption.getAmount() > 0) {
23546 ashik.ali 1452
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
23612 amit.gupta 1453
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
23546 ashik.ali 1454
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1455
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1456
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
23612 amit.gupta 1457
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
23546 ashik.ali 1458
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
23371 ashik.ali 1459
			}
22859 ashik.ali 1460
		}
1461
	}
23650 amit.gupta 1462
 
24275 amit.gupta 1463
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber,
1464
			float totalAmount, int customerAddressId) {
22859 ashik.ali 1465
		FofoOrder fofoOrder = new FofoOrder();
23369 ashik.ali 1466
		fofoOrder.setCustomerGstNumber(customerGstNumber);
22859 ashik.ali 1467
		fofoOrder.setCustomerId(customerId);
1468
		fofoOrder.setFofoId(fofoId);
24226 amit.gupta 1469
		fofoOrder.setInvoiceNumber(documentNumber);
22859 ashik.ali 1470
		fofoOrder.setTotalAmount(totalAmount);
1471
		fofoOrder.setCustomerAddressId(customerAddressId);
1472
		fofoOrderRepository.persist(fofoOrder);
1473
		return fofoOrder;
1474
	}
23650 amit.gupta 1475
 
1476
	private void validateItemsSerializedNonSerialized(List<Item> items,
1477
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1478
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
22859 ashik.ali 1479
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
23650 amit.gupta 1480
		for (Item i : items) {
22872 ashik.ali 1481
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
23650 amit.gupta 1482
			if (i.getType().equals(ItemType.SERIALIZED)) {
1483
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
22872 ashik.ali 1484
					invalidItemIdSerialNumbers.add(i.getId());
22859 ashik.ali 1485
				}
23650 amit.gupta 1486
			} else {
1487
				Set<String> serialNumbers = this
1488
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1489
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
22872 ashik.ali 1490
					itemIdNonSerializedSerialNumbers.add(i.getId());
22859 ashik.ali 1491
				}
1492
			}
1493
		}
1494
 
23650 amit.gupta 1495
		if (!invalidItemIdSerialNumbers.isEmpty()) {
22859 ashik.ali 1496
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1497
			// itemId's are serialized you are saying these are not serialized
23650 amit.gupta 1498
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
1499
					"FFORDR_1013");
22859 ashik.ali 1500
		}
1501
 
23650 amit.gupta 1502
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
22859 ashik.ali 1503
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1504
			// itemId's are non serialized you are saying these are serialized
23650 amit.gupta 1505
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
1506
					"FFORDR_1014");
22859 ashik.ali 1507
		}
1508
	}
23650 amit.gupta 1509
 
1510
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
1511
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1512
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
22859 ashik.ali 1513
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1514
		}
23650 amit.gupta 1515
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1516
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
22872 ashik.ali 1517
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
23650 amit.gupta 1518
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1519
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
1520
					.get(currentInventorySnapshot.getItemId());
22872 ashik.ali 1521
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
23650 amit.gupta 1522
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1523
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1524
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1525
				Quantity quantity = new Quantity();
1526
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1527
				quantity.setRequested(customFofoOrderItem.getQuantity());
1528
				itemIdQuantityAvailability.setQuantity(quantity);
1529
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1530
			}
22859 ashik.ali 1531
		}
1532
 
23650 amit.gupta 1533
		if (!itemIdQuantityAvailabilities.isEmpty()) {
22859 ashik.ali 1534
			// itemIdQuantity request is not valid
23650 amit.gupta 1535
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
1536
					itemIdQuantityAvailabilities);
1537
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
1538
					"FFORDR_1015");
22859 ashik.ali 1539
		}
1540
	}
23650 amit.gupta 1541
 
1542
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
1543
			String serialNumber) {
22872 ashik.ali 1544
		int itemId = 0;
23650 amit.gupta 1545
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
22872 ashik.ali 1546
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
23650 amit.gupta 1547
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1548
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
22872 ashik.ali 1549
					itemId = entry.getKey();
1550
					break;
1551
				}
22859 ashik.ali 1552
			}
1553
		}
22872 ashik.ali 1554
		return itemId;
22859 ashik.ali 1555
	}
23650 amit.gupta 1556
 
1557
	private Map<Integer, Item> toItemMap(List<Item> items) {
22955 ashik.ali 1558
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1559
			@Override
1560
			public Integer apply(Item item) {
1561
				return item.getId();
1562
			}
1563
		};
1564
		Function<Item, Item> itemFunction = new Function<Item, Item>() {
1565
			@Override
1566
			public Item apply(Item item) {
1567
				return item;
1568
			}
1569
		};
1570
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
22859 ashik.ali 1571
	}
1572
 
23650 amit.gupta 1573
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
22859 ashik.ali 1574
		customerAddress.setName(customAddress.getName());
29068 amit.gupta 1575
		customerAddress.setLastName(customAddress.getLastName());
22859 ashik.ali 1576
		customerAddress.setLine1(customAddress.getLine1());
1577
		customerAddress.setLine2(customAddress.getLine2());
1578
		customerAddress.setLandmark(customAddress.getLandmark());
1579
		customerAddress.setCity(customAddress.getCity());
1580
		customerAddress.setPinCode(customAddress.getPinCode());
1581
		customerAddress.setState(customAddress.getState());
1582
		customerAddress.setCountry(customAddress.getCountry());
1583
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1584
	}
1585
 
23650 amit.gupta 1586
	private CustomAddress createCustomAddress(Address address) {
22859 ashik.ali 1587
		CustomAddress customAddress = new CustomAddress();
1588
		customAddress.setName(address.getName());
1589
		customAddress.setLine1(address.getLine1());
1590
		customAddress.setLine2(address.getLine2());
1591
		customAddress.setLandmark(address.getLandmark());
1592
		customAddress.setCity(address.getCity());
1593
		customAddress.setPinCode(address.getPinCode());
1594
		customAddress.setState(address.getState());
1595
		customAddress.setCountry(address.getCountry());
1596
		customAddress.setPhoneNumber(address.getPhoneNumber());
1597
		return customAddress;
1598
	}
1599
 
23650 amit.gupta 1600
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
22859 ashik.ali 1601
		CustomAddress customAddress = new CustomAddress();
1602
		customAddress.setName(customerAddress.getName());
26817 amit.gupta 1603
		customAddress.setLastName(customerAddress.getLastName());
22859 ashik.ali 1604
		customAddress.setLine1(customerAddress.getLine1());
1605
		customAddress.setLine2(customerAddress.getLine2());
1606
		customAddress.setLandmark(customerAddress.getLandmark());
1607
		customAddress.setCity(customerAddress.getCity());
1608
		customAddress.setPinCode(customerAddress.getPinCode());
1609
		customAddress.setState(customerAddress.getState());
1610
		customAddress.setCountry(customerAddress.getCountry());
1611
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1612
		return customAddress;
1613
	}
1614
 
23650 amit.gupta 1615
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1616
			throws ProfitMandiBusinessException {
23365 ashik.ali 1617
		Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1618
 
22859 ashik.ali 1619
		float calculatedAmount = 0;
23650 amit.gupta 1620
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
23365 ashik.ali 1621
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1622
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
22859 ashik.ali 1623
		}
23650 amit.gupta 1624
		if (calculatedAmount != totalAmount) {
28390 amit.gupta 1625
			LOGGER.warn("Error occured while validating payment options amount - {} != TotalAmount {}",
23650 amit.gupta 1626
					calculatedAmount, totalAmount);
1627
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
1628
					calculatedAmount, "FFORDR_1016");
22859 ashik.ali 1629
		}
23650 amit.gupta 1630
 
23365 ashik.ali 1631
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
23650 amit.gupta 1632
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
23365 ashik.ali 1633
			paymentOptionIds.removeAll(foundPaymentOptionIds);
23650 amit.gupta 1634
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
1635
					"FFORDR_1017");
23365 ashik.ali 1636
		}
22859 ashik.ali 1637
	}
23650 amit.gupta 1638
 
22925 ashik.ali 1639
	@Override
1640
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1641
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
23650 amit.gupta 1642
		if (!fofoOrderItems.isEmpty()) {
22925 ashik.ali 1643
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
23650 amit.gupta 1644
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
1645
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
22925 ashik.ali 1646
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
23650 amit.gupta 1647
			while (fofoOrderItemsIterator.hasNext()) {
22925 ashik.ali 1648
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1649
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1650
				newFofoOrderItems.add(fofoOrderItem);
1651
				fofoOrderItemsIterator.remove();
1652
			}
1653
			fofoOrderItems = newFofoOrderItems;
1654
		}
1655
		return fofoOrderItems;
1656
	}
23650 amit.gupta 1657
 
1658
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
22955 ashik.ali 1659
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1660
			@Override
1661
			public Integer apply(FofoOrderItem fofoOrderItem) {
1662
				return fofoOrderItem.getId();
1663
			}
1664
		};
1665
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
22925 ashik.ali 1666
	}
23650 amit.gupta 1667
 
1668
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
22925 ashik.ali 1669
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1670
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1671
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
23650 amit.gupta 1672
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1673
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
22925 ashik.ali 1674
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1675
				fofoLineItems2.add(fofoLineItem);
1676
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
23650 amit.gupta 1677
			} else {
22925 ashik.ali 1678
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1679
			}
1680
		}
1681
		return fofoOrderItemIdFofoLineItemsMap;
1682
	}
23650 amit.gupta 1683
 
23418 ashik.ali 1684
	@Override
23650 amit.gupta 1685
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
1686
			throws ProfitMandiBusinessException {
23582 ashik.ali 1687
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1688
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1689
		customer.setFirstName(customCustomer.getFirstName());
1690
		customer.setLastName(customCustomer.getLastName());
24121 govind 1691
		customer.setMobileNumber(customCustomer.getMobileNumber());
1692
		customer.setEmailId(customCustomer.getEmailId());
23582 ashik.ali 1693
		customerRepository.persist(customer);
1694
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
27411 amit.gupta 1695
		if (!customerAddress.getState().equalsIgnoreCase(customCustomer.getAddress().getState())) {
25101 amit.gupta 1696
			List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1697
			resetTaxation(fofoOrder.getFofoId(), customerAddress, fofoOrderItems);
1698
		}
23582 ashik.ali 1699
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1700
		customerAddressRepository.persist(customerAddress);
24121 govind 1701
		fofoOrder.setCustomerGstNumber(customCustomer.getGstNumber());
23582 ashik.ali 1702
	}
23418 ashik.ali 1703
 
25101 amit.gupta 1704
	private void resetTaxation(int fofoId, CustomerAddress customerAddress, List<FofoOrderItem> fofoOrderItems)
1705
			throws ProfitMandiBusinessException {
1706
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
1707
 
1708
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
1709
 
1710
		Integer stateId = null;
27411 amit.gupta 1711
		if (customerAddress.getState().equalsIgnoreCase(retailerAddress.getState())) {
25101 amit.gupta 1712
			try {
30527 tejbeer 1713
				stateId = Long.valueOf(stateRepository.selectByName(customerAddress.getState()).getId()).intValue();
25101 amit.gupta 1714
			} catch (Exception e) {
1715
				LOGGER.error("Unable to get state rates");
1716
			}
1717
		}
1718
		List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
1719
		final Map<Integer, GstRate> gstRates;
1720
		if (stateId != null) {
26817 amit.gupta 1721
			gstRates = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
25101 amit.gupta 1722
		} else {
1723
			gstRates = new HashMap<>();
26817 amit.gupta 1724
			stateGstRateRepository.getIgstTaxRate(itemIds).entrySet().forEach(x -> {
25101 amit.gupta 1725
				GstRate gstRate = new GstRate();
1726
				gstRate.setIgstRate(x.getValue());
1727
				gstRate.setCgstRate(0f);
1728
				gstRate.setSgstRate(0f);
1729
				gstRates.put(x.getKey(), gstRate);
1730
 
1731
			});
1732
		}
1733
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1734
			GstRate rate = gstRates.get(fofoOrderItem.getItemId());
1735
			fofoOrderItem.setCgstRate(rate.getCgstRate());
1736
			fofoOrderItem.setSgstRate(rate.getSgstRate());
1737
			fofoOrderItem.setIgstRate(rate.getIgstRate());
1738
		}
1739
	}
1740
 
23638 amit.gupta 1741
	@Override
24275 amit.gupta 1742
	public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest)
1743
			throws ProfitMandiBusinessException {
23655 amit.gupta 1744
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
23650 amit.gupta 1745
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
23655 amit.gupta 1746
		if (fofoOrder.getFofoId() != fofoId) {
23638 amit.gupta 1747
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1748
		}
23655 amit.gupta 1749
		int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
24275 amit.gupta 1750
		if (foiBadReturnRequest.getMarkedBadArr().size() > billedQty) {
23655 amit.gupta 1751
			throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
1752
		}
23650 amit.gupta 1753
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
23655 amit.gupta 1754
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
23650 amit.gupta 1755
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
1756
			customerReturnItem.setFofoId(fofoId);
23655 amit.gupta 1757
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
24264 amit.gupta 1758
			customerReturnItem.setFofoOrderId(fofoOrder.getId());
23655 amit.gupta 1759
			customerReturnItem.setRemarks(badReturnRequest.getRemarks());
23650 amit.gupta 1760
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1761
			customerReturnItem.setQuantity(1);
1762
			customerReturnItem.setType(ReturnType.BAD);
24275 amit.gupta 1763
			// customerReturnItemRepository.persist(customerReturnItem);
23650 amit.gupta 1764
			inventoryService.saleReturnInventoryItem(customerReturnItem);
1765
			customerReturnItems.add(customerReturnItem);
23638 amit.gupta 1766
		}
23655 amit.gupta 1767
		CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
24275 amit.gupta 1768
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1769
			purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(),
1770
					ReturnType.BAD);
23655 amit.gupta 1771
		}
27516 amit.gupta 1772
		// This should cancel the order
29562 amit.gupta 1773
		fofoOrder.setCancelledTimestamp(LocalDateTime.now());
29548 amit.gupta 1774
		this.reverseScheme(fofoOrder);
24275 amit.gupta 1775
		return creditNote;
23638 amit.gupta 1776
	}
1777
 
24275 amit.gupta 1778
	private CustomerCreditNote generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems)
1779
			throws ProfitMandiBusinessException {
23650 amit.gupta 1780
 
23638 amit.gupta 1781
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
23650 amit.gupta 1782
				.selectByFofoId(fofoOrder.getFofoId());
1783
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
23638 amit.gupta 1784
		invoiceNumberGenerationSequenceRepository.persist(sequence);
24275 amit.gupta 1785
 
23655 amit.gupta 1786
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
23650 amit.gupta 1787
		CustomerCreditNote creditNote = new CustomerCreditNote();
1788
		creditNote.setCreditNoteNumber(creditNoteNumber);
1789
		creditNote.setFofoId(fofoOrder.getFofoId());
23655 amit.gupta 1790
		creditNote.setFofoOrderId(fofoOrder.getId());
1791
		creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
1792
		creditNote.setSettlementType(SettlementType.UNSETTLED);
23650 amit.gupta 1793
		customerCreditNoteRepository.persist(creditNote);
24275 amit.gupta 1794
 
23650 amit.gupta 1795
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1796
			customerReturnItem.setCreditNoteId(creditNote.getId());
1797
			customerReturnItemRepository.persist(customerReturnItem);
23638 amit.gupta 1798
		}
24275 amit.gupta 1799
		// this.returnInventoryItems(inventoryItems, debitNote);
23638 amit.gupta 1800
 
23655 amit.gupta 1801
		return creditNote;
23650 amit.gupta 1802
	}
24275 amit.gupta 1803
 
23655 amit.gupta 1804
	@Override
1805
	public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
1806
		CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
1807
		return getCreditNotePdfModel(creditNote);
1808
	}
24275 amit.gupta 1809
 
1810
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote)
1811
			throws ProfitMandiBusinessException {
23655 amit.gupta 1812
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
24275 amit.gupta 1813
		List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository
1814
				.selectAllByCreditNoteId(creditNote.getId());
23655 amit.gupta 1815
		CustomCustomer customCustomer = getCustomCustomer(fofoOrder);
24275 amit.gupta 1816
 
23655 amit.gupta 1817
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
30426 tejbeer 1818
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoOrder.getFofoId());
23655 amit.gupta 1819
 
1820
		FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
1821
		float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1822
		float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1823
		float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
1824
 
1825
		CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1826
		customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
1827
		customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
1828
				+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
24275 amit.gupta 1829
 
1830
		if (ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())) {
23655 amit.gupta 1831
			Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId())
1832
					.collect(Collectors.toSet());
1833
			List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
1834
					.map(x -> x.getSerialNumber()).collect(Collectors.toList());
1835
			customFofoOrderItem.setDescription(
1836
					customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1837
		}
24275 amit.gupta 1838
 
23655 amit.gupta 1839
		customFofoOrderItem.setRate(taxableSellingPrice);
1840
		customFofoOrderItem.setDiscount(taxableDiscountPrice);
1841
		customFofoOrderItem.setQuantity(customerReturnItems.size());
24275 amit.gupta 1842
		customFofoOrderItem.setNetAmount(
1843
				(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
23655 amit.gupta 1844
 
1845
		float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1846
		float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1847
		float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1848
		LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
1849
		customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1850
		customFofoOrderItem.setIgstAmount(igstAmount);
1851
		customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1852
		customFofoOrderItem.setCgstAmount(cgstAmount);
1853
		customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1854
		customFofoOrderItem.setSgstAmount(sgstAmount);
1855
		customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
23721 amit.gupta 1856
		customFofoOrderItem.setOrderId(1);
23655 amit.gupta 1857
		customerFofoOrderItems.add(customFofoOrderItem);
24275 amit.gupta 1858
 
30321 amit.gupta 1859
		InvoicePdfModel pdfModel = new InvoicePdfModel();
23650 amit.gupta 1860
		pdfModel.setAuther("NSSPL");
23655 amit.gupta 1861
		pdfModel.setCustomer(customCustomer);
1862
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1863
		pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
1864
		pdfModel.setTitle("Credit Note");
1865
		pdfModel.setRetailer(customRetailer);
1866
		pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
1867
		pdfModel.setOrderItems(customerFofoOrderItems);
24275 amit.gupta 1868
 
23650 amit.gupta 1869
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
1870
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
1871
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
1872
		creditNotePdfModel.setPdfModel(pdfModel);
1873
		return creditNotePdfModel;
1874
	}
23638 amit.gupta 1875
 
24275 amit.gupta 1876
	// This will remove the order and maintain order record and reverse inventory
1877
	// and scheme
24264 amit.gupta 1878
	@Override
29548 amit.gupta 1879
	public void cancelOrder(List<String> invoiceNumbers) throws ProfitMandiBusinessException {
24275 amit.gupta 1880
		for (String invoiceNumber : invoiceNumbers) {
28166 tejbeer 1881
			// Cancel only when not cancelled
24264 amit.gupta 1882
			FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
28166 tejbeer 1883
			if (fofoOrder.getCancelledTimestamp() == null) {
27734 amit.gupta 1884
				fofoOrder.setCancelledTimestamp(LocalDateTime.now());
29548 amit.gupta 1885
				PaymentOptionTransaction paymentTransaction = new PaymentOptionTransaction();
1886
				paymentTransaction.setAmount(-fofoOrder.getTotalAmount());
1887
				paymentTransaction.setFofoId(fofoOrder.getFofoId());
1888
				paymentTransaction.setReferenceId(fofoOrder.getId());
1889
				paymentTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1890
				paymentTransaction.setPaymentOptionId(1);
1891
				paymentOptionTransactionRepository.persist(paymentTransaction);
29707 tejbeer 1892
 
27734 amit.gupta 1893
				List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
1894
				List<InventoryItem> inventoryItems = new ArrayList<>();
1895
				fois.stream().forEach(x -> {
29707 tejbeer 1896
					x.getFofoLineItems().stream().forEach(y -> {
28166 tejbeer 1897
						inventoryService.rollbackInventory(y.getInventoryItemId(), y.getQuantity(),
1898
								fofoOrder.getFofoId());
27734 amit.gupta 1899
						inventoryItems.add(inventoryItemRepository.selectById(y.getInventoryItemId()));
1900
					});
1901
				});
29707 tejbeer 1902
				// if(invoice)
29548 amit.gupta 1903
				this.reverseScheme(fofoOrder);
29557 amit.gupta 1904
				insuranceService.cancelInsurance(fofoOrder);
24264 amit.gupta 1905
			}
1906
		}
1907
	}
29707 tejbeer 1908
 
29548 amit.gupta 1909
	@Override
1910
	public void reverseScheme(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
1911
		String reversalReason = "Order Rolledback/Cancelled/Returned for Invoice #" + fofoOrder.getInvoiceNumber();
1912
		List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
29707 tejbeer 1913
		Set<Integer> inventoryItemIds = fois.stream()
1914
				.flatMap(x -> x.getFofoLineItems().stream().map(y -> y.getInventoryItemId()))
1915
				.collect(Collectors.toSet());
29548 amit.gupta 1916
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
29707 tejbeer 1917
		schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, SchemeService.OUT_SCHEME_TYPES);
29548 amit.gupta 1918
		schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason,
1919
				Arrays.asList(SchemeType.INVESTMENT));
1920
		schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason,
1921
				Arrays.asList(SchemeType.ACTIVATION));
30449 amit.gupta 1922
		schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason,
1923
				Arrays.asList(SchemeType.SPECIAL_SUPPORT));
29707 tejbeer 1924
 
29548 amit.gupta 1925
	}
24264 amit.gupta 1926
 
24271 amit.gupta 1927
	@Override
1928
	public float getSales(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
24287 amit.gupta 1929
		Float sales = fofoOrderRepository.selectSaleSumGroupByFofoIds(startDate, endDate).get(fofoId);
24285 amit.gupta 1930
		return sales == null ? 0f : sales;
24271 amit.gupta 1931
	}
1932
 
1933
	@Override
27083 amit.gupta 1934
	public LocalDateTime getMaxSalesDate(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
1935
		LocalDateTime dateTime = fofoOrderRepository.selectMaxSaleDateGroupByFofoIds(startDate, endDate).get(fofoId);
1936
		return dateTime;
1937
	}
1938
 
1939
	@Override
27516 amit.gupta 1940
	// Only being used internally
24271 amit.gupta 1941
	public float getSales(int fofoId, LocalDate onDate) {
24285 amit.gupta 1942
		LocalDateTime startTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT);
1943
		LocalDateTime endTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT).plusDays(1);
1944
		return this.getSales(fofoId, startTime, endTime);
24271 amit.gupta 1945
	}
1946
 
1947
	@Override
1948
	public float getSales(LocalDateTime onDate) {
1949
		// TODO Auto-generated method stub
1950
		return 0;
1951
	}
1952
 
1953
	@Override
1954
	public float getSales(LocalDateTime startDate, LocalDateTime endDate) {
1955
		// TODO Auto-generated method stub
1956
		return 0;
1957
	}
1958
 
24917 tejbeer 1959
	@Override
1960
	public boolean notifyColorChange(int orderId, int itemId) throws ProfitMandiBusinessException {
1961
		Order order = orderRepository.selectById(orderId);
26891 amit.gupta 1962
		saholicInventoryService.reservationCountByColor(itemId, order);
25101 amit.gupta 1963
 
1964
		order.getLineItem().setItemId(itemId);
1965
		Item item = itemRepository.selectById(itemId);
24917 tejbeer 1966
		order.getLineItem().setColor(item.getColor());
1967
		return true;
1968
	}
1969
 
25083 amit.gupta 1970
	@Override
1971
	public FofoOrder getOrderByInventoryItemId(int inventoryItemId) throws Exception {
1972
		List<FofoLineItem> lineItems = fofoLineItemRepository.selectByInventoryItemId(inventoryItemId);
25101 amit.gupta 1973
		if (lineItems.size() > 0) {
25083 amit.gupta 1974
			FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(lineItems.get(0).getFofoOrderItemId());
1975
			fofoOrderItem.setFofoLineItems(new HashSet<>(lineItems));
1976
			FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderItem.getOrderId());
1977
			fofoOrder.setOrderItem(fofoOrderItem);
1978
			return fofoOrder;
1979
		} else {
1980
			throw new Exception(String.format("Could not find inventoryItemId - %s", inventoryItemId));
1981
		}
1982
	}
28166 tejbeer 1983
 
1984
	@Override
1985
	public Map<Integer, Long> carryBagCreditCount(int fofoId) throws ProfitMandiBusinessException {
1986
 
1987
		FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1988
		LocalDateTime lastCredit = fs.getBagsLastCredited();
1989
		/*
1990
		 * long carryBagCount = 0; List<FofoOrder> fofoOrders =
1991
		 * fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(fofoId,
1992
		 * lastCredit.atStartOfDay(), LocalDate.now().plusDays(1).atStartOfDay()); for
1993
		 * (FofoOrder fo : fofoOrders) { carryBagCount +=
1994
		 * fofoOrderItemRepository.selectByOrderId(fo.getId()).stream() .filter(x ->
1995
		 * x.getSellingPrice() >= 12000).count();
30449 amit.gupta 1996
		 *
28166 tejbeer 1997
		 * }
1998
		 */
1999
 
2000
		Session session = sessionFactory.getCurrentSession();
2001
		CriteriaBuilder cb = session.getCriteriaBuilder();
2002
 
2003
		CriteriaQuery<SimpleEntry> query = cb.createQuery(SimpleEntry.class);
2004
		Root<FofoOrder> fofoOrder = query.from(FofoOrder.class);
2005
		Root<FofoOrderItem> fofoOrderItem = query.from(FofoOrderItem.class);
30449 amit.gupta 2006
		Root<TagListing> tagListingRoot = query.from(TagListing.class);
2007
		Root<Item> itemRoot = query.from(Item.class);
28166 tejbeer 2008
 
2009
		Predicate p2 = cb.between(fofoOrder.get(ProfitMandiConstants.CREATE_TIMESTAMP), lastCredit,
2010
				LocalDate.now().atStartOfDay());
2011
		Predicate p3 = cb.isNull(fofoOrder.get("cancelledTimestamp"));
30449 amit.gupta 2012
		Predicate joinPredicate = cb.and(
2013
				cb.equal(fofoOrder.get(ProfitMandiConstants.ID), fofoOrderItem.get(ProfitMandiConstants.ORDER_ID)),
2014
				cb.equal(fofoOrderItem.get("itemId"), tagListingRoot.get("itemId")),
2015
				cb.equal(itemRoot.get("id"), tagListingRoot.get("itemId")),
30527 tejbeer 2016
				cb.equal(fofoOrder.get(ProfitMandiConstants.FOFO_ID), fofoId));
28166 tejbeer 2017
		ItemCriteria itemCriteria = new ItemCriteria();
2018
		itemCriteria.setBrands(mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
2019
				.collect(Collectors.toList()));
2020
		float startValue = 12000;
2021
		itemCriteria.setStartPrice(startValue);
2022
		itemCriteria.setEndPrice(0);
2023
		itemCriteria.setFeaturedPhone(false);
2024
		itemCriteria.setSmartPhone(true);
2025
		itemCriteria.setCatalogIds(new ArrayList<>());
2026
		itemCriteria.setExcludeCatalogIds(new ArrayList<>());
30449 amit.gupta 2027
		Predicate itemPredicate = itemRepository.getItemPredicate(itemCriteria, cb, itemRoot, tagListingRoot);
2028
		Predicate finalPredicate = cb.and(itemPredicate, p2, p3, joinPredicate);
28166 tejbeer 2029
		query = query.multiselect(fofoOrder.get(ProfitMandiConstants.FOFO_ID), cb.count(fofoOrder))
2030
				.where(finalPredicate).groupBy(fofoOrder.get(ProfitMandiConstants.FOFO_ID));
2031
		List<SimpleEntry> simpleEntries = session.createQuery(query).getResultList();
2032
		Map<Integer, Long> returnMap = new HashMap<>();
2033
 
2034
		for (SimpleEntry simpleEntry : simpleEntries) {
2035
			returnMap.put((Integer) simpleEntry.getKey(), (Long) simpleEntry.getValue());
2036
		}
2037
		return returnMap;
2038
 
2039
	}
25724 amit.gupta 2040
}