Subversion Repositories SmartDukaan

Rev

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