Subversion Repositories SmartDukaan

Rev

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