Subversion Repositories SmartDukaan

Rev

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

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