Subversion Repositories SmartDukaan

Rev

Rev 31057 | Rev 31059 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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