Subversion Repositories SmartDukaan

Rev

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