Subversion Repositories SmartDukaan

Rev

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