Subversion Repositories SmartDukaan

Rev

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