Subversion Repositories SmartDukaan

Rev

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