Subversion Repositories SmartDukaan

Rev

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