Subversion Repositories SmartDukaan

Rev

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