Subversion Repositories SmartDukaan

Rev

Rev 33795 | Rev 33873 | 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;
33838 ranu 5
import com.spice.profitmandi.common.enumuration.UpgradeOfferPaymentStatus;
22859 ashik.ali 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
32420 amit.gupta 7
import com.spice.profitmandi.common.model.*;
23650 amit.gupta 8
import com.spice.profitmandi.common.util.FormattingUtils;
22859 ashik.ali 9
import com.spice.profitmandi.common.util.StringUtils;
23172 ashik.ali 10
import com.spice.profitmandi.common.util.Utils;
29515 tejbeer 11
import com.spice.profitmandi.common.web.client.RestClient;
33795 ranu 12
import com.spice.profitmandi.dao.entity.catalog.CustomerOfferItem;
22859 ashik.ali 13
import com.spice.profitmandi.dao.entity.catalog.Item;
25103 amit.gupta 14
import com.spice.profitmandi.dao.entity.catalog.TagListing;
33795 ranu 15
import com.spice.profitmandi.dao.entity.catalog.UpgradeOffer;
32420 amit.gupta 16
import com.spice.profitmandi.dao.entity.dtr.*;
17
import com.spice.profitmandi.dao.entity.fofo.*;
28978 amit.gupta 18
import com.spice.profitmandi.dao.entity.inventory.State;
24917 tejbeer 19
import com.spice.profitmandi.dao.entity.transaction.Order;
22859 ashik.ali 20
import com.spice.profitmandi.dao.entity.user.Address;
21
import com.spice.profitmandi.dao.entity.user.Counter;
22
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
27516 amit.gupta 23
import com.spice.profitmandi.dao.entity.warehouse.WarehouseInventoryItem;
24264 amit.gupta 24
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
23546 ashik.ali 25
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
23650 amit.gupta 26
import com.spice.profitmandi.dao.enumuration.fofo.ReturnType;
22859 ashik.ali 27
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
23655 amit.gupta 28
import com.spice.profitmandi.dao.enumuration.fofo.SettlementType;
29515 tejbeer 29
import com.spice.profitmandi.dao.enumuration.inventory.ScratchedGift;
28339 tejbeer 30
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
33795 ranu 31
import com.spice.profitmandi.dao.repository.catalog.*;
32420 amit.gupta 32
import com.spice.profitmandi.dao.repository.dtr.*;
33
import com.spice.profitmandi.dao.repository.fofo.*;
24854 amit.gupta 34
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
24917 tejbeer 35
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
22859 ashik.ali 36
import com.spice.profitmandi.dao.repository.user.AddressRepository;
37
import com.spice.profitmandi.dao.repository.user.CounterRepository;
38
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
27516 amit.gupta 39
import com.spice.profitmandi.dao.repository.warehouse.WarehouseInventoryItemRepository;
25724 amit.gupta 40
import com.spice.profitmandi.service.integrations.zest.InsuranceService;
31274 amit.gupta 41
import com.spice.profitmandi.service.integrations.zest.MobileInsurancePlan;
23418 ashik.ali 42
import com.spice.profitmandi.service.inventory.InventoryService;
23655 amit.gupta 43
import com.spice.profitmandi.service.inventory.PurchaseReturnService;
26891 amit.gupta 44
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
28166 tejbeer 45
import com.spice.profitmandi.service.offers.ItemCriteria;
22859 ashik.ali 46
import com.spice.profitmandi.service.pricing.PricingService;
47
import com.spice.profitmandi.service.scheme.SchemeService;
23655 amit.gupta 48
import com.spice.profitmandi.service.user.RetailerService;
32420 amit.gupta 49
import org.apache.logging.log4j.LogManager;
50
import org.apache.logging.log4j.Logger;
51
import org.hibernate.Session;
52
import org.hibernate.SessionFactory;
53
import org.json.JSONObject;
54
import org.springframework.beans.factory.annotation.Autowired;
55
import org.springframework.beans.factory.annotation.Qualifier;
56
import org.springframework.beans.factory.annotation.Value;
57
import org.springframework.cache.annotation.Cacheable;
58
import org.springframework.core.io.InputStreamResource;
59
import org.springframework.http.HttpHeaders;
60
import org.springframework.http.HttpStatus;
61
import org.springframework.http.ResponseEntity;
62
import org.springframework.stereotype.Component;
22859 ashik.ali 63
 
32420 amit.gupta 64
import javax.persistence.criteria.CriteriaBuilder;
65
import javax.persistence.criteria.CriteriaQuery;
66
import javax.persistence.criteria.Predicate;
67
import javax.persistence.criteria.Root;
68
import java.io.ByteArrayInputStream;
69
import java.io.InputStream;
70
import java.time.LocalDate;
71
import java.time.LocalDateTime;
72
import java.time.LocalTime;
73
import java.util.AbstractMap.SimpleEntry;
74
import java.util.*;
75
import java.util.function.Function;
76
import java.util.stream.Collectors;
77
 
22859 ashik.ali 78
@Component
79
public class OrderServiceImpl implements OrderService {
80
 
32145 tejbeer 81
    private static final Logger LOGGER = LogManager.getLogger(OrderServiceImpl.class);
22859 ashik.ali 82
 
32145 tejbeer 83
    private static Map<String, Integer> serialNumberOrderIdMap = new HashMap<>();
31030 amit.gupta 84
 
32145 tejbeer 85
    static {
86
        serialNumberOrderIdMap.put("862897055749275", 67228);
87
    }
31030 amit.gupta 88
 
32145 tejbeer 89
    @Autowired
90
    @Qualifier("fofoInventoryItemRepository")
91
    private InventoryItemRepository inventoryItemRepository;
27083 amit.gupta 92
 
32145 tejbeer 93
    @Autowired
94
    private StateGstRateRepository stateGstRateRepository;
23650 amit.gupta 95
 
32145 tejbeer 96
    @Autowired
97
    private SaholicInventoryService saholicInventoryService;
27083 amit.gupta 98
 
32145 tejbeer 99
    @Autowired
100
    private LiveDemoBillingRespository liveDemoBillingRespository;
24823 amit.gupta 101
 
32145 tejbeer 102
    @Autowired
103
    private InsuranceService insuranceService;
25724 amit.gupta 104
 
32145 tejbeer 105
    @Autowired
106
    @Qualifier("fofoCurrentInventorySnapshotRepository")
107
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
22859 ashik.ali 108
 
32145 tejbeer 109
    @Autowired
110
    private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
22859 ashik.ali 111
 
32145 tejbeer 112
    @Autowired
113
    private PurchaseReturnService purchaseReturnService;
23655 amit.gupta 114
 
32145 tejbeer 115
    @Autowired
116
    private RetailerService retailerService;
23655 amit.gupta 117
 
32145 tejbeer 118
    @Autowired
119
    private CustomerRepository customerRepository;
23650 amit.gupta 120
 
32145 tejbeer 121
    @Autowired
122
    private PurchaseReturnItemRepository purchaseReturnItemRepository;
22859 ashik.ali 123
 
32145 tejbeer 124
    @Autowired
125
    private AddressRepository addressRepository;
22859 ashik.ali 126
 
32145 tejbeer 127
    @Autowired
128
    private FofoLineItemRepository fofoLineItemRepository;
22859 ashik.ali 129
 
32145 tejbeer 130
    @Autowired
32816 ranu 131
    private FofoNonSerializeSerialRepository fofoNonSerializeSerialRepository;
132
 
133
    @Autowired
32145 tejbeer 134
    private WarehouseInventoryItemRepository warehouseInventoryItemRepository;
27516 amit.gupta 135
 
32145 tejbeer 136
    @Autowired
137
    private FofoOrderItemRepository fofoOrderItemRepository;
23650 amit.gupta 138
 
32145 tejbeer 139
    @Autowired
140
    private PaymentOptionRepository paymentOptionRepository;
22859 ashik.ali 141
 
32145 tejbeer 142
    @Autowired
143
    private CustomerReturnItemRepository customerReturnItemRepository;
23650 amit.gupta 144
 
32145 tejbeer 145
    @Autowired
146
    @Qualifier("fofoScanRecordRepository")
147
    private ScanRecordRepository scanRecordRepository;
22859 ashik.ali 148
 
32145 tejbeer 149
    @Autowired
150
    private FofoOrderRepository fofoOrderRepository;
22859 ashik.ali 151
 
32145 tejbeer 152
    @Autowired
153
    private RetailerRepository retailerRepository;
22859 ashik.ali 154
 
32145 tejbeer 155
    @Autowired
156
    private UserRepository userRepository;
22859 ashik.ali 157
 
32145 tejbeer 158
    @Autowired
159
    private UserAccountRepository userAccountRepository;
22859 ashik.ali 160
 
32145 tejbeer 161
    @Autowired
162
    private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
22859 ashik.ali 163
 
32145 tejbeer 164
    @Autowired
165
    private CustomerAddressRepository customerAddressRepository;
22859 ashik.ali 166
 
32145 tejbeer 167
    @Autowired
168
    @Qualifier("catalogItemRepository")
169
    private ItemRepository itemRepository;
23650 amit.gupta 170
 
32145 tejbeer 171
    @Autowired
172
    private InsuranceProviderRepository insuranceProviderRepository;
23650 amit.gupta 173
 
32145 tejbeer 174
    @Autowired
175
    private InsurancePolicyRepository insurancePolicyRepository;
24917 tejbeer 176
 
32145 tejbeer 177
    @Autowired
178
    private StateRepository stateRepository;
23650 amit.gupta 179
 
32145 tejbeer 180
    @Autowired
181
    private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
23650 amit.gupta 182
 
32145 tejbeer 183
    @Autowired
184
    private PricingService pricingService;
23650 amit.gupta 185
 
32145 tejbeer 186
    @Autowired
187
    private PrivateDealUserRepository privateDealUserRepository;
23650 amit.gupta 188
 
32145 tejbeer 189
    @Autowired
190
    private TagListingRepository tagListingRepository;
24823 amit.gupta 191
 
32145 tejbeer 192
    @Autowired
193
    private CounterRepository counterRepository;
23650 amit.gupta 194
 
32145 tejbeer 195
    @Autowired
196
    private FofoStoreRepository fofoStoreRepository;
23650 amit.gupta 197
 
32145 tejbeer 198
    @Autowired
199
    private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
23650 amit.gupta 200
 
32145 tejbeer 201
    @Autowired
202
    private SchemeService schemeService;
23650 amit.gupta 203
 
32145 tejbeer 204
    private static final List<Integer> orderIdsConsumed = new ArrayList<>();
28166 tejbeer 205
 
32145 tejbeer 206
    @Autowired
207
    @Qualifier("fofoInventoryService")
208
    private InventoryService inventoryService;
23650 amit.gupta 209
 
32145 tejbeer 210
    @Autowired
211
    private CustomerCreditNoteRepository customerCreditNoteRepository;
23650 amit.gupta 212
 
32145 tejbeer 213
    @Autowired
214
    private OrderRepository orderRepository;
24917 tejbeer 215
 
32145 tejbeer 216
    @Autowired
217
    private HygieneDataRepository hygieneDataRepository;
25640 tejbeer 218
 
32145 tejbeer 219
    @Autowired
220
    private SessionFactory sessionFactory;
28166 tejbeer 221
 
32145 tejbeer 222
    @Autowired
223
    private Mongo mongoClient;
28964 tejbeer 224
 
32145 tejbeer 225
    @Autowired
226
    private PendingOrderRepository pendingOrderRepository;
28964 tejbeer 227
 
32145 tejbeer 228
    @Autowired
33399 ranu 229
 
230
    private PendingOrderService pendingOrderService;
231
 
232
    @Autowired
32145 tejbeer 233
    private PendingOrderItemRepository pendingOrderItemRepository;
28166 tejbeer 234
 
32145 tejbeer 235
    @Autowired
236
    private ScratchOfferRepository scratchOfferRepository;
29515 tejbeer 237
 
32145 tejbeer 238
    @Autowired
239
    RestClient restClient;
29515 tejbeer 240
 
33715 ranu 241
    @Autowired
242
    UpSaleOrderRepository upSaleOrderRepository;
243
 
33795 ranu 244
    @Autowired
245
    private CustomerOfferRepository customerOfferRepository;
246
 
247
    @Autowired
248
    private CustomerOfferItemRepository customerOfferItemRepository;
249
 
250
    @Autowired
251
    private UpgradeOfferRepository upgradeOfferRepository;
252
 
32145 tejbeer 253
    @Value("${prod}")
254
    private boolean prodEnv;
29515 tejbeer 255
 
32145 tejbeer 256
    private static final String SMS_GATEWAY = "http://api.pinnacle.in/index.php/sms/send";
257
    private static final String SENDER = "SMTDKN";
29515 tejbeer 258
 
32145 tejbeer 259
    public static final String APP_DOWNLOAD_BILLING_TEMPLATE_ID = "1507163542403945677";
29515 tejbeer 260
 
32145 tejbeer 261
    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";
29515 tejbeer 262
 
32145 tejbeer 263
    @Override
264
    public int createOrder(CreateOrderRequest createOrderRequest, int fofoId, boolean accessoriesDeals) throws ProfitMandiBusinessException {
265
        LOGGER.info("fofoId -- {} Order Request -- {}", fofoId, createOrderRequest);
266
        CustomCustomer customCustomer = createOrderRequest.getCustomer();
267
        Customer customer = customerRepository.selectById(customCustomer.getCustomerId());
22872 ashik.ali 268
 
32145 tejbeer 269
        if (!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
270
            LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
271
            throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER, customCustomer.getGstNumber(), "VE_1072");
272
        }
23650 amit.gupta 273
 
32145 tejbeer 274
        Map<Integer, Integer> itemIdQuantity = new HashMap<>(); // this is for error
275
        Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
276
        Map<Integer, Float> lineItemPrice = new HashMap<>(); // this is for pricing error
23650 amit.gupta 277
 
32145 tejbeer 278
        float totalAmount = 0;
279
        boolean noGST = false;
33520 amit.gupta 280
        int changedTotalBillAmount = 0;
281
        for (CustomPaymentOption cpo : createOrderRequest.getPaymentOptions()) {
33399 ranu 282
            changedTotalBillAmount += cpo.getAmount();
283
        }
32145 tejbeer 284
        for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
33520 amit.gupta 285
            if (customFofoOrderItem.getPoiId() > 0) {
33399 ranu 286
                PendingOrderItem pendingOrderItem = pendingOrderItemRepository.selectById(customFofoOrderItem.getPoiId());
33520 amit.gupta 287
                if (customFofoOrderItem.getQuantity() > pendingOrderItem.getQuantity()) {
33414 amit.gupta 288
                    throw new ProfitMandiBusinessException("itemIdQuantity", customFofoOrderItem.getItemId(), "Quantity should not be greater than order item quantity");
33399 ranu 289
                }
33520 amit.gupta 290
                if (pendingOrderItem.getQuantity() > customFofoOrderItem.getQuantity()) {
291
                    pendingOrderService.duplicatePendingOrder(pendingOrderItem, customFofoOrderItem.getQuantity());
33399 ranu 292
                }
293
            }
32145 tejbeer 294
            // itemIds.add(customFofoOrderItem.getItemId());
295
            Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
296
            if (!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.size()) {
297
                itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
298
            }
299
            if (!(customFofoOrderItem.getSellingPrice() > 0)) {
300
                lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
301
            } else {
33554 tejus.loha 302
                totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
32145 tejbeer 303
                for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
304
                    if (serialNumberDetail.getAmount() > 0) {
305
                        totalAmount = totalAmount + serialNumberDetail.getAmount();
306
                    }
307
                }
308
            }
23650 amit.gupta 309
 
32145 tejbeer 310
            itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
311
        }
312
        if (!itemIdQuantity.isEmpty()) {
313
            // if item quantity does not match with given serialnumbers size
314
            LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
315
            throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
316
            // return "error";
317
        }
23650 amit.gupta 318
 
32145 tejbeer 319
        this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
23650 amit.gupta 320
 
32145 tejbeer 321
        if (!lineItemPrice.isEmpty()) {
322
            // given fofo line item price must be greater than zero
323
            LOGGER.error("requested itemId's selling price must greater than 0");
324
            throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
325
        }
22859 ashik.ali 326
 
32145 tejbeer 327
        List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
23650 amit.gupta 328
 
32145 tejbeer 329
        this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 330
 
32145 tejbeer 331
        List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
332
        if (items.size() != itemIdCustomFofoOrderItemMap.keySet().size()) {
333
            LOGGER.error("Requested ItemIds not found in catalog");
334
            // invalid itemIds
335
            throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(), "FFORDR_1003");
336
        }
23650 amit.gupta 337
 
32145 tejbeer 338
        Map<Integer, Item> itemMap = this.toItemMap(items);
23650 amit.gupta 339
 
32145 tejbeer 340
        Set<Integer> nonSerializedItemIds = new HashSet<>();
341
        Set<String> serialNumbers = new HashSet<>();
342
        List<InsuranceModel> insuredModels = new ArrayList<>();
343
        for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
344
            Item item = itemMap.get(customFofoOrderItem.getItemId());
345
            noGST = item.getHsnCode().equals("NOGST");
346
            if (item.getType().equals(ItemType.SERIALIZED)) {
347
                for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
348
                    serialNumbers.add(serialNumberDetail.getSerialNumber());
349
                    if (serialNumberDetail.getAmount() > 0) {
350
                        if (customer.getEmailId() == null || customer.getEmailId().equals("")) {
351
                            throw new ProfitMandiBusinessException("Email Id is required for insurance", "Email Id is required for insurance", "Email Id is required for insurance");
352
                        }
353
                        InsuranceModel im = new InsuranceModel();
354
                        im.setBrand(item.getBrand());
355
                        im.setColor(item.getColor());
356
                        im.setModelName(item.getModelName() + item.getModelNumber());
357
                        im.setInsuranceAmount(serialNumberDetail.getAmount());
358
                        im.setDeviceSellingPrice(customFofoOrderItem.getSellingPrice());
359
                        im.setInsuranceId(serialNumberDetail.getInsurance());
360
                        im.setSerialNumber(serialNumberDetail.getSerialNumber());
361
                        im.setMemory(serialNumberDetail.getMemory());
362
                        im.setRam(serialNumberDetail.getRam());
363
                        im.setMfgDate(serialNumberDetail.getMfgDate());
364
                        insuredModels.add(im);
365
                        // Check for free insurance code
366
                        try {
33520 amit.gupta 367
                            Map<String, List<MobileInsurancePlan>> mobileInsurancePlanMap = insuranceService.getAllPlans(item.getId(), im.getDeviceSellingPrice(), false);
33436 ranu 368
                            LOGGER.info("mobileInsurancePlanMap - {}", mobileInsurancePlanMap);
32145 tejbeer 369
                            MobileInsurancePlan mobileInsurancePlan = mobileInsurancePlanMap.entrySet().stream().flatMap(x -> x.getValue().stream()).filter(x -> x.getProductId().equals(serialNumberDetail.getInsurance())).findFirst().get();
370
                            LOGGER.info("SerialNumber Detqail InsuranceId - {}", serialNumberDetail.getInsurance());
371
                            LOGGER.info("product description - {}", mobileInsurancePlan);
372
                            if (mobileInsurancePlan.getPlanName().equals("OneAssist Damage Protection Plan")) {
373
                                MobileInsurancePlan freePlan = mobileInsurancePlanMap.get("Prolong Extendended Warranty(SmartDukaan Special Price)").get(0);
374
                                InsuranceModel imFree = new InsuranceModel();
375
                                imFree.setBrand(item.getBrand());
376
                                imFree.setColor(item.getColor());
377
                                imFree.setModelName(item.getModelName() + item.getModelNumber());
378
                                imFree.setInsuranceAmount(0);
379
                                imFree.setDeviceSellingPrice(customFofoOrderItem.getSellingPrice());
380
                                imFree.setInsuranceId(freePlan.getProductId());
381
                                imFree.setSerialNumber(serialNumberDetail.getSerialNumber());
382
                                imFree.setMemory(serialNumberDetail.getMemory());
383
                                imFree.setRam(serialNumberDetail.getRam());
384
                                imFree.setMfgDate(serialNumberDetail.getMfgDate());
385
                                insuredModels.add(imFree);
386
                            }
387
                        } catch (Exception e) {
388
                            LOGGER.error("Exception - {}", e);
389
                            throw new ProfitMandiBusinessException("problem fetching plans", "problem fetching plans", "problem fetching plans");
390
                        }
391
                    }
31274 amit.gupta 392
 
32145 tejbeer 393
                }
394
            } else {
395
                nonSerializedItemIds.add(customFofoOrderItem.getItemId());
396
            }
397
        }
23650 amit.gupta 398
 
32145 tejbeer 399
        Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
400
        Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
401
        // Map<String, Float> serialNumberItemPrice = new HashMap<>();
23650 amit.gupta 402
 
32145 tejbeer 403
        if (!serialNumbers.isEmpty()) {
404
            List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, serialNumbers, false);
405
            LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
406
            for (InventoryItem inventoryItem : serializedInventoryItems) {
407
                if (inventoryItem.getGoodQuantity() == 1) {
408
                    if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())) {
409
                        serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
410
                    } else {
411
                        Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
412
                        itemIdInventoryItems.add(inventoryItem);
413
                        serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
414
                    }
415
                }
416
            }
417
        }
23418 ashik.ali 418
 
32145 tejbeer 419
        if (!nonSerializedItemIds.isEmpty()) {
420
            List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId, nonSerializedItemIds);
421
            LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
422
            for (InventoryItem it : nonSerializedInventoryItems) {
423
                if (it.getGoodQuantity() > 0) {
424
                    if (nonSerializedInventoryItemMap.containsKey(it.getItemId())) {
425
                        nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
426
                    } else {
427
                        Set<InventoryItem> tmp = new HashSet<>();
428
                        tmp.add(it);
429
                        nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
430
                    }
431
                }
432
            }
433
        }
23650 amit.gupta 434
 
32145 tejbeer 435
        this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);
22859 ashik.ali 436
 
32145 tejbeer 437
        Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
438
        Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); // to keep track of inventoryitem quanity
439
        // used for scan records insertion
22859 ashik.ali 440
 
32145 tejbeer 441
        LOGGER.info("itemMap keys {}", itemMap.keySet());
442
        // Lets reduce quantity and decide what inventory items to use.
443
        for (Item item : items) {
444
            if (item.getType().equals(ItemType.SERIALIZED)) {
445
                // TODO:handle null
446
                if (serializedInventoryItemMap.get(item.getId()) == null || itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().size() != serializedInventoryItemMap.get(item.getId()).size()) {
24440 amit.gupta 447
 
32145 tejbeer 448
                    List<String> invalidSerialNumbers = itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream().map(x -> x.getSerialNumber()).collect(Collectors.toList());
449
                    throw new ProfitMandiBusinessException("invalidSerialNumbers", invalidSerialNumbers, "FFORDR_1004");
450
                }
451
                List<String> serialNumberList = liveDemoBillingRespository.selectAllSerialNumber();
24823 amit.gupta 452
 
32145 tejbeer 453
                Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
454
                for (InventoryItem inventoryItem : inventoryItemsSerializedserialized) {
455
                    inventoryItem.setGoodQuantity(0);
456
                    inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
457
                    if (serialNumberList.contains(inventoryItem.getSerialNumber())) {
458
                        LiveDemoSerialNumber liveDemoSerialNumber = liveDemoBillingRespository.selectBySerialNumber(inventoryItem.getSerialNumber());
459
                        liveDemoBillingRespository.delete(liveDemoSerialNumber);
460
                    }
461
                }
462
                inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
463
            } else {
464
                Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
465
                int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
466
                int totalLeft = quantityToBill;
467
                Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
468
                if (inventoryItemsNonSerialized != null) {
469
                    for (InventoryItem inventoryItem : inventoryItemsNonSerialized) {
470
                        if (totalLeft > 0) {
471
                            int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
472
                            inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
473
                            inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity() - toUse);
474
                            totalLeft = totalLeft - toUse;
475
                            inventoryItemsNonSerializedUsed.add(inventoryItem);
476
                        }
477
                    }
478
                }
23650 amit.gupta 479
 
32145 tejbeer 480
                if (totalLeft > 0) {
481
                    // not enough quanity for non-serialized
482
                    LOGGER.error("not enough quanity for non-serialized");
483
                    throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft, "FFORDR_1005");
484
                }
485
                inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
486
            }
487
        }
23650 amit.gupta 488
 
32145 tejbeer 489
        Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
490
        LOGGER.info("itemIdMopMap {}", itemIdMopPriceMap);
491
        if (accessoriesDeals) {
32420 amit.gupta 492
            this.validateDpPrice(fofoId, itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
32145 tejbeer 493
        } else {
32420 amit.gupta 494
            this.validateMopPrice(fofoId, itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
32145 tejbeer 495
        }
23650 amit.gupta 496
 
32145 tejbeer 497
        String fofoStoreCode = this.getFofoStoreCode(fofoId);
498
        String documentNumber = null;
499
        if (noGST) {
500
            documentNumber = this.getSecurityDepositNumber(fofoId, fofoStoreCode);
24275 amit.gupta 501
 
32145 tejbeer 502
        } else {
503
            documentNumber = this.getInvoiceNumber(fofoId, fofoStoreCode);
504
        }
22859 ashik.ali 505
 
32627 ranu 506
        CustomerAddress customerAddress = null;
507
        if (customCustomer.getCustomerAddressId() != 0) {
508
            customerAddress = customer.getCustomerAddress().stream().filter(x -> x.getId() == customCustomer.getCustomerAddressId()).findFirst().get();
509
        }
510
        FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId, documentNumber, totalAmount, customCustomer.getCustomerAddressId());
23650 amit.gupta 511
 
32145 tejbeer 512
        this.createPaymentOptions(fofoOrder, createOrderRequest.getPaymentOptions());
23650 amit.gupta 513
 
32145 tejbeer 514
        int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
23650 amit.gupta 515
 
32145 tejbeer 516
        Address retailerAddress = addressRepository.selectById(retailerAddressId);
23650 amit.gupta 517
 
32145 tejbeer 518
        Integer stateId = null;
32634 amit.gupta 519
        if (customerAddress == null || customerAddress.getState() == null || customerAddress.getState().equals(retailerAddress.getState())) {
32145 tejbeer 520
            try {
32634 amit.gupta 521
                State state = stateRepository.selectByName(retailerAddress.getState());
32145 tejbeer 522
                stateId = Long.valueOf(state.getId()).intValue();
523
            } catch (Exception e) {
524
                LOGGER.error("Unable to get state rates");
525
            }
526
        }
23650 amit.gupta 527
 
32145 tejbeer 528
        for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
529
            FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(), itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), stateId);
23650 amit.gupta 530
 
32816 ranu 531
            Item item = itemMap.get(customFofoOrderItem.getItemId());
532
            if (item.getType().equals(ItemType.NON_SERIALIZED)) {
533
                if (customFofoOrderItem.getCustomSerialNumbers() != null && !customFofoOrderItem.getCustomSerialNumbers().isEmpty()) {
534
                    persistNonSerializedWithCustomSerialNumber(customFofoOrderItem, fofoOrderItem.getId());
535
                } else {
536
                    LOGGER.info("Custom serial numbers are empty. Not persisting data.");
537
                }
538
            }
539
 
540
 
32145 tejbeer 541
            Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
23650 amit.gupta 542
 
32145 tejbeer 543
            this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
23650 amit.gupta 544
 
32145 tejbeer 545
            this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
23650 amit.gupta 546
 
32145 tejbeer 547
            this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed, fofoOrder.getId());
548
        }
23650 amit.gupta 549
 
32145 tejbeer 550
        List<FofoOrderItem> fofoItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
25647 tejbeer 551
 
32145 tejbeer 552
        boolean smartPhone = false;
32892 ranu 553
        for (FofoOrderItem fofoOrderItem : fofoItems) {
554
            Item item = itemRepository.selectById(fofoOrderItem.getItemId());
555
 
556
            if (item.isSmartPhone()) {
557
                LOGGER.info("fofoItem {}", fofoOrderItem);
32145 tejbeer 558
                smartPhone = true;
559
            }
32892 ranu 560
        }
31172 tejbeer 561
 
32892 ranu 562
        if (!smartPhone) {
563
            LOGGER.warn("No smartphones found in fofoItems.");
32145 tejbeer 564
        }
31172 tejbeer 565
 
32892 ranu 566
 
32145 tejbeer 567
        if (smartPhone) {
568
            this.createAndGetHygieneData(fofoOrder.getId(), fofoOrder.getFofoId());
569
        }
570
        // insurance calculation is insurance flag is enabled
571
        //
572
        if (insuredModels.size() > 0) {
573
            LOGGER.info("Processing insurane for serialNumbers");
574
            LOGGER.info("InsuranceModels {}", insuredModels);
575
            LocalDate customerDateOfBirth = LocalDate.from(createOrderRequest.getCustomer().getDateOfBirth());
576
            fofoOrder.setDateOfBirth(customerDateOfBirth);
577
            for (InsuranceModel insuranceModel : insuredModels) {
578
                LOGGER.info("Creating insurance for {}", insuranceModel.getInsuranceId());
33715 ranu 579
                insuranceService.createInsurance(fofoOrder, insuranceModel, false);
32145 tejbeer 580
            }
581
        }
28339 tejbeer 582
 
32145 tejbeer 583
        schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
31993 amit.gupta 584
 
32145 tejbeer 585
        if (createOrderRequest.getPoId() != 0) {
586
            PendingOrder po = pendingOrderRepository.selectById(createOrderRequest.getPoId());
587
            po.setBilledAmount(po.getBilledAmount() + totalAmount);
33520 amit.gupta 588
            for (CustomFofoOrderItem cfoi : createOrderRequest.getFofoOrderItems()) {
33399 ranu 589
                PendingOrderItem poi = pendingOrderItemRepository.selectById(cfoi.getPoiId());
590
                poi.setStatus(OrderStatus.BILLED);
591
                poi.setBilledTimestamp(LocalDateTime.now());
592
            }
33436 ranu 593
            po.setStatus(OrderStatus.BILLED);
33399 ranu 594
 
32145 tejbeer 595
        }
32961 amit.gupta 596
        //Process scratch
597
        this.processScratchOffer(fofoOrder);
29515 tejbeer 598
 
33795 ranu 599
//        persist the data of upgrade offer table
600
        for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
601
            if (customFofoOrderItem.getCustomerOfferItemId() > 0) {
602
                UpgradeOffer upgradeOffer = new UpgradeOffer();
603
                upgradeOffer.setOrderId(fofoOrder.getId());
604
                upgradeOffer.setCustomerOfferItemId(customFofoOrderItem.getCustomerOfferItemId());
605
                upgradeOffer.setItemId(customFofoOrderItem.getItemId());
606
 
607
                Set<SerialNumberDetail> serialNumberDetails = customFofoOrderItem.getSerialNumberDetails();
608
 
609
                if (!customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
610
                    String serialNumber = serialNumberDetails.iterator().next().getSerialNumber();
611
                    upgradeOffer.setSerialNumber(serialNumber);
612
 
613
//                Set<String> serialNumbersSet = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
614
//                LOGGER.info("serialNumbersSet.toString() {}",serialNumbersSet.toString());
615
//                upgradeOffer.setSerialNumber(serialNumbersSet.toString());
616
                } else {
617
                    upgradeOffer.setSerialNumber(null); // Handle case where there is no serial number detail
618
                }
619
                upgradeOffer.setCreatedTimestamp(LocalDateTime.now());
33838 ranu 620
                upgradeOffer.setPaymentStatus(UpgradeOfferPaymentStatus.PENDING);
621
                upgradeOffer.setStatusDescription(UpgradeOfferPaymentStatus.PENDING.getValue());
33795 ranu 622
                upgradeOfferRepository.persist(upgradeOffer);
623
            }
624
        }
625
 
626
//        enable it fo upsell call
33715 ranu 627
        if (smartPhone) {
628
            if (fofoOrder.getId() > 0) {
629
                List<InsurancePolicy> insurancePolicies = insurancePolicyRepository
630
                        .selectByRetailerIdInvoiceNumber(fofoOrder.getInvoiceNumber());
631
                if (insurancePolicies.isEmpty()) {
632
                    List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
633
                    for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
634
                        Item item = itemRepository.selectById(fofoOrderItem.getItemId());
635
                        if (item.isSmartPhone()) {
636
                            UpSaleOrder upSaleOrder = new UpSaleOrder();
637
                            upSaleOrder.setCreatedTimestamp(LocalDateTime.now());
638
                            upSaleOrder.setOrderId(fofoOrder.getId());
33718 ranu 639
                            upSaleOrder.setFofoId(fofoOrder.getFofoId());
33715 ranu 640
                            upSaleOrderRepository.persist(upSaleOrder);
641
                            break; // Exit the loop after persisting the UpSaleOrder for the first smartphone
642
                        }
643
                    }
644
                }
645
            }
646
        }
33674 ranu 647
 
32961 amit.gupta 648
        return fofoOrder.getId();
649
    }
650
 
33665 ranu 651
    static Map<Double, List<ScratchedGift>> GIFT_SERIES = new TreeMap<>(Comparator.reverseOrder());
32961 amit.gupta 652
 
32816 ranu 653
    private void persistNonSerializedWithCustomSerialNumber(CustomFofoOrderItem customFofoOrderItem, int orderItemId) {
654
        // Create a new instance of FofoNonSerializeSerial
655
        for (String accSerialNumber : customFofoOrderItem.getCustomSerialNumbers()) {
656
            if (!accSerialNumber.isEmpty()) {
657
                FofoNonSerializeSerial nonSerializeSerial = new FofoNonSerializeSerial();
658
 
659
                // Populate the entity with relevant information
660
                nonSerializeSerial.setOrderItemId(orderItemId);
661
                nonSerializeSerial.setSerialNumber(accSerialNumber);
662
 
663
                // Save the entity to the database
664
                fofoNonSerializeSerialRepository.persist(nonSerializeSerial);
665
            }
666
 
667
        }
668
    }
669
 
670
 
32145 tejbeer 671
    public void sendAppDownloadBillingOffer(String mobileNumber) throws Exception {
672
        String sdurl = "http://surl.li/anhfn";
673
        try {
674
            if (prodEnv) {
675
                this.sendSms(APP_DOWNLOAD_BILLING_TEMPLATE_ID, String.format(APP_DOWNLOAD_BILLING_OFFER, sdurl), mobileNumber);
676
            }
677
        } catch (Exception e) {
678
            e.printStackTrace();
679
        }
29515 tejbeer 680
 
32145 tejbeer 681
    }
29515 tejbeer 682
 
32145 tejbeer 683
    public void sendSms(String dltTemplateId, String message, String mobileNumber) throws Exception {
684
        Map<String, String> map = new HashMap<>();
29515 tejbeer 685
 
32145 tejbeer 686
        map.put("sender", SENDER);
687
        map.put("messagetype", "TXT");
688
        map.put("apikey", "b866f7-c6c483-682ff5-054420-ad9e2c");
29515 tejbeer 689
 
32145 tejbeer 690
        map.put("numbers", "91" + mobileNumber);
691
        LOGGER.info("Message {}", message);
692
        // OTP Message Template
693
        map.put("message", message);
694
        map.put("dlttempid", dltTemplateId);
29515 tejbeer 695
 
32145 tejbeer 696
        String response = restClient.post(SMS_GATEWAY, map, new HashMap<>());
697
        LOGGER.info(response);
29515 tejbeer 698
 
32145 tejbeer 699
    }
29515 tejbeer 700
 
701
 
32218 tejbeer 702
    private void createScratchOffer(int fofoId, String invoiceNumber, int customerId) {
29515 tejbeer 703
 
32586 ranu 704
        //ScratchedGift gift = getScratchedGiftRandom(fofoId, customerId);
705
 
706
 
707
        //  LocalDateTime endDate = LocalDateTime.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), 27, 21, 00);
32599 ranu 708
        List<ScratchOffer> scratchOffers = scratchOfferRepository.selectBycCustomerIdAndDate(customerId, ProfitMandiConstants.SCRATCH_OFFER_START_DATE, ProfitMandiConstants.SCRATCH_OFFER_END_DATE);
32605 ranu 709
        if (scratchOffers.size() == 0) {
32599 ranu 710
            ScratchOffer so2 = new ScratchOffer();
711
            so2.setInvoiceNumber(invoiceNumber);
712
            so2.setScratched(false);
713
            so2.setCreatedTimestamp(LocalDateTime.now());
33679 ranu 714
            so2.setExpiredTimestamp(ProfitMandiConstants.SCRATCH_OFFER_END_DATE.plusDays(1).atTime(LocalTime.MAX));
32599 ranu 715
            so2.setOfferName(ScratchedGift.BLNT);
716
            so2.setCustomerId(customerId);
32586 ranu 717
 
32599 ranu 718
            LocalDateTime today830PM = LocalDate.now().atTime(20, 30);
719
            LocalDateTime today9PM = LocalDate.now().atTime(21, 0);
33667 ranu 720
            so2.setUnlockedAt(LocalDateTime.now());
32586 ranu 721
 
33667 ranu 722
//            if (LocalDateTime.now().isAfter(today830PM)) {
723
//                so2.setUnlockedAt(today9PM.plusDays(0));
724
//            } else {
725
//                so2.setUnlockedAt(today9PM);
726
//            }
32599 ranu 727
            scratchOfferRepository.persist(so2);
32586 ranu 728
        }
729
    }
33665 ranu 730
    private static Map<ScratchedGift, Integer> GIFT_QUANTITIES = new HashMap<>();
32586 ranu 731
 
33665 ranu 732
    static {
733
        GIFT_QUANTITIES.put(ScratchedGift.MINI_LUNCH_BOX, 500);
734
        GIFT_QUANTITIES.put(ScratchedGift.THREE_SET_CONTAINER, 250);
735
        GIFT_QUANTITIES.put(ScratchedGift.CASSROLE, 250);
736
        GIFT_QUANTITIES.put(ScratchedGift.INSULATED_FLASK, 250);
737
        GIFT_QUANTITIES.put(ScratchedGift.JUICE_JUG, 250);
738
        GIFT_QUANTITIES.put(ScratchedGift.JUICER, 11);
739
        GIFT_QUANTITIES.put(ScratchedGift.HAIR_DRYER, 16);
740
        GIFT_QUANTITIES.put(ScratchedGift.CHOPPER, 20);
741
        GIFT_QUANTITIES.put(ScratchedGift.BOTTLE, 12);
742
        GIFT_QUANTITIES.put(ScratchedGift.ELECTRIC_KETTLE, 137);
743
        GIFT_QUANTITIES.put(ScratchedGift.BOWL_SET, 134);
744
        GIFT_QUANTITIES.put(ScratchedGift.BOTTLE_MUG, 28);
745
        GIFT_QUANTITIES.put(ScratchedGift.EW, 1000);
746
    }
32892 ranu 747
 
32960 amit.gupta 748
    static {
33665 ranu 749
        GIFT_SERIES.put(0.0, Arrays.asList(ScratchedGift.MINI_LUNCH_BOX, ScratchedGift.BOWL_SET, ScratchedGift.THREE_SET_CONTAINER, ScratchedGift.BOTTLE, ScratchedGift.BOTTLE_MUG));
750
        GIFT_SERIES.put(20001.0, Arrays.asList(ScratchedGift.CASSROLE, ScratchedGift.INSULATED_FLASK, ScratchedGift.JUICE_JUG));
751
        GIFT_SERIES.put(25001.0, Arrays.asList(ScratchedGift.ELECTRIC_KETTLE));
752
        GIFT_SERIES.put(35001.0, Arrays.asList(ScratchedGift.JUICER, ScratchedGift.HAIR_DRYER, ScratchedGift.CHOPPER));
753
    }
754
 
755
    List<Double> PRICE_RANGE = Arrays.asList(0.0, 20001.0, 25001.0, 35001.0);
756
 
757
    @Override
758
    public void processScratchOffer(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
759
        boolean isSmartPhonePurchased = false;
760
        float maxPurchaseValue = 0;
761
        List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
762
        for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
763
            Item item = itemRepository.selectById(fofoOrderItem.getItemId());
764
 
765
            if (item.isSmartPhone()) {
766
                LOGGER.info("fofoItem {}", fofoOrderItem);
767
                isSmartPhonePurchased = true;
768
                maxPurchaseValue = Math.max(fofoOrderItem.getSellingPrice(), maxPurchaseValue);
769
 
770
            }
771
        }
772
        LocalDate startDate = ProfitMandiConstants.SCRATCH_OFFER_START_DATE;
773
        LocalDate endDate = ProfitMandiConstants.SCRATCH_OFFER_END_DATE;
774
        boolean specificPriceOffer = ProfitMandiConstants.SPECIFIC_PRICE_OFFER;
775
        boolean randomOffer = ProfitMandiConstants.RANDOM_OFFER;
776
 
777
        if (isSmartPhonePurchased) {
778
 
779
            if (LocalDateTime.now().isAfter(startDate.atStartOfDay()) && LocalDateTime.now().isBefore(endDate.atTime(Utils.MAX_TIME))) {
780
                Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
781
                try {
782
                    this.sendAppDownloadBillingOffer(customer.getMobileNumber());
783
                } catch (Exception e) {
784
                    // TODO Auto-generated catch block
785
                    e.printStackTrace();
786
                }
787
                if (specificPriceOffer) {
788
                    this.createSpecificPriceScratchOffer(fofoOrder.getInvoiceNumber(), fofoOrder.getCustomerId(), maxPurchaseValue);
789
                } else if (randomOffer) {
790
                    this.createRandomScratchOffer(fofoOrder.getInvoiceNumber(), fofoOrder.getCustomerId());
791
                    LOGGER.info("randomOffer {}", randomOffer);
792
                } else {
793
                    this.createScratchOffer(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber(), fofoOrder.getCustomerId());
794
                }
795
 
796
            }
797
        }
798
    }
799
 
800
    @Override
801
    public ScratchedGift getSelectedGift(double purchaseAmount) {
802
        //Iterating map in reverse order of values
803
        Map<ScratchedGift, Long> scratchOfferCountMap = scratchOfferRepository.countOffersByDateRange(ProfitMandiConstants.SCRATCH_OFFER_START_DATE, ProfitMandiConstants.SCRATCH_OFFER_END_DATE);
804
 
805
        RandomCollection<ScratchedGift> giftRandomCollection = createDynamicGiftSeries(scratchOfferCountMap, purchaseAmount);
806
        if (giftRandomCollection.size() > 0) {
807
            return giftRandomCollection.next();
33677 ranu 808
        } else if (purchaseAmount < 35000) {
33665 ranu 809
            // Default gift if no match found
810
            return ScratchedGift.EW;
33674 ranu 811
        } else {
812
            return ScratchedGift.BLNT;
33665 ranu 813
        }
814
    }
815
 
816
    public RandomCollection<ScratchedGift> createDynamicGiftSeries(Map<ScratchedGift, Long> soldGiftContMap, Double sellingPrice) {
817
        int index = 0;
818
        RandomCollection<ScratchedGift> randomCollection = new RandomCollection<>();
819
        for (Double price : PRICE_RANGE) {
820
            if (sellingPrice >= price) {
821
                int divisor = PRICE_RANGE.size() - index;
822
                for (ScratchedGift gift : GIFT_SERIES.get(price)) {
823
                    int remainingQty = GIFT_QUANTITIES.get(gift) - soldGiftContMap.getOrDefault(gift, 0l).intValue();
824
                    if (remainingQty == 0) {
825
                        continue;
826
                    }
827
                    if (remainingQty > divisor) {
828
                        randomCollection.add(remainingQty / divisor, gift);
829
                    } else {
830
                        randomCollection.add(remainingQty, gift);
831
                    }
832
 
833
                }
834
                index++;
835
            }
836
        }
837
        return randomCollection;
838
    }
839
 
840
    /*static {
32960 amit.gupta 841
        RandomCollection<ScratchedGift> map1 = new RandomCollection<ScratchedGift>().
842
                add(100d, ScratchedGift.GIFT_BOWL);
843
        GIFT_SERIES.put(0.0, map1);
844
        //Map<ScratchedGift, Double> map2 = new HashMap<>();
845
        RandomCollection<ScratchedGift> map2 = new RandomCollection<ScratchedGift>()
846
                .add(40d, ScratchedGift.GIFT_BOWL)
847
                .add(20d, ScratchedGift.NECK_BAND)
848
                .add(30d, ScratchedGift.FLASKNMUG)
849
                .add(10d, ScratchedGift.ELECTRIC_KETTLE);
850
        GIFT_SERIES.put(10001.0, map2);
851
        RandomCollection<ScratchedGift> map3 = new RandomCollection<ScratchedGift>()
852
                .add(25d, ScratchedGift.GIFT_BOWL)
853
                .add(30d, ScratchedGift.NECK_BAND)
854
                .add(10d, ScratchedGift.SPEAKER)
855
                .add(25d, ScratchedGift.FLASKNMUG)
856
                .add(10d, ScratchedGift.ELECTRIC_KETTLE);
857
        GIFT_SERIES.put(18001.0, map3);
858
        RandomCollection<ScratchedGift> map4 = new RandomCollection<ScratchedGift>()
859
                .add(30d, ScratchedGift.NECK_BAND)
860
                .add(20d, ScratchedGift.SPEAKER)
861
                .add(20d, ScratchedGift.FLASKNMUG)
862
                .add(30d, ScratchedGift.ELECTRIC_KETTLE);
863
        GIFT_SERIES.put(25001.0, map4);
864
        RandomCollection<ScratchedGift> map5 = new RandomCollection<ScratchedGift>()
865
                .add(40d, ScratchedGift.SPEAKER)
866
                .add(60d, ScratchedGift.SMART_WATCH);
32892 ranu 867
 
32960 amit.gupta 868
        GIFT_SERIES.put(50001.0, map5);
33665 ranu 869
    }*/
32892 ranu 870
 
32960 amit.gupta 871
 
872
    private void createSpecificPriceScratchOffer(String invoiceNumber, int customerId, float purchaseAmount) {
873
        ScratchedGift selectedGift = getSelectedGift(purchaseAmount);
33142 ranu 874
        List<ScratchOffer> scratchOffers = scratchOfferRepository.selectBycCustomerIdAndDate(customerId, ProfitMandiConstants.SCRATCH_OFFER_START_DATE, ProfitMandiConstants.SCRATCH_OFFER_END_DATE);
875
        if (scratchOffers.size() == 0) {
876
            ScratchOffer so2 = new ScratchOffer();
877
            so2.setInvoiceNumber(invoiceNumber);
878
            so2.setScratched(false);
879
            so2.setCreatedTimestamp(LocalDateTime.now());
33679 ranu 880
            so2.setExpiredTimestamp(ProfitMandiConstants.SCRATCH_OFFER_END_DATE.plusDays(1).atTime(LocalTime.MAX));
33142 ranu 881
            so2.setOfferName(selectedGift);
882
            so2.setCustomerId(customerId);
883
            so2.setUnlockedAt(LocalDateTime.now());
884
            scratchOfferRepository.persist(so2);
885
        }
886
    }
32960 amit.gupta 887
 
33142 ranu 888
    private void createRandomScratchOffer(String invoiceNumber, int customerId) {
889
        ScratchedGift selectedGift = getScratchedGiftRandomAccordingQuantity(customerId);
32892 ranu 890
        List<ScratchOffer> scratchOffers = scratchOfferRepository.selectBycCustomerIdAndDate(customerId, ProfitMandiConstants.SCRATCH_OFFER_START_DATE, ProfitMandiConstants.SCRATCH_OFFER_END_DATE);
891
        if (scratchOffers.size() == 0) {
892
            ScratchOffer so2 = new ScratchOffer();
893
            so2.setInvoiceNumber(invoiceNumber);
894
            so2.setScratched(false);
895
            so2.setCreatedTimestamp(LocalDateTime.now());
33679 ranu 896
            so2.setExpiredTimestamp(ProfitMandiConstants.SCRATCH_OFFER_END_DATE.plusDays(1).atTime(LocalTime.MAX));
32892 ranu 897
            so2.setOfferName(selectedGift);
898
            so2.setCustomerId(customerId);
899
            so2.setUnlockedAt(LocalDateTime.now());
900
            scratchOfferRepository.persist(so2);
901
        }
902
    }
903
 
33247 ranu 904
    private ScratchedGift getScratchedGiftRandom(int fofoId, int customerId) throws ProfitMandiBusinessException {
32218 tejbeer 905
        Map<Integer, ScratchedGift> giftSeries = new HashMap<>();
906
        giftSeries.put(1, ScratchedGift.MINI_CHOPPER);
907
        giftSeries.put(2, ScratchedGift.FRUIT_JUICER);
908
        giftSeries.put(3, ScratchedGift.STEAM_IRON);
909
 
910
 
32579 amit.gupta 911
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(fofoId, ProfitMandiConstants.SCRATCH_OFFER_START_DATE.atStartOfDay(),
912
                ProfitMandiConstants.SCRATCH_OFFER_END_DATE.atTime(Utils.MAX_TIME));
32218 tejbeer 913
 
914
        ScratchedGift gift = ScratchedGift.BLNT;
915
 
916
        Random random = new Random();
32672 amit.gupta 917
        int rand;
32218 tejbeer 918
        while (true) {
919
            rand = random.nextInt(4);
920
            if (rand != 0) break;
921
        }
922
        if (fofoOrders.isEmpty()) {
923
            gift = giftSeries.get(rand);
924
        } else {
925
 
926
            List<String> invoiceNumbers = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).map(x -> x.getInvoiceNumber()).collect(Collectors.toList());
927
 
928
            List<ScratchOffer> scratchOffers = scratchOfferRepository.selectByInvoiceNumbers(invoiceNumbers);
929
            if (scratchOffers.isEmpty()) {
930
                gift = giftSeries.get(rand);
931
            } else {
932
                List<ScratchOffer> bigGifts = scratchOffers.stream().filter(x -> !x.getOfferName().equals(ScratchedGift.BLNT) && !x.getOfferName().equals(ScratchedGift.EW)).collect(Collectors.toList());
933
                if (bigGifts.size() <= 10) {
934
                    List<Integer> scratchCustomerIds = scratchOffers.stream().map(x -> x.getCustomerId()).collect(Collectors.toList());
935
                    if (scratchCustomerIds.contains(customerId)) {
936
 
937
 
938
                        gift = ScratchedGift.BLNT;
939
 
940
                        LOGGER.info("gift2 {}", gift);
941
 
942
                    } else {
943
 
944
                        int miniChopper = (int) bigGifts.stream().filter(x -> x.getOfferName().equals(ScratchedGift.MINI_CHOPPER)).count();
945
                        int fruitJuicer = (int) bigGifts.stream().filter(x -> x.getOfferName().equals(ScratchedGift.FRUIT_JUICER)).count();
946
                        int streanIron = (int) bigGifts.stream().filter(x -> x.getOfferName().equals(ScratchedGift.STEAM_IRON)).count();
947
 
948
                        if (rand == 1) {
949
                            if (miniChopper < 4) {
950
                                LOGGER.info("miniChopper {}", miniChopper);
951
 
952
 
953
                                gift = giftSeries.get(rand);
954
                            }
955
                        }
956
 
957
                        if (rand == 2) {
958
                            if (fruitJuicer < 3) {
959
 
960
                                LOGGER.info("fruitJuicer {}", fruitJuicer);
961
 
962
                                gift = giftSeries.get(rand);
963
                            }
964
                        }
965
 
966
                        if (rand == 3) {
967
                            if (streanIron < 3) {
968
 
969
                                LOGGER.info("streanIron {}", streanIron);
970
 
971
 
972
                                gift = giftSeries.get(rand);
973
 
974
                            }
975
                        }
976
 
977
                        LOGGER.info("gift4 {}", gift);
978
                    }
979
                }
980
            }
981
 
982
 
983
        }
32586 ranu 984
        return gift;
32145 tejbeer 985
    }
29515 tejbeer 986
 
33142 ranu 987
    private ScratchedGift getScratchedGiftRandomAccordingQuantity(int customerId) {
988
        RandomCollection<ScratchedGift> map1 = new RandomCollection<ScratchedGift>().
989
                add(50d, ScratchedGift.SOLOR_LAMP)
990
                .add(100d, ScratchedGift.BLUETOOTH_SPEAKER)
991
                .add(150d, ScratchedGift.RED_WATER_BOTTLE)
992
                .add(200d, ScratchedGift.GIFT_BOWL)
993
                .add(100d, ScratchedGift.EARBUDS);
994
 
33665 ranu 995
        ScratchedGift gift;
33142 ranu 996
 
33665 ranu 997
        List<ScratchOffer> lastScratchOffers = scratchOfferRepository.selectBycCustomerIdAndDate(customerId, ProfitMandiConstants.LAST_SCRATCH_OFFER_START_DATE, ProfitMandiConstants.LAST_SCRATCH_OFFER_END_DATE);
998
 
999
        if (lastScratchOffers.isEmpty()) {
1000
            gift = map1.next();
1001
        } else {
1002
            gift = ScratchedGift.RED_WATER_BOTTLE;
1003
            LOGGER.info("RED_WATER_BOTTLE {}", gift);
33142 ranu 1004
        }
1005
        return gift;
1006
    }
1007
 
32145 tejbeer 1008
    private HygieneData createAndGetHygieneData(int id, int fofoId) {
1009
        HygieneData hygieneData = new HygieneData();
1010
        hygieneData.setOrderId(id);
1011
        hygieneData.setFofoId(fofoId);
1012
        hygieneData.setCreatedTimestamp(LocalDateTime.now());
1013
        hygieneDataRepository.persist(hygieneData);
25640 tejbeer 1014
 
32145 tejbeer 1015
        return hygieneData;
1016
    }
25640 tejbeer 1017
 
33665 ranu 1018
 
32145 tejbeer 1019
    @Override
1020
    public String getInvoiceNumber(int fofoId, String fofoStoreCode) {
1021
        InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1022
        try {
1023
            invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1024
            invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1025
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
1026
            invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1027
            invoiceNumberGenerationSequence.setFofoId(fofoId);
1028
            invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
1029
            invoiceNumberGenerationSequence.setSequence(1);
1030
        }
1031
        invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1032
        return invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence();
1033
    }
24275 amit.gupta 1034
 
32145 tejbeer 1035
    private String getSecurityDepositNumber(int fofoId, String fofoStoreCode) {
1036
        InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1037
        try {
1038
            invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1039
            invoiceNumberGenerationSequence.setChallanNumberSequence(invoiceNumberGenerationSequence.getChallanNumberSequence() + 1);
1040
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
1041
            invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1042
            invoiceNumberGenerationSequence.setFofoId(fofoId);
1043
            invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
1044
            invoiceNumberGenerationSequence.setChallanNumberSequence(1);
1045
        }
1046
        invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1047
        return invoiceNumberGenerationSequence.getPrefix() + "/SEC" + invoiceNumberGenerationSequence.getChallanNumberSequence();
1048
    }
24226 amit.gupta 1049
 
32145 tejbeer 1050
    private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails) {
1051
        Set<String> serialNumbers = new HashSet<>();
1052
        for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1053
            if (serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
1054
                serialNumbers.add(serialNumberDetail.getSerialNumber());
1055
            }
1056
        }
1057
        return serialNumbers;
1058
    }
23650 amit.gupta 1059
 
32145 tejbeer 1060
    @Override
1061
    public InvoicePdfModel getInvoicePdfModel(int orderId) throws ProfitMandiBusinessException {
1062
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
1063
        return this.getInvoicePdfModel(fofoOrder);
1064
    }
23650 amit.gupta 1065
 
32145 tejbeer 1066
    @Override
1067
    @Cacheable(value = "order.dummymodel", cacheManager = "oneDayCacheManager")
1068
    public InvoicePdfModel getDummyPdfModel(String serialNumber) throws ProfitMandiBusinessException {
1069
        List<WarehouseInventoryItem> warehouseInventoryItems = warehouseInventoryItemRepository.selectWarehouseInventoryItemBySerailNumbers(Arrays.asList(serialNumber));
1070
        if (warehouseInventoryItems.size() > 0) {
1071
            WarehouseInventoryItem warehouseInventoryItem = warehouseInventoryItems.get(0);
1072
            int currentQuantity = warehouseInventoryItems.get(0).getCurrentQuantity();
1073
            if (currentQuantity > 0) {
1074
                throw new ProfitMandiBusinessException("Serial Number", serialNumber, "Serial Number exist in our warehouse");
1075
            } else {
1076
                try {
1077
                    InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(serialNumber);
1078
                    if (inventoryItem.getGoodQuantity() > 0) {
1079
                        throw new ProfitMandiBusinessException("Serial Number", serialNumber, "Serial Number is not yet billed by the partner");
1080
                    } else {
1081
                        List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(inventoryItem.getId());
1082
                        Optional<ScanRecord> scanRecord = scanRecords.stream().filter(x -> x.getOrderId() != 0).findFirst();
1083
                        if (scanRecord.isPresent()) {
1084
                            FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(scanRecord.get().getOrderId());
1085
                            orderIdsConsumed.add(fofoOrder.getId());
1086
                            return this.getInvoicePdfModel(fofoOrder);
1087
                        } else {
1088
                            throw new ProfitMandiBusinessException("Serial Number", serialNumber, "Serial Number returned by partner, but in transit");
1089
                        }
1090
                    }
1091
                } catch (Exception e) {
1092
                    int itemId = warehouseInventoryItem.getItemId();
1093
                    if (serialNumberOrderIdMap.containsKey(serialNumber)) {
1094
                        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(serialNumberOrderIdMap.get(serialNumber));
1095
                        InvoicePdfModel pdfModel = this.getInvoicePdfModel(fofoOrder.getId());
1096
                        this.modifyDummyModel(fofoOrder, pdfModel, itemId, serialNumber);
1097
                        return pdfModel;
1098
                    }
1099
                    // Map this serialNumber for dummy billing
1100
                    LocalDateTime grnDate = warehouseInventoryItem.getCreated();
1101
                    Random random = new Random();
1102
                    int randomDays = random.ints(2, 15).findFirst().getAsInt();
1103
                    LocalDateTime saleDate = grnDate.plusDays(randomDays);
1104
                    if (saleDate.isAfter(LocalDate.now().atStartOfDay())) {
1105
                        saleDate = LocalDateTime.now().minusDays(2);
1106
                    }
1107
                    Random offsetRandom = new Random();
1108
                    int offset = offsetRandom.ints(2, 100).findFirst().getAsInt();
1109
                    FofoOrder fofoOrder = fofoOrderRepository.selectFirstOrderAfterDate(saleDate, offset);
1110
                    while (orderIdsConsumed.contains(fofoOrder.getId())) {
1111
                        Random offsetRandom2 = new Random();
1112
                        int offset2 = offsetRandom2.ints(2, 100).findFirst().getAsInt();
1113
                        FofoOrder fofoOrder2 = fofoOrderRepository.selectFirstOrderAfterDate(saleDate, offset2);
1114
                        if (fofoOrder2 != null) {
1115
                            fofoOrder = fofoOrder2;
1116
                        }
1117
                    }
1118
                    InvoicePdfModel pdfModel = this.getInvoicePdfModel(fofoOrder.getId());
1119
                    orderIdsConsumed.add(fofoOrder.getId());
1120
                    this.modifyDummyModel(fofoOrder, pdfModel, itemId, serialNumber);
1121
                    return pdfModel;
27516 amit.gupta 1122
 
32145 tejbeer 1123
                }
1124
            }
1125
        } else {
1126
            throw new ProfitMandiBusinessException("Serial Number", serialNumber, "Serial Number does not exist in our warehouse");
1127
        }
1128
    }
27516 amit.gupta 1129
 
33665 ranu 1130
    void modifyDummyModel(FofoOrder fofoOrder, InvoicePdfModel pdfModel, int itemId, String serialNumber) throws
1131
            ProfitMandiBusinessException {
28166 tejbeer 1132
 
32145 tejbeer 1133
        int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoOrder.getFofoId());
27516 amit.gupta 1134
 
32145 tejbeer 1135
        Address retailerAddress = addressRepository.selectById(retailerAddressId);
1136
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
27516 amit.gupta 1137
 
32145 tejbeer 1138
        CustomerAddress customerAddress = customer.getCustomerAddress().stream().filter(x -> x.getId() == fofoOrder.getCustomerAddressId()).findFirst().get();
27516 amit.gupta 1139
 
32145 tejbeer 1140
        Integer stateId = null;
1141
        if (customerAddress.getState().equals(retailerAddress.getState())) {
1142
            try {
1143
                // stateId =
1144
                // Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
30527 tejbeer 1145
 
32145 tejbeer 1146
                stateId = Long.valueOf(stateRepository.selectByName(customerAddress.getState()).getId()).intValue();
1147
            } catch (Exception e) {
1148
                LOGGER.error("Unable to get state rates");
1149
            }
1150
        }
1151
        CustomOrderItem cli = pdfModel.getOrderItems().stream().findFirst().get();
1152
        List<FofoOrderItem> fofoOrderItems = Arrays.asList(this.getDummyFofoOrderItem(itemId, fofoOrder.getId(), serialNumber, stateId));
1153
        pdfModel.setPaymentOptions(pdfModel.getPaymentOptions().stream().limit(1).collect(Collectors.toList()));
1154
        CustomPaymentOption paymentOption = pdfModel.getPaymentOptions().get(0);
1155
        paymentOption.setAmount(fofoOrderItems.get(0).getMop());
33298 amit.gupta 1156
        List<CustomOrderItem> customerFofoOrderItems = new ArrayList<>();
32145 tejbeer 1157
        for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1158
            CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1159
            float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1160
            float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
1161
            float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
27516 amit.gupta 1162
 
32145 tejbeer 1163
            customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
1164
            customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
1165
            Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
1166
            // LOGGER.info("serialNumbers {}", serialNumbers);
1167
            // LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
1168
            if (!serialNumbers.isEmpty()) {
1169
                customFofoOrderItem.setDescription(
1170
                        customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1171
            }
1172
            customFofoOrderItem.setRate(taxableSellingPrice);
1173
            customFofoOrderItem.setDiscount(taxableDiscountPrice);
1174
            customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
1175
            customFofoOrderItem.setNetAmount(
1176
                    (fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
1177
            float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1178
            float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1179
            float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1180
            customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1181
            customFofoOrderItem.setIgstAmount(igstAmount);
1182
            customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1183
            customFofoOrderItem.setCgstAmount(cgstAmount);
1184
            customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1185
            customFofoOrderItem.setSgstAmount(sgstAmount);
1186
            customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
1187
            customerFofoOrderItems.add(customFofoOrderItem);
1188
        }
1189
        pdfModel.setTotalAmount(paymentOption.getAmount());
1190
        pdfModel.setOrderItems(customerFofoOrderItems);
28166 tejbeer 1191
 
32145 tejbeer 1192
    }
27516 amit.gupta 1193
 
32145 tejbeer 1194
    private InvoicePdfModel getInvoicePdfModel(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
23650 amit.gupta 1195
 
32145 tejbeer 1196
        List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository.selectByReferenceIdAndTypes(fofoOrder.getId(), Arrays.asList(PaymentOptionReferenceType.ORDER, PaymentOptionReferenceType.INSURANCE));
23650 amit.gupta 1197
 
32145 tejbeer 1198
        List<CustomPaymentOption> paymentOptions = new ArrayList<>();
23552 amit.gupta 1199
 
32145 tejbeer 1200
        InvoicePdfModel pdfModel = new InvoicePdfModel();
33795 ranu 1201
 
1202
 
1203
        List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
1204
 
1205
        double upgradePartnerDiscount = 0;
1206
 
1207
        for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1208
 
1209
            Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
1210
            for (String serialNumber : serialNumbers) {
1211
                UpgradeOffer upgradeOffer = upgradeOfferRepository.selectBySerialNumber(serialNumber);
1212
                if (upgradeOffer != null) {
1213
                    CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(upgradeOffer.getCustomerOfferItemId());
1214
                    upgradePartnerDiscount += customerOfferItem.getDealerPayout();
1215
                } else {
1216
                    upgradePartnerDiscount += 0;
1217
                }
1218
            }
1219
 
1220
 
1221
        }
1222
 
1223
        boolean hasSamsungUpgrade = paymentOptionTransactions.stream()
1224
                .anyMatch(transaction ->
1225
                        "SAMSUNG UPGRADE".equals(paymentOptionRepository
1226
                                .selectById(transaction.getPaymentOptionId())
1227
                                .getName()));
1228
 
1229
        LOGGER.info("paymentOptionTransactions - {}", paymentOptionTransactions);
1230
        LOGGER.info("hasSamsungUpgrade - {}", hasSamsungUpgrade);
1231
 
1232
        double cashDiscount = paymentOptionTransactions.stream()
1233
                .filter(x -> "CASH DISCOUNT".equals(paymentOptionRepository.selectById(x.getPaymentOptionId()).getName())).mapToDouble(x -> x.getAmount()).findFirst().orElse(0);
1234
 
1235
        LOGGER.info("cashDiscount - {}", cashDiscount);
1236
 
32145 tejbeer 1237
        for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
33795 ranu 1238
            String paymentOptionName = paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName();
1239
 
32145 tejbeer 1240
            CustomPaymentOption cpi = new CustomPaymentOption();
33795 ranu 1241
            LOGGER.info("paymentOptionName {}", paymentOptionName);
1242
 
1243
            float amountToSet = paymentOptionTransaction.getAmount();
1244
 
1245
            if ("SAMSUNG UPGRADE".equals(paymentOptionName) && hasSamsungUpgrade) {
1246
                if (cashDiscount > upgradePartnerDiscount) {
1247
                    amountToSet += (float) upgradePartnerDiscount;
1248
                } else {
1249
                    amountToSet += (float) cashDiscount;
1250
                }
1251
 
1252
            } else if ("CASH".equals(paymentOptionName) && !hasSamsungUpgrade) {
1253
                amountToSet += ((float) cashDiscount - (float) upgradePartnerDiscount);
1254
 
1255
            } else if ("CASH".equals(paymentOptionName) && hasSamsungUpgrade && (cashDiscount > upgradePartnerDiscount)) {
1256
                amountToSet += ((float) cashDiscount - (float) upgradePartnerDiscount);
1257
 
1258
            }
1259
 
1260
            cpi.setAmount(amountToSet);
1261
            cpi.setPaymentOption(paymentOptionName);
1262
 
32145 tejbeer 1263
            paymentOptions.add(cpi);
1264
        }
24215 amit.gupta 1265
 
33795 ranu 1266
 
32145 tejbeer 1267
        pdfModel.setTitle("Retailer Invoice");
1268
        Optional<FofoOrderItem> fofoOrderItemOptional = fofoOrderItems.stream().findAny();
1269
        if (fofoOrderItemOptional.isPresent() && fofoOrderItemOptional.get().equals("NOGST")) {
1270
            pdfModel.setTitle("Security Deposit Receipt");
1271
        }
1272
        pdfModel.setPaymentOptions(paymentOptions);
1273
        pdfModel.setAuther("SmartDukaan");
1274
        pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
23650 amit.gupta 1275
 
32145 tejbeer 1276
        // insurance calculation
1277
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoOrder.getInvoiceNumber());
33298 amit.gupta 1278
        List<CustomInsurancePolicy> customInsurancePolicies = new ArrayList<>();
32145 tejbeer 1279
        final float totalInsuranceTaxRate = 18;
1280
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
1281
            float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
1282
            CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
1283
            customInsurancePolicy.setDescription(insurancePolicy.getPolicyPlan() + " for Device #" + insurancePolicy.getSerialNumber() + "\n Plan Reference - " + insurancePolicy.getPolicyNumber());
1284
            customInsurancePolicy.setHsnCode("998716");
1285
            customInsurancePolicy.setRate(taxableInsurancePrice);
1286
            customInsurancePolicy.setIgstRate(18);
1287
            customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
1288
            customInsurancePolicy.setCgstRate(9);
1289
            customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
1290
            customInsurancePolicy.setSgstRate(9);
1291
            customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
1292
            customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
1293
            customInsurancePolicies.add(customInsurancePolicy);
1294
        }
1295
        pdfModel.setInsurancePolicies(customInsurancePolicies);
24275 amit.gupta 1296
 
32145 tejbeer 1297
        Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
1298
        PrivateDealUser privateDealUser = null;
1299
        try {
1300
            privateDealUser = privateDealUserRepository.selectById(retailer.getId());
1301
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
1302
            LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
1303
        }
23650 amit.gupta 1304
 
32145 tejbeer 1305
        User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
1306
        CustomRetailer customRetailer = new CustomRetailer();
1307
        customRetailer.setBusinessName(retailer.getName());
1308
        customRetailer.setMobileNumber(user.getMobileNumber());
1309
        // customRetailer.setTinNumber(retailer.getNumber());
1310
        if (privateDealUser == null) {
1311
            customRetailer.setGstNumber(null);
1312
        } else {
1313
            if (null != privateDealUser.getCounterId()) {
1314
                Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
1315
                customRetailer.setGstNumber(counter.getGstin());
1316
            } else {
1317
                customRetailer.setGstNumber(null);
1318
            }
1319
        }
1320
        Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
1321
        customRetailer.setAddress(this.createCustomAddress(retailerAddress));
1322
        pdfModel.setRetailer(customRetailer);
23650 amit.gupta 1323
 
33089 amit.gupta 1324
        pdfModel.setCustomer(getCustomCustomer(fofoOrder, customRetailer.getAddress()));
1325
        pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
1326
        pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
1327
 
1328
 
33298 amit.gupta 1329
        List<CustomOrderItem> customerFofoOrderItems = new ArrayList<>();
32145 tejbeer 1330
        for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
1331
            float discount = fofoOrderItem.getDiscount();
1332
            CustomOrderItem customFofoOrderItem = new CustomOrderItem();
1333
            float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
1334
            float taxableSellingPrice = (fofoOrderItem.getSellingPrice() + discount) / (1 + totalTaxRate / 100);
1335
            float taxableDiscountPrice = discount / (1 + totalTaxRate / 100);
23650 amit.gupta 1336
 
32145 tejbeer 1337
            customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
1338
            customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
1339
            Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
32816 ranu 1340
            List<FofoNonSerializeSerial> nonSerializeSerials = fofoNonSerializeSerialRepository.selectByItemIdAndOrderId(fofoOrderItem.getId());
1341
            // Extract serial numbers from FofoNonSerializeSerial entities
1342
            List<String> customSerialNumbers = nonSerializeSerials.stream().map(FofoNonSerializeSerial::getSerialNumber).collect(Collectors.toList());
1343
            LOGGER.info("nonSerializeSerials {}", nonSerializeSerials);
32145 tejbeer 1344
            if (!serialNumbers.isEmpty()) {
1345
                customFofoOrderItem.setDescription(
1346
                        customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
1347
            }
32816 ranu 1348
            if (!customSerialNumbers.isEmpty()) {
1349
                customFofoOrderItem.setDescription(
1350
                        customFofoOrderItem.getDescription() + "\n SerialNumber - " + String.join(", ", customSerialNumbers));
1351
            }
32145 tejbeer 1352
            customFofoOrderItem.setRate(taxableSellingPrice);
1353
            customFofoOrderItem.setDiscount(taxableDiscountPrice);
1354
            customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
1355
            customFofoOrderItem.setNetAmount(fofoOrderItem.getSellingPrice() * fofoOrderItem.getQuantity());
1356
            float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
1357
            float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
1358
            float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
1359
            customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
1360
            customFofoOrderItem.setIgstAmount(igstAmount);
1361
            customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
1362
            customFofoOrderItem.setCgstAmount(cgstAmount);
1363
            customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
1364
            customFofoOrderItem.setSgstAmount(sgstAmount);
1365
            customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
1366
            customerFofoOrderItems.add(customFofoOrderItem);
1367
        }
1368
        pdfModel.setOrderItems(customerFofoOrderItems);
32627 ranu 1369
        String customerAddressStateCode = "";
32145 tejbeer 1370
        String partnerAddressStateCode = stateRepository.selectByName(pdfModel.getRetailer().getAddress().getState()).getCode();
32627 ranu 1371
        if (pdfModel.getCustomer() != null && pdfModel.getCustomer().getAddress() != null &&
1372
                pdfModel.getCustomer().getAddress().getState() != null &&
1373
                !pdfModel.getCustomer().getAddress().getState().trim().isEmpty()) {
1374
            customerAddressStateCode = stateRepository.selectByName(pdfModel.getCustomer().getAddress().getState()).getCode();
1375
        }
1376
 
32145 tejbeer 1377
        pdfModel.setPartnerAddressStateCode(partnerAddressStateCode);
32627 ranu 1378
        if (!customerAddressStateCode.equals("")) {
1379
            pdfModel.setCustomerAddressStateCode(customerAddressStateCode);
1380
        }
32145 tejbeer 1381
        pdfModel.setCancelled(fofoOrder.getCancelledTimestamp() != null);
1382
        List<String> tncs = new ArrayList<>();
1383
        tncs.add("I agree that goods received are in good working condition");
1384
        tncs.add("Goods once sold cannot be exchanged or taken back");
1385
        tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
1386
        tncs.add("Customer needs to activate the handset at the time of delivery to be eligible for the discount");
1387
        tncs.add(
1388
                "Customers requesting Tempered Glass Replacement will have to bring the broken tempered glass, either pasted on the phone or along with the phone");
1389
        tncs.add("Service fee of Rs.20 will be chargeable for each Tempered Glass Replacement");
1390
        if (pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
1391
            tncs.add("Damage protection provided is the responisibility of Protection Provider only");
1392
        }
1393
        pdfModel.setTncs(tncs);
1394
        return pdfModel;
23650 amit.gupta 1395
 
32145 tejbeer 1396
    }
23650 amit.gupta 1397
 
33665 ranu 1398
    private CustomCustomer getCustomCustomer(FofoOrder fofoOrder, CustomAddress retailerAddress) throws
1399
            ProfitMandiBusinessException {
32145 tejbeer 1400
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1401
        CustomCustomer customCustomer = new CustomCustomer();
1402
        customCustomer.setFirstName(customer.getFirstName());
1403
        customCustomer.setLastName(customer.getLastName());
1404
        customCustomer.setEmailId(customer.getEmailId());
1405
        customCustomer.setMobileNumber(customer.getMobileNumber());
1406
        customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
32627 ranu 1407
        if (fofoOrder.getCustomerAddressId() != 0) {
1408
            CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
1409
            customCustomer.setAddress(this.createCustomAddress(customerAddress));
1410
        } else {
33089 amit.gupta 1411
 
1412
            customCustomer.setAddress(this.createCustomAddressWithoutId(customCustomer, retailerAddress));
32627 ranu 1413
        }
32145 tejbeer 1414
        return customCustomer;
32627 ranu 1415
 
32145 tejbeer 1416
    }
23655 amit.gupta 1417
 
32145 tejbeer 1418
    @Override
1419
    public InvoicePdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
1420
        FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
1421
        return this.getInvoicePdfModel(fofoOrder);
1422
    }
23650 amit.gupta 1423
 
32145 tejbeer 1424
    public String getBillingAddress(CustomerAddress customerAddress) {
1425
        StringBuilder address = new StringBuilder();
1426
        if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
1427
            address.append(customerAddress.getLine1());
1428
            address.append(", ");
1429
        }
22859 ashik.ali 1430
 
32145 tejbeer 1431
        if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
1432
            address.append(customerAddress.getLine2());
1433
            address.append(", ");
1434
        }
22859 ashik.ali 1435
 
32145 tejbeer 1436
        if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
1437
            address.append(customerAddress.getLandmark());
1438
            address.append(", ");
1439
        }
22859 ashik.ali 1440
 
32145 tejbeer 1441
        if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
1442
            address.append(customerAddress.getCity());
1443
            address.append(", ");
1444
        }
22859 ashik.ali 1445
 
32145 tejbeer 1446
        if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
1447
            address.append(customerAddress.getState());
1448
        }
22859 ashik.ali 1449
 
32145 tejbeer 1450
        if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
1451
            address.append("- ");
1452
            address.append(customerAddress.getPinCode());
1453
        }
22859 ashik.ali 1454
 
32145 tejbeer 1455
        return address.toString();
1456
    }
23650 amit.gupta 1457
 
32145 tejbeer 1458
    @Override
1459
    public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException {
1460
        try {
1461
            JSONObject cartObject = new JSONObject(cartJson);
1462
            Iterator<?> keys = cartObject.keys();
23650 amit.gupta 1463
 
32145 tejbeer 1464
            Set<Integer> itemIds = new HashSet<>();
1465
            List<CartFofo> cartItems = new ArrayList<CartFofo>();
23650 amit.gupta 1466
 
32145 tejbeer 1467
            while (keys.hasNext()) {
1468
                String key = (String) keys.next();
1469
                if (cartObject.get(key) instanceof JSONObject) {
1470
                    LOGGER.info(cartObject.get(key).toString());
1471
                }
1472
                CartFofo cf = new CartFofo();
1473
                cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
1474
                cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
1475
                if (cartObject.getJSONObject(key).has("poId")) {
23650 amit.gupta 1476
 
32145 tejbeer 1477
                    cf.setPoId(cartObject.getJSONObject(key).getInt("poId"));
1478
                    cf.setPoItemId(cartObject.getJSONObject(key).getInt("poItemId"));
1479
                }
1480
                if (cf.getQuantity() <= 0) {
1481
                    continue;
1482
                }
1483
                cartItems.add(cf);
1484
                itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
1485
            }
1486
            Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
1487
            if (itemIds.size() > 0) {
1488
                List<Item> items = itemRepository.selectByIds(itemIds);
1489
                for (Item i : items) {
1490
                    itemMap.put(i.getId(), i);
1491
                }
23650 amit.gupta 1492
 
32145 tejbeer 1493
            }
1494
            for (CartFofo cf : cartItems) {
1495
                Item i = itemMap.get(cf.getItemId());
1496
                if (i == null) {
1497
                    continue;
1498
                }
1499
                cf.setDisplayName(getValidName(i.getBrand()) + " " + getValidName(i.getModelName()) + " " + getValidName(i.getModelNumber()) + " " + getValidName(i.getColor()).replaceAll("\\s+", " "));
1500
                cf.setItemType(i.getType());
1501
            }
1502
            return cartItems;
1503
        } catch (Exception e) {
1504
            LOGGER.error("Unable to Prepare cart to place order...", e);
1505
            throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
1506
        }
1507
    }
23650 amit.gupta 1508
 
32145 tejbeer 1509
    @Override
33665 ranu 1510
    public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue, LocalDateTime
1511
            startDate, LocalDateTime endDate, int offset, int limit) throws ProfitMandiBusinessException {
32145 tejbeer 1512
        long countItems = 0;
1513
        List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 1514
 
32145 tejbeer 1515
        if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
1516
            fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, null, null, offset, limit);
1517
            countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, null, null);
1518
        } else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
1519
            fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, null, null, offset, limit);
1520
            countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, null, null);
1521
        } else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
1522
            fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, null, null, offset, limit);
1523
            countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, null, null);
1524
        } else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
1525
            fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, null, null, offset, limit);
1526
            countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, null, null);
1527
        } else if (searchType == SearchType.INVOICE_NUMBER && !searchValue.isEmpty()) {
1528
            fofoOrders = Arrays.asList(fofoOrderRepository.selectByFofoIdAndInvoiceNumber(fofoId, searchValue));
1529
            countItems = fofoOrders.size();
1530
        } else if (searchType == SearchType.DATE_RANGE) {
1531
            fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
1532
            countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDate, endDate);
1533
        }
1534
        Map<String, Object> map = new HashMap<>();
23650 amit.gupta 1535
 
32145 tejbeer 1536
        map.put("saleHistories", fofoOrders);
1537
        map.put("start", offset + 1);
1538
        map.put("size", countItems);
1539
        map.put("searchType", searchType);
1540
        map.put("searchTypes", SearchType.values());
1541
        map.put("startDate", startDate);
1542
        map.put("searchValue", searchValue);
1543
        map.put(ProfitMandiConstants.END_TIME, endDate);
1544
        if (fofoOrders.size() < limit) {
1545
            map.put("end", offset + fofoOrders.size());
1546
        } else {
1547
            map.put("end", offset + limit);
1548
        }
1549
        return map;
1550
    }
30426 tejbeer 1551
 
33665 ranu 1552
    public ResponseEntity<?> downloadReportInCsv(org.apache.commons.io.output.ByteArrayOutputStream
1553
                                                         baos, List<List<?>> rows, String fileName) {
32145 tejbeer 1554
        final HttpHeaders headers = new HttpHeaders();
1555
        headers.set("Content-Type", "text/csv");
30426 tejbeer 1556
 
32145 tejbeer 1557
        headers.set("Content-disposition", "inline; filename=" + fileName + ".csv");
1558
        headers.setContentLength(baos.toByteArray().length);
23202 ashik.ali 1559
 
32145 tejbeer 1560
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1561
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
30426 tejbeer 1562
 
33454 amit.gupta 1563
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
32145 tejbeer 1564
    }
30157 manish 1565
 
32145 tejbeer 1566
    @Override
33665 ranu 1567
    public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String
1568
            searchValue, LocalDateTime startDate, LocalDateTime endDate, int offset, int limit) throws
1569
            ProfitMandiBusinessException {
32145 tejbeer 1570
        List<FofoOrder> fofoOrders = new ArrayList<>();
23650 amit.gupta 1571
 
32145 tejbeer 1572
        if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
1573
            fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDate, endDate, offset, limit);
1574
        } else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
1575
            fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDate, endDate, offset, limit);
1576
        } else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
1577
            fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDate, endDate, offset, limit);
1578
        } else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
1579
            fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDate, endDate, offset, limit);
24275 amit.gupta 1580
 
32145 tejbeer 1581
        } else if (searchType == SearchType.DATE_RANGE) {
1582
            fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDate, endDate, offset, limit);
1583
        }
1584
        Map<String, Object> map = new HashMap<>();
1585
        map.put("saleHistories", fofoOrders);
1586
        map.put("searchType", searchType);
1587
        map.put("searchTypes", SearchType.values());
1588
        map.put("startDate", startDate);
1589
        map.put("searchValue", searchValue);
1590
        map.put(ProfitMandiConstants.END_TIME, endDate);
1591
        return map;
1592
    }
23650 amit.gupta 1593
 
32145 tejbeer 1594
    private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
1595
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
1596
        return fofoStore.getCode();
1597
    }
23650 amit.gupta 1598
 
32145 tejbeer 1599
    private String getValidName(String name) {
1600
        return name != null ? name : "";
1601
    }
23650 amit.gupta 1602
 
32145 tejbeer 1603
    private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
1604
        Set<String> serialNumbers = new HashSet<>();
1605
        for (FofoLineItem fofoLineItem : fofoLineItems) {
1606
            if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
1607
                serialNumbers.add(fofoLineItem.getSerialNumber());
1608
            }
1609
        }
1610
        return serialNumbers;
1611
    }
23650 amit.gupta 1612
 
33520 amit.gupta 1613
    static final List<String> MOP_VOILATED_BRANDS = Arrays.asList("Live Demo", "Almost New");
1614
 
33665 ranu 1615
    private void validateDpPrice(int fofoId, Map<
1616
            Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws
1617
            ProfitMandiBusinessException {
32420 amit.gupta 1618
        if (pricingService.getMopVoilatedRetailerIds().contains(fofoId)) return;
32145 tejbeer 1619
        for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoLineItemMap.entrySet()) {
1620
            int itemId = entry.getKey();
1621
            CustomFofoOrderItem customFofoOrderItem = entry.getValue();
1622
            LOGGER.info("CustomFofoOrderItem -- {}", customFofoOrderItem);
1623
            PriceModel priceModel = itemIdMopPriceMap.get(itemId);
1624
            Item item = itemRepository.selectById(itemId);
33520 amit.gupta 1625
            if (!MOP_VOILATED_BRANDS.contains(item.getBrand()) && (item.getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID || item.getCategoryId() == ProfitMandiConstants.TABLET_CATEGORY_ID || item.getCategoryId() == ProfitMandiConstants.LED_CATEGORY_ID) && customFofoOrderItem.getSerialNumberDetails().stream().filter(x -> org.apache.commons.lang.StringUtils.isNotEmpty(x.getSerialNumber())).collect(Collectors.toList()).size() > 0) {
32145 tejbeer 1626
                if (Utils.compareFloat(priceModel.getPrice(), customFofoOrderItem.getSellingPrice() + customFofoOrderItem.getDiscountAmount()) > 0) {
1627
                    throw new ProfitMandiBusinessException("Selling Price for ", item.getItemDescription(), "FFORDR_1010");
1628
                }
1629
            } else {
33520 amit.gupta 1630
                if (!MOP_VOILATED_BRANDS.contains(item.getBrand()) && priceModel.getPurchasePrice() > customFofoOrderItem.getSellingPrice()) {
32145 tejbeer 1631
                    throw new ProfitMandiBusinessException("Selling Price", itemRepository.selectById(itemId).getItemDescription(), "Selling Price should not be less than DP");
1632
                }
1633
            }
1634
        }
1635
    }
24275 amit.gupta 1636
 
33665 ranu 1637
    private void validateMopPrice(int fofoId, Map<
1638
            Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws
1639
            ProfitMandiBusinessException {
32420 amit.gupta 1640
        if (pricingService.getMopVoilatedRetailerIds().contains(fofoId)) return;
32145 tejbeer 1641
        Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
1642
        for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
1643
            CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
1644
            Item item = itemRepository.selectById(customFofoOrderItem.getItemId());
33520 amit.gupta 1645
            if (!(MOP_VOILATED_BRANDS.contains(item.getBrand()) || item.getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID || item.getCategoryId() != ProfitMandiConstants.TABLET_CATEGORY_ID) && customFofoOrderItem.getSellingPrice() + customFofoOrderItem.getDiscountAmount() < entry.getValue().getPrice()) {
32145 tejbeer 1646
                invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
1647
            }
1648
        }
23650 amit.gupta 1649
 
32145 tejbeer 1650
        if (!invalidMopItemIdPriceMap.isEmpty()) {
1651
            LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
1652
            throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
1653
        }
23650 amit.gupta 1654
 
32145 tejbeer 1655
    }
23650 amit.gupta 1656
 
33665 ranu 1657
    private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<
1658
            Integer, Integer> inventoryItemQuantityUsed, int fofoOrderId) {
32145 tejbeer 1659
        for (InventoryItem inventoryItem : inventoryItems) {
1660
            inventoryItem.setLastScanType(ScanType.SALE);
33087 amit.gupta 1661
            inventoryItem.setUpdateTimestamp(LocalDateTime.now());
32145 tejbeer 1662
            ScanRecord scanRecord = new ScanRecord();
1663
            scanRecord.setInventoryItemId(inventoryItem.getId());
1664
            scanRecord.setFofoId(fofoId);
1665
            scanRecord.setOrderId(fofoOrderId);
1666
            // correct this
1667
            scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1668
            scanRecord.setType(ScanType.SALE);
1669
            scanRecordRepository.persist(scanRecord);
1670
            purchaseReturnItemRepository.deleteById(inventoryItem.getId());
23650 amit.gupta 1671
 
32145 tejbeer 1672
        }
1673
    }
23650 amit.gupta 1674
 
33665 ranu 1675
    private void createFofoLineItem(int fofoOrderItemId, Set<
1676
            InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed) {
32145 tejbeer 1677
        for (InventoryItem inventoryItem : inventoryItems) {
1678
            FofoLineItem fofoLineItem = new FofoLineItem();
1679
            fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1680
            fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1681
            fofoLineItem.setInventoryItemId(inventoryItem.getId());
1682
            fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1683
            fofoLineItemRepository.persist(fofoLineItem);
1684
        }
1685
    }
23650 amit.gupta 1686
 
33665 ranu 1687
    private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId, Map<
1688
            Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId) throws
1689
            ProfitMandiBusinessException {
32145 tejbeer 1690
        FofoOrderItem fofoOrderItem = new FofoOrderItem();
1691
        fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1692
        fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1693
        fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1694
        fofoOrderItem.setOrderId(fofoOrderId);
1695
        TagListing tl = tagListingRepository.selectByItemId(customFofoOrderItem.getItemId());
1696
        // In case listing gets removed rebill it using the selling price
1697
        if (tl != null) {
1698
            fofoOrderItem.setDp(tl.getSellingPrice());
1699
            fofoOrderItem.setMop(tl.getMop());
1700
        } else {
1701
            fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1702
            fofoOrderItem.setMop(customFofoOrderItem.getSellingPrice());
1703
        }
1704
        fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
24823 amit.gupta 1705
 
32145 tejbeer 1706
        Item item = itemMap.get(customFofoOrderItem.getItemId());
1707
        Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1708
        if (stateId != null) {
1709
            itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
1710
        } else {
1711
            itemIdStateTaxRateMap = stateGstRateRepository.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1712
        }
1713
        for (InventoryItem inventoryItem : inventoryItems) {
23650 amit.gupta 1714
 
32145 tejbeer 1715
            fofoOrderItem.setIgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getIgstRate());
23650 amit.gupta 1716
 
32145 tejbeer 1717
            fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1718
            fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
27516 amit.gupta 1719
 
1720
 
32145 tejbeer 1721
            fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1722
            break;
1723
        }
1724
        fofoOrderItem.setBrand(item.getBrand());
1725
        fofoOrderItem.setModelName(item.getModelName());
1726
        fofoOrderItem.setModelNumber(item.getModelNumber());
1727
        fofoOrderItem.setColor(item.getColor());
1728
        fofoOrderItemRepository.persist(fofoOrderItem);
1729
        return fofoOrderItem;
1730
    }
27516 amit.gupta 1731
 
33665 ranu 1732
    private FofoOrderItem getDummyFofoOrderItem(int itemId, int fofoOrderId, String serialNumber, Integer stateId) throws
1733
            ProfitMandiBusinessException {
32145 tejbeer 1734
        Item item = itemRepository.selectById(itemId);
1735
        TagListing tl = tagListingRepository.selectByItemId(itemId);
1736
        FofoOrderItem fofoOrderItem = new FofoOrderItem();
1737
        fofoOrderItem.setItemId(itemId);
1738
        fofoOrderItem.setQuantity(1);
1739
        fofoOrderItem.setSellingPrice(tl.getMop());
1740
        fofoOrderItem.setOrderId(fofoOrderId);
1741
        // In case listing gets removed rebill it using the selling price
1742
        fofoOrderItem.setDp(tl.getSellingPrice());
1743
        fofoOrderItem.setMop(tl.getMop());
1744
        fofoOrderItem.setDiscount(0);
27516 amit.gupta 1745
 
32145 tejbeer 1746
        Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1747
        if (stateId != null) {
1748
            itemIdStateTaxRateMap = stateGstRateRepository.getStateTaxRate(Arrays.asList(itemId), stateId);
1749
        } else {
1750
            itemIdStateTaxRateMap = stateGstRateRepository.getIgstTaxRate(Arrays.asList(itemId));
1751
        }
27516 amit.gupta 1752
 
32145 tejbeer 1753
        fofoOrderItem.setIgstRate(itemIdStateTaxRateMap.get(itemId).getIgstRate());
27516 amit.gupta 1754
 
32145 tejbeer 1755
        fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(itemId).getCgstRate());
1756
        fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(itemId).getSgstRate());
23650 amit.gupta 1757
 
1758
 
32145 tejbeer 1759
        fofoOrderItem.setHsnCode(item.getHsnCode());
1760
        fofoOrderItem.setBrand(item.getBrand());
1761
        fofoOrderItem.setModelName(item.getModelName());
1762
        fofoOrderItem.setModelNumber(item.getModelNumber());
1763
        fofoOrderItem.setColor(item.getColor());
23650 amit.gupta 1764
 
32145 tejbeer 1765
        Set<FofoLineItem> fofoLineItems = new HashSet<>();
1766
        FofoLineItem fli = new FofoLineItem();
1767
        fli.setQuantity(1);
1768
        fli.setSerialNumber(serialNumber);
1769
        fofoLineItems.add(fli);
1770
        fofoOrderItem.setFofoLineItems(fofoLineItems);
22859 ashik.ali 1771
 
32145 tejbeer 1772
        return fofoOrderItem;
1773
    }
22859 ashik.ali 1774
 
33665 ranu 1775
    private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots,
1776
                                                int fofoId, int itemId, int quantity) throws ProfitMandiBusinessException {
32145 tejbeer 1777
        for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1778
            if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1779
                currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId, currentInventorySnapshot.getAvailability() - quantity);
1780
            }
1781
        }
1782
    }
23650 amit.gupta 1783
 
33665 ranu 1784
    private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws
1785
            ProfitMandiBusinessException {
32145 tejbeer 1786
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1787
            if (customPaymentOption.getAmount() > 0) {
1788
                PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
32627 ranu 1789
                LOGGER.error("error", fofoOrder.getId());
32145 tejbeer 1790
                paymentOptionTransaction.setReferenceId(fofoOrder.getId());
1791
                paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1792
                paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1793
                paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
1794
                paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
1795
                paymentOptionTransactionRepository.persist(paymentOptionTransaction);
1796
            }
1797
        }
1798
    }
22859 ashik.ali 1799
 
33665 ranu 1800
    private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String
1801
            documentNumber, float totalAmount, int customerAddressId) {
32145 tejbeer 1802
        FofoOrder fofoOrder = new FofoOrder();
1803
        fofoOrder.setCustomerGstNumber(customerGstNumber);
1804
        fofoOrder.setCustomerId(customerId);
1805
        fofoOrder.setFofoId(fofoId);
1806
        fofoOrder.setInvoiceNumber(documentNumber);
1807
        fofoOrder.setTotalAmount(totalAmount);
1808
        fofoOrder.setCustomerAddressId(customerAddressId);
1809
        fofoOrderRepository.persist(fofoOrder);
1810
        return fofoOrder;
1811
    }
23650 amit.gupta 1812
 
33665 ranu 1813
    private void validateItemsSerializedNonSerialized
1814
            (List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws
1815
            ProfitMandiBusinessException {
32145 tejbeer 1816
        List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1817
        List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1818
        for (Item i : items) {
1819
            CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1820
            if (i.getType().equals(ItemType.SERIALIZED)) {
1821
                if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
1822
                    invalidItemIdSerialNumbers.add(i.getId());
1823
                }
1824
            } else {
1825
                Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1826
                if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
1827
                    itemIdNonSerializedSerialNumbers.add(i.getId());
1828
                }
1829
            }
1830
        }
23650 amit.gupta 1831
 
32145 tejbeer 1832
        if (!invalidItemIdSerialNumbers.isEmpty()) {
1833
            LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1834
            // itemId's are serialized you are saying these are not serialized
1835
            throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
1836
        }
22859 ashik.ali 1837
 
32145 tejbeer 1838
        if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
1839
            LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1840
            // itemId's are non serialized you are saying these are serialized
1841
            throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
1842
        }
1843
    }
22859 ashik.ali 1844
 
33665 ranu 1845
    private void validateCurrentInventorySnapshotQuantities
1846
            (List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws
1847
            ProfitMandiBusinessException {
32145 tejbeer 1848
        if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
1849
            throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1850
        }
1851
        List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1852
        LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
1853
        LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
1854
        for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1855
            CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
1856
            LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1857
            if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1858
                ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1859
                itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1860
                Quantity quantity = new Quantity();
1861
                quantity.setAvailable(currentInventorySnapshot.getAvailability());
1862
                quantity.setRequested(customFofoOrderItem.getQuantity());
1863
                itemIdQuantityAvailability.setQuantity(quantity);
1864
                itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1865
            }
1866
        }
22859 ashik.ali 1867
 
32145 tejbeer 1868
        if (!itemIdQuantityAvailabilities.isEmpty()) {
1869
            // itemIdQuantity request is not valid
1870
            LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
1871
            throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
1872
        }
1873
    }
22859 ashik.ali 1874
 
33665 ranu 1875
    private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String
1876
            serialNumber) {
32145 tejbeer 1877
        int itemId = 0;
1878
        for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
1879
            Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1880
            for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1881
                if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
1882
                    itemId = entry.getKey();
1883
                    break;
1884
                }
1885
            }
1886
        }
1887
        return itemId;
1888
    }
23650 amit.gupta 1889
 
32145 tejbeer 1890
    private Map<Integer, Item> toItemMap(List<Item> items) {
1891
        Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1892
            @Override
1893
            public Integer apply(Item item) {
1894
                return item.getId();
1895
            }
1896
        };
1897
        Function<Item, Item> itemFunction = new Function<Item, Item>() {
1898
            @Override
1899
            public Item apply(Item item) {
1900
                return item;
1901
            }
1902
        };
1903
        return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
1904
    }
23650 amit.gupta 1905
 
32145 tejbeer 1906
    private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
1907
        customerAddress.setName(customAddress.getName());
1908
        customerAddress.setLastName(customAddress.getLastName());
1909
        customerAddress.setLine1(customAddress.getLine1());
1910
        customerAddress.setLine2(customAddress.getLine2());
1911
        customerAddress.setLandmark(customAddress.getLandmark());
1912
        customerAddress.setCity(customAddress.getCity());
1913
        customerAddress.setPinCode(customAddress.getPinCode());
1914
        customerAddress.setState(customAddress.getState());
1915
        customerAddress.setCountry(customAddress.getCountry());
1916
        customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1917
    }
23650 amit.gupta 1918
 
32145 tejbeer 1919
    private CustomAddress createCustomAddress(Address address) {
1920
        CustomAddress customAddress = new CustomAddress();
1921
        customAddress.setName(address.getName());
1922
        customAddress.setLine1(address.getLine1());
1923
        customAddress.setLine2(address.getLine2());
1924
        customAddress.setLandmark(address.getLandmark());
1925
        customAddress.setCity(address.getCity());
1926
        customAddress.setPinCode(address.getPinCode());
1927
        customAddress.setState(address.getState());
1928
        customAddress.setCountry(address.getCountry());
1929
        customAddress.setPhoneNumber(address.getPhoneNumber());
1930
        return customAddress;
1931
    }
23650 amit.gupta 1932
 
32145 tejbeer 1933
    private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
1934
        CustomAddress customAddress = new CustomAddress();
1935
        customAddress.setName(customerAddress.getName());
1936
        customAddress.setLastName(customerAddress.getLastName());
1937
        customAddress.setLine1(customerAddress.getLine1());
1938
        customAddress.setLine2(customerAddress.getLine2());
1939
        customAddress.setLandmark(customerAddress.getLandmark());
1940
        customAddress.setCity(customerAddress.getCity());
1941
        customAddress.setPinCode(customerAddress.getPinCode());
1942
        customAddress.setState(customerAddress.getState());
1943
        customAddress.setCountry(customerAddress.getCountry());
1944
        customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1945
        return customAddress;
1946
    }
23650 amit.gupta 1947
 
33665 ranu 1948
    private CustomAddress createCustomAddressWithoutId(CustomCustomer customerAddress, CustomAddress
1949
            retailerAddress) {
32627 ranu 1950
        CustomAddress customAddress = new CustomAddress();
1951
        customAddress.setName(customerAddress.getFirstName());
1952
        customAddress.setLastName(customerAddress.getLastName());
1953
        customAddress.setLine1("");
1954
        customAddress.setLine2("");
1955
        customAddress.setLandmark("");
33089 amit.gupta 1956
        customAddress.setCity(retailerAddress.getCity());
1957
        customAddress.setPinCode(retailerAddress.getPinCode());
1958
        customAddress.setState(retailerAddress.getState());
32627 ranu 1959
        customAddress.setCountry("");
1960
        customAddress.setPhoneNumber(customerAddress.getMobileNumber());
1961
        return customAddress;
1962
    }
1963
 
33665 ranu 1964
    private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions,
1965
                                                      float totalAmount) throws ProfitMandiBusinessException {
32145 tejbeer 1966
        Set<Integer> paymentOptionIds = new HashSet<>();
23650 amit.gupta 1967
 
32145 tejbeer 1968
        float calculatedAmount = 0;
1969
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1970
            paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1971
            calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
1972
        }
1973
        if (calculatedAmount != totalAmount) {
1974
            LOGGER.warn("Error occured while validating payment options amount - {} != TotalAmount {}", calculatedAmount, totalAmount);
1975
            throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
1976
        }
23418 ashik.ali 1977
 
32145 tejbeer 1978
        List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
1979
        if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
1980
            paymentOptionIds.removeAll(foundPaymentOptionIds);
1981
            throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds, "FFORDR_1017");
1982
        }
1983
    }
25101 amit.gupta 1984
 
32145 tejbeer 1985
    @Override
1986
    public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1987
        List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1988
        if (!fofoOrderItems.isEmpty()) {
1989
            List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1990
            Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1991
            Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1992
            while (fofoOrderItemsIterator.hasNext()) {
1993
                FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1994
                fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1995
                newFofoOrderItems.add(fofoOrderItem);
1996
                fofoOrderItemsIterator.remove();
1997
            }
1998
            fofoOrderItems = newFofoOrderItems;
1999
        }
2000
        return fofoOrderItems;
2001
    }
25101 amit.gupta 2002
 
32145 tejbeer 2003
    private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
2004
        Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
2005
            @Override
2006
            public Integer apply(FofoOrderItem fofoOrderItem) {
2007
                return fofoOrderItem.getId();
2008
            }
2009
        };
2010
        return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
2011
    }
25101 amit.gupta 2012
 
33665 ranu 2013
    private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) throws
2014
            ProfitMandiBusinessException {
32145 tejbeer 2015
        Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
2016
        List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
2017
        Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
2018
        for (FofoLineItem fofoLineItem : fofoLineItems) {
2019
            if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
2020
                Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
2021
                fofoLineItems2.add(fofoLineItem);
2022
                fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
2023
            } else {
2024
                fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
2025
            }
2026
        }
2027
        return fofoOrderItemIdFofoLineItemsMap;
2028
    }
25101 amit.gupta 2029
 
32145 tejbeer 2030
    @Override
33665 ranu 2031
    public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber) throws
2032
            ProfitMandiBusinessException {
32145 tejbeer 2033
        FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2034
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
2035
        customer.setFirstName(customCustomer.getFirstName());
2036
        customer.setLastName(customCustomer.getLastName());
2037
        customer.setMobileNumber(customCustomer.getMobileNumber());
2038
        customer.setEmailId(customCustomer.getEmailId());
2039
        customerRepository.persist(customer);
2040
        CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
2041
        if (!customerAddress.getState().equalsIgnoreCase(customCustomer.getAddress().getState())) {
2042
            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
2043
            resetTaxation(fofoOrder.getFofoId(), customerAddress, fofoOrderItems);
2044
        }
2045
        this.setCustomerAddress(customerAddress, customCustomer.getAddress());
2046
        fofoOrder.setCustomerGstNumber(customCustomer.getGstNumber());
2047
    }
23638 amit.gupta 2048
 
33665 ranu 2049
    private void resetTaxation(int fofoId, CustomerAddress customerAddress, List<FofoOrderItem> fofoOrderItems) throws
2050
            ProfitMandiBusinessException {
32145 tejbeer 2051
        int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
23650 amit.gupta 2052
 
32145 tejbeer 2053
        Address retailerAddress = addressRepository.selectById(retailerAddressId);
24275 amit.gupta 2054
 
32145 tejbeer 2055
        Integer stateId = null;
2056
        if (customerAddress.getState().equalsIgnoreCase(retailerAddress.getState())) {
2057
            try {
2058
                stateId = Long.valueOf(stateRepository.selectByName(customerAddress.getState()).getId()).intValue();
2059
            } catch (Exception e) {
2060
                LOGGER.error("Unable to get state rates");
2061
            }
2062
        }
2063
        List<Integer> itemIds = fofoOrderItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
2064
        final Map<Integer, GstRate> gstRates;
2065
        if (stateId != null) {
2066
            gstRates = stateGstRateRepository.getStateTaxRate(itemIds, stateId);
2067
        } else {
2068
            gstRates = stateGstRateRepository.getIgstTaxRate(itemIds);
2069
        }
2070
        for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
2071
            GstRate rate = gstRates.get(fofoOrderItem.getItemId());
2072
            fofoOrderItem.setCgstRate(rate.getCgstRate());
2073
            fofoOrderItem.setSgstRate(rate.getSgstRate());
2074
            fofoOrderItem.setIgstRate(rate.getIgstRate());
2075
        }
2076
    }
24275 amit.gupta 2077
 
32145 tejbeer 2078
    @Override
33665 ranu 2079
    public CustomerCreditNote badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest) throws
2080
            ProfitMandiBusinessException {
32145 tejbeer 2081
        FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFofoOrderItemId());
2082
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
2083
        if (fofoOrder.getFofoId() != fofoId) {
2084
            throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
2085
        }
2086
        int billedQty = foi.getQuantity() - customerReturnItemRepository.selectAllByOrderItemId(foi.getId()).size();
2087
        if (foiBadReturnRequest.getMarkedBadArr().size() > billedQty) {
2088
            throw new ProfitMandiBusinessException("Cant bad return more than what is billed", "", "Invalid Quantity");
2089
        }
2090
        List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
2091
        for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getMarkedBadArr()) {
2092
            CustomerReturnItem customerReturnItem = new CustomerReturnItem();
2093
            customerReturnItem.setFofoId(fofoId);
2094
            customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFofoOrderItemId());
2095
            customerReturnItem.setFofoOrderId(fofoOrder.getId());
2096
            customerReturnItem.setRemarks(badReturnRequest.getRemarks());
2097
            customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
2098
            customerReturnItem.setQuantity(1);
2099
            customerReturnItem.setType(ReturnType.BAD);
2100
            // customerReturnItemRepository.persist(customerReturnItem);
2101
            inventoryService.saleReturnInventoryItem(customerReturnItem);
2102
            customerReturnItems.add(customerReturnItem);
2103
        }
2104
        CustomerCreditNote creditNote = generateCreditNote(fofoOrder, customerReturnItems);
2105
        for (CustomerReturnItem customerReturnItem : customerReturnItems) {
2106
            purchaseReturnService.returnInventoryItem(fofoId, false, customerReturnItem.getInventoryItemId(), ReturnType.BAD);
2107
        }
2108
        // This should cancel the order
2109
        fofoOrder.setCancelledTimestamp(LocalDateTime.now());
2110
        this.reverseScheme(fofoOrder);
2111
        return creditNote;
2112
    }
23638 amit.gupta 2113
 
33665 ranu 2114
    private CustomerCreditNote generateCreditNote(FofoOrder
2115
                                                          fofoOrder, List<CustomerReturnItem> customerReturnItems) throws ProfitMandiBusinessException {
24275 amit.gupta 2116
 
32145 tejbeer 2117
        InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoOrder.getFofoId());
2118
        sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
2119
        invoiceNumberGenerationSequenceRepository.persist(sequence);
24275 amit.gupta 2120
 
32145 tejbeer 2121
        String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getCreditNoteSequence();
2122
        CustomerCreditNote creditNote = new CustomerCreditNote();
2123
        creditNote.setCreditNoteNumber(creditNoteNumber);
2124
        creditNote.setFofoId(fofoOrder.getFofoId());
2125
        creditNote.setFofoOrderId(fofoOrder.getId());
2126
        creditNote.setFofoOrderItemId(customerReturnItems.get(0).getFofoOrderItemId());
2127
        creditNote.setSettlementType(SettlementType.UNSETTLED);
2128
        customerCreditNoteRepository.persist(creditNote);
24275 amit.gupta 2129
 
32145 tejbeer 2130
        for (CustomerReturnItem customerReturnItem : customerReturnItems) {
2131
            customerReturnItem.setCreditNoteId(creditNote.getId());
2132
            customerReturnItemRepository.persist(customerReturnItem);
2133
        }
2134
        // this.returnInventoryItems(inventoryItems, debitNote);
23655 amit.gupta 2135
 
32145 tejbeer 2136
        return creditNote;
2137
    }
23655 amit.gupta 2138
 
32145 tejbeer 2139
    @Override
2140
    public CreditNotePdfModel getCreditNotePdfModel(int customerCreditNoteId) throws ProfitMandiBusinessException {
2141
        CustomerCreditNote creditNote = customerCreditNoteRepository.selectById(customerCreditNoteId);
2142
        return getCreditNotePdfModel(creditNote);
2143
    }
24275 amit.gupta 2144
 
33665 ranu 2145
    private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote) throws
2146
            ProfitMandiBusinessException {
32145 tejbeer 2147
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(creditNote.getFofoOrderId());
2148
        List<CustomerReturnItem> customerReturnItems = customerReturnItemRepository.selectAllByCreditNoteId(creditNote.getId());
33090 amit.gupta 2149
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoOrder.getFofoId());
2150
        CustomCustomer customCustomer = getCustomCustomer(fofoOrder, customRetailer.getAddress());
24275 amit.gupta 2151
 
33298 amit.gupta 2152
        List<CustomOrderItem> customerFofoOrderItems = new ArrayList<>();
23655 amit.gupta 2153
 
32145 tejbeer 2154
        FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(creditNote.getFofoOrderItemId());
2155
        float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
2156
        float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
2157
        float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
24275 amit.gupta 2158
 
32145 tejbeer 2159
        CustomOrderItem customFofoOrderItem = new CustomOrderItem();
2160
        customFofoOrderItem.setAmount(customerReturnItems.size() * (taxableSellingPrice - taxableDiscountPrice));
2161
        customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
24275 amit.gupta 2162
 
32145 tejbeer 2163
        if (ItemType.SERIALIZED.equals(itemRepository.selectById(fofoOrderItem.getItemId()).getType())) {
2164
            Set<Integer> inventoryItemIds = customerReturnItems.stream().map(x -> x.getInventoryItemId()).collect(Collectors.toSet());
2165
            List<String> serialNumbers = inventoryItemRepository.selectByIds(inventoryItemIds).stream().map(x -> x.getSerialNumber()).collect(Collectors.toList());
2166
            customFofoOrderItem.setDescription(
2167
                    customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
2168
        }
23638 amit.gupta 2169
 
32145 tejbeer 2170
        customFofoOrderItem.setRate(taxableSellingPrice);
2171
        customFofoOrderItem.setDiscount(taxableDiscountPrice);
2172
        customFofoOrderItem.setQuantity(customerReturnItems.size());
2173
        customFofoOrderItem.setNetAmount(
2174
                (fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * customFofoOrderItem.getQuantity());
29707 tejbeer 2175
 
32145 tejbeer 2176
        float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
2177
        float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
2178
        float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
2179
        LOGGER.info("fofoOrderItem - {}", fofoOrderItem);
2180
        customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
2181
        customFofoOrderItem.setIgstAmount(igstAmount);
2182
        customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
2183
        customFofoOrderItem.setCgstAmount(cgstAmount);
2184
        customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
2185
        customFofoOrderItem.setSgstAmount(sgstAmount);
2186
        customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
2187
        customFofoOrderItem.setOrderId(1);
2188
        customerFofoOrderItems.add(customFofoOrderItem);
29707 tejbeer 2189
 
32145 tejbeer 2190
        InvoicePdfModel pdfModel = new InvoicePdfModel();
2191
        pdfModel.setAuther("NSSPL");
2192
        pdfModel.setCustomer(customCustomer);
2193
        pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
2194
        pdfModel.setInvoiceDate(FormattingUtils.formatDate(fofoOrder.getCreateTimestamp()));
2195
        pdfModel.setTitle("Credit Note");
2196
        pdfModel.setRetailer(customRetailer);
2197
        pdfModel.setTotalAmount(customFofoOrderItem.getNetAmount());
2198
        pdfModel.setOrderItems(customerFofoOrderItems);
29707 tejbeer 2199
 
32145 tejbeer 2200
        CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
2201
        creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
2202
        creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
2203
        creditNotePdfModel.setPdfModel(pdfModel);
2204
        return creditNotePdfModel;
2205
    }
24264 amit.gupta 2206
 
32145 tejbeer 2207
    // This will remove the order and maintain order record and reverse inventory
2208
    // and scheme
2209
    @Override
2210
    public void cancelOrder(List<String> invoiceNumbers) throws ProfitMandiBusinessException {
2211
        for (String invoiceNumber : invoiceNumbers) {
2212
            // Cancel only when not cancelled
2213
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
2214
            if (fofoOrder.getCancelledTimestamp() == null) {
2215
                fofoOrder.setCancelledTimestamp(LocalDateTime.now());
2216
                PaymentOptionTransaction paymentTransaction = new PaymentOptionTransaction();
2217
                paymentTransaction.setAmount(-fofoOrder.getTotalAmount());
2218
                paymentTransaction.setFofoId(fofoOrder.getFofoId());
2219
                paymentTransaction.setReferenceId(fofoOrder.getId());
2220
                paymentTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
2221
                paymentTransaction.setPaymentOptionId(1);
2222
                paymentOptionTransactionRepository.persist(paymentTransaction);
31030 amit.gupta 2223
 
32145 tejbeer 2224
                List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
2225
                if (fois.size() > 0) {
2226
                    List<InventoryItem> inventoryItems = new ArrayList<>();
2227
                    fois.stream().forEach(x -> {
2228
                        x.getFofoLineItems().stream().forEach(y -> {
2229
                            inventoryService.rollbackInventory(y.getInventoryItemId(), y.getQuantity(), fofoOrder.getFofoId());
2230
                            inventoryItems.add(inventoryItemRepository.selectById(y.getInventoryItemId()));
2231
                        });
2232
                    });
2233
                    // if(invoice)
2234
                    this.reverseScheme(fofoOrder);
2235
                }
2236
                insuranceService.cancelInsurance(fofoOrder);
2237
            }
2238
        }
2239
    }
31030 amit.gupta 2240
 
32145 tejbeer 2241
    @Override
2242
    public void reverseScheme(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
2243
        String reversalReason = "Order Rolledback/Cancelled/Returned for Invoice #" + fofoOrder.getInvoiceNumber();
2244
        List<FofoOrderItem> fois = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
2245
        Set<Integer> inventoryItemIds = fois.stream().flatMap(x -> x.getFofoLineItems().stream().map(y -> y.getInventoryItemId())).collect(Collectors.toSet());
2246
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds);
2247
        schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, SchemeService.OUT_SCHEME_TYPES);
2248
        schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, Arrays.asList(SchemeType.INVESTMENT));
2249
        schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, Arrays.asList(SchemeType.ACTIVATION));
2250
        schemeService.reverseSchemes(inventoryItems, fofoOrder.getId(), reversalReason, Arrays.asList(SchemeType.SPECIAL_SUPPORT));
31030 amit.gupta 2251
 
32145 tejbeer 2252
    }
24271 amit.gupta 2253
 
32145 tejbeer 2254
    @Override
2255
    public void reverseActivationScheme(List<Integer> inventoryItemIds) throws ProfitMandiBusinessException {
2256
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(inventoryItemIds);
2257
        for (InventoryItem inventoryItem : inventoryItems) {
2258
            List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByInventoryItemId(inventoryItem.getId());
2259
            FofoLineItem fofoLineItem = fofoLineItems.get(0);
2260
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(fofoLineItem.getFofoOrderItemId());
2261
            FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderItem.getOrderId());
2262
            String reversalReason = "Scheme rolled back as activation date is invalid for imei " + inventoryItem.getSerialNumber();
2263
            schemeService.reverseSchemes(Arrays.asList(inventoryItem), fofoOrder.getId(), reversalReason, Arrays.asList(SchemeType.ACTIVATION));
2264
            schemeService.reverseSchemes(Arrays.asList(inventoryItem), fofoOrder.getId(), reversalReason, Arrays.asList(SchemeType.SPECIAL_SUPPORT));
27083 amit.gupta 2265
 
32145 tejbeer 2266
        }
24271 amit.gupta 2267
 
32145 tejbeer 2268
    }
24271 amit.gupta 2269
 
32145 tejbeer 2270
    @Override
2271
    public float getSales(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
2272
        Float sales = fofoOrderRepository.selectSaleSumGroupByFofoIds(startDate, endDate).get(fofoId);
2273
        return sales == null ? 0f : sales;
2274
    }
24271 amit.gupta 2275
 
32145 tejbeer 2276
    @Override
2277
    public LocalDateTime getMaxSalesDate(int fofoId, LocalDateTime startDate, LocalDateTime endDate) {
2278
        LocalDateTime dateTime = fofoOrderRepository.selectMaxSaleDateGroupByFofoIds(startDate, endDate).get(fofoId);
2279
        return dateTime;
2280
    }
25101 amit.gupta 2281
 
32145 tejbeer 2282
    @Override
2283
    // Only being used internally
2284
    public float getSales(int fofoId, LocalDate onDate) {
2285
        LocalDateTime startTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT);
2286
        LocalDateTime endTime = LocalDateTime.of(onDate, LocalTime.MIDNIGHT).plusDays(1);
2287
        return this.getSales(fofoId, startTime, endTime);
2288
    }
24917 tejbeer 2289
 
32145 tejbeer 2290
    @Override
2291
    public float getSales(LocalDateTime onDate) {
2292
        // TODO Auto-generated method stub
2293
        return 0;
2294
    }
28166 tejbeer 2295
 
32145 tejbeer 2296
    @Override
2297
    public float getSales(LocalDateTime startDate, LocalDateTime endDate) {
2298
        // TODO Auto-generated method stub
2299
        return 0;
2300
    }
28166 tejbeer 2301
 
32145 tejbeer 2302
    @Override
2303
    public boolean notifyColorChange(int orderId, int itemId) throws ProfitMandiBusinessException {
2304
        Order order = orderRepository.selectById(orderId);
2305
        saholicInventoryService.reservationCountByColor(itemId, order);
28166 tejbeer 2306
 
32145 tejbeer 2307
        order.getLineItem().setItemId(itemId);
2308
        Item item = itemRepository.selectById(itemId);
2309
        order.getLineItem().setColor(item.getColor());
2310
        return true;
2311
    }
28166 tejbeer 2312
 
32145 tejbeer 2313
    @Override
2314
    public FofoOrder getOrderByInventoryItemId(int inventoryItemId) throws Exception {
2315
        List<FofoLineItem> lineItems = fofoLineItemRepository.selectByInventoryItemId(inventoryItemId);
2316
        if (lineItems.size() > 0) {
2317
            FofoOrderItem fofoOrderItem = fofoOrderItemRepository.selectById(lineItems.get(0).getFofoOrderItemId());
2318
            fofoOrderItem.setFofoLineItems(new HashSet<>(lineItems));
2319
            FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderItem.getOrderId());
2320
            fofoOrder.setOrderItem(fofoOrderItem);
2321
            return fofoOrder;
2322
        } else {
2323
            throw new Exception(String.format("Could not find inventoryItemId - %s", inventoryItemId));
2324
        }
2325
    }
28166 tejbeer 2326
 
32145 tejbeer 2327
    @Override
2328
    public Map<Integer, Long> carryBagCreditCount(int fofoId) throws ProfitMandiBusinessException {
28166 tejbeer 2329
 
32145 tejbeer 2330
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
2331
        LocalDateTime lastCredit = fs.getBagsLastCredited();
2332
        /*
2333
         * long carryBagCount = 0; List<FofoOrder> fofoOrders =
2334
         * fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(fofoId,
2335
         * lastCredit.atStartOfDay(), LocalDate.now().plusDays(1).atStartOfDay()); for
2336
         * (FofoOrder fo : fofoOrders) { carryBagCount +=
2337
         * fofoOrderItemRepository.selectByOrderId(fo.getId()).stream() .filter(x ->
2338
         * x.getSellingPrice() >= 12000).count();
2339
         *
2340
         * }
2341
         */
28166 tejbeer 2342
 
32145 tejbeer 2343
        Session session = sessionFactory.getCurrentSession();
2344
        CriteriaBuilder cb = session.getCriteriaBuilder();
2345
 
2346
        CriteriaQuery<SimpleEntry> query = cb.createQuery(SimpleEntry.class);
2347
        Root<FofoOrder> fofoOrder = query.from(FofoOrder.class);
2348
        Root<FofoOrderItem> fofoOrderItem = query.from(FofoOrderItem.class);
2349
        Root<TagListing> tagListingRoot = query.from(TagListing.class);
2350
        Root<Item> itemRoot = query.from(Item.class);
2351
 
2352
        Predicate p2 = cb.between(fofoOrder.get(ProfitMandiConstants.CREATE_TIMESTAMP), lastCredit, LocalDate.now().atStartOfDay());
2353
        Predicate p3 = cb.isNull(fofoOrder.get("cancelledTimestamp"));
2354
        Predicate joinPredicate = cb.and(
2355
                cb.equal(fofoOrder.get(ProfitMandiConstants.ID), fofoOrderItem.get(ProfitMandiConstants.ORDER_ID)), cb.equal(fofoOrderItem.get("itemId"), tagListingRoot.get("itemId")), cb.equal(itemRoot.get("id"), tagListingRoot.get("itemId")), cb.equal(fofoOrder.get(ProfitMandiConstants.FOFO_ID), fofoId));
2356
        ItemCriteria itemCriteria = new ItemCriteria();
2357
        itemCriteria.setBrands(mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name")).collect(Collectors.toList()));
2358
        float startValue = 12000;
2359
        itemCriteria.setStartPrice(startValue);
2360
        itemCriteria.setEndPrice(0);
2361
        itemCriteria.setFeaturedPhone(false);
2362
        itemCriteria.setSmartPhone(true);
2363
        itemCriteria.setCatalogIds(new ArrayList<>());
2364
        itemCriteria.setExcludeCatalogIds(new ArrayList<>());
2365
        Predicate itemPredicate = itemRepository.getItemPredicate(itemCriteria, cb, itemRoot, tagListingRoot.get("itemId"), tagListingRoot.get("sellingPrice"));
2366
        Predicate finalPredicate = cb.and(itemPredicate, p2, p3, joinPredicate);
2367
        query = query.multiselect(fofoOrder.get(ProfitMandiConstants.FOFO_ID), cb.count(fofoOrder)).where(finalPredicate).groupBy(fofoOrder.get(ProfitMandiConstants.FOFO_ID));
2368
        List<SimpleEntry> simpleEntries = session.createQuery(query).getResultList();
2369
        Map<Integer, Long> returnMap = new HashMap<>();
2370
 
2371
        for (SimpleEntry simpleEntry : simpleEntries) {
2372
            returnMap.put((Integer) simpleEntry.getKey(), (Long) simpleEntry.getValue());
2373
        }
2374
        return returnMap;
2375
 
2376
    }
32607 ranu 2377
 
2378
    @Override
2379
    public void createMissingScratchOffers() {
2380
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectFromSaleDate(LocalDate.of(2023, 11, 6).atStartOfDay());
2381
        for (FofoOrder fofoOrder : fofoOrders) {
2382
            if (fofoOrder.getCancelledTimestamp() == null) { // Check if cancelled_timestamp is not null
2383
                try {
2384
                    this.createScratchOffer(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber(), fofoOrder.getCustomerId());
2385
                } catch (Exception e) {
2386
                    LOGGER.error("Error while processing missing scratch offer invoice orderId", fofoOrder.getId());
2387
                }
2388
            }
2389
        }
2390
    }
32724 amit.gupta 2391
 
2392
    @Override
33665 ranu 2393
    public boolean refundOrder(int orderId, String refundedBy, String refundReason) throws
2394
            ProfitMandiBusinessException {
32724 amit.gupta 2395
        /*def refund_order(order_id, refunded_by, reason):
2396
        """
2397
        If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2398
            1. Creates a refund request for batch processing.
2399
            2. Creates a return order for the warehouse executive to return the shipped material.
2400
            3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2401
 
2402
        If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2403
            1. Creates a refund request for batch processing.
2404
            2. Cancels the reservation of the item in the warehouse.
2405
            3. Marks the current order as the REFUNDED final state.
2406
 
2407
        For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2408
            1. Cancels the reservation of the item in the warehouse.
2409
            2. Marks the current order as CANCELED.
2410
 
2411
        In all cases, it updates the reason for cancellation or refund and the person who performed the action.
2412
 
2413
        Returns True if it is successful, False otherwise.
2414
 
2415
        Throws an exception if the order with the given id couldn't be found.
2416
 
2417
        Parameters:
2418
         - order_id
2419
         - refunded_by
2420
         - reason
2421
        """
2422
        LOGGER.info("Refunding order id: {}", orderId);
2423
        Order order = orderRepository.selectById(orderId);
2424
 
2425
        if order.cod:
2426
        logging.info("Refunding COD order with status " + str(order.status))
2427
        status_transition = refund_status_transition
2428
        if order.status not in status_transition.keys():
2429
        raise TransactionServiceException(114, "This order can't be refunded")
2430
 
2431
        if order.status in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
2432
        __update_inventory_reservation(order, refund=True)
2433
        order.statusDescription = "Order Cancelled"
2434
            #Shipment Id and Airway Bill No should be none in case of Cancellation
2435
        order.logisticsTransactionId = None
2436
        order.tracking_id = None
2437
        order.airwaybill_no = None
2438
        elif order.status == OrderStatus.BILLED:
2439
        __create_return_order(order)
2440
        order.statusDescription = "Order Cancelled"
2441
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
2442
        if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2443
        __create_return_order(order)
2444
        order.statusDescription = "RTO Refunded"
2445
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
2446
            #__create_return_order(order)
2447
        order.statusDescription = "Lost in Transit Refunded"
2448
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
2449
        if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2450
        __create_return_order(order)
2451
        __create_refund(order, 0, 'Should be unreachable for now')
2452
        order.statusDescription = "DOA Refunded"
2453
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
2454
        if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2455
        __create_return_order(order)
2456
        __create_refund(order, 0, 'Should be unreachable for now')
2457
        order.statusDescription = "Return Refunded"
2458
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
2459
        if order.previousStatus in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
2460
        __update_inventory_reservation(order, refund=True)
2461
        order.statusDescription = "Order Cancelled on customer request"
2462
        elif order.previousStatus == OrderStatus.BILLED:
2463
        __create_return_order(order)
2464
        order.statusDescription = "Order Cancelled on customer request"
2465
        order.received_return_timestamp = datetime.datetime.now()
2466
    else:
2467
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2468
                OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
2469
                OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2470
                OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
2471
                OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2472
                OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
2473
                OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2474
                OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
2475
                OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2476
                OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2477
                OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2478
                OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
2479
                OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2480
                OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2481
                OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2482
                OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2483
                OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2484
                OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2485
                OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2486
                OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
2487
                OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
2488
                     }
2489
        if order.status not in status_transition.keys():
2490
        raise TransactionServiceException(114, "This order can't be refunded")
2491
 
2492
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
2493
        if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2494
        __create_return_order(order)
2495
        __create_refund(order, order.wallet_amount, 'Order #{0} is RTO refunded'.format(order.id))
2496
        order.statusDescription = "RTO Refunded"
2497
            #Start:- Added By Manish Sharma for Creating a new Ticket: Category- RTO Refund on 21-Jun-2013
2498
        try:
2499
        crmServiceClient = CRMClient().get_client()
2500
        ticket =Ticket()
2501
        activity = Activity()
2502
 
2503
        description = "Creating Ticket for " + order.statusDescription + " Order"
2504
        ticket.creatorId = 1
2505
        ticket.assigneeId = 34
2506
        ticket.category = TicketCategory.RTO_REFUND
2507
        ticket.priority = TicketPriority.MEDIUM
2508
        ticket.status = TicketStatus.OPEN
2509
        ticket.description = description
2510
        ticket.orderId = order.id
2511
 
2512
        activity.creatorId = 1
2513
        activity.ticketAssigneeId = ticket.assigneeId
2514
        activity.type = ActivityType.OTHER
2515
        activity.description = description
2516
        activity.ticketCategory = ticket.category
2517
        activity.ticketDescription = ticket.description
2518
        activity.ticketPriority = ticket.priority
2519
        activity.ticketStatus = ticket.status
2520
 
2521
        ticket.customerId= order.customer_id
2522
        ticket.customerEmailId = order.customer_email
2523
        ticket.customerMobileNumber = order.customer_mobilenumber
2524
        ticket.customerName = order.customer_name
2525
        activity.customerId = ticket.customerId
2526
        activity.customerEmailId = order.customer_email
2527
        activity.customerMobileNumber = order.customer_mobilenumber
2528
        activity.customerName = order.customer_name
2529
 
2530
        crmServiceClient.insertTicket(ticket, activity)
2531
 
2532
        except:
2533
        print "Ticket for RTO Refund is not created."
2534
            #End:- Added By Manish Sharma for Creating a new Ticket: Category- RTO Refund on 21-Jun-2013
2535
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
2536
            #__create_return_order(order)
2537
        __create_refund(order, order.wallet_amount, 'Order #{0} is Lost in Transit'.format(order.id))
2538
        order.statusDescription = "Lost in Transit Refunded"
2539
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
2540
        if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2541
        __create_return_order(order)
2542
        __create_refund(order, 0, 'This should be unreachable')
2543
        order.statusDescription = "DOA Refunded"
2544
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
2545
        if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2546
        __create_return_order(order)
2547
        __create_refund(order, 0, 'This should be unreachable')
2548
        order.statusDescription = "Return Refunded"
2549
        elif order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
2550
        __update_inventory_reservation(order, refund=True)
2551
        order.statusDescription = "Order Refunded"
2552
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
2553
        if order.previousStatus in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.PAYMENT_FLAGGED, OrderStatus.ACCEPTED]:
2554
        __update_inventory_reservation(order, refund=True)
2555
        order.statusDescription = "Order Cancelled on customer request"
2556
        elif order.previousStatus == OrderStatus.BILLED:
2557
        __create_refund(order, order.wallet_amount,  'Order #{0} Cancelled on customer request'.format(order.id))
2558
        order.statusDescription = "Order Cancelled on customer request"
2559
 
2560
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
2561
        __update_inventory_reservation(order, refund=True)
2562
        order.statusDescription = "Order Cancelled due to payment flagged"
2563
 
2564
    # For orders that are cancelled after being billed, we need to scan in the scanned out
2565
    # inventory item and change availability accordingly
2566
        inventoryClient = InventoryClient().get_client()
2567
        warehouse = inventoryClient.getWarehouse(order.warehouse_id)
2568
        if warehouse.billingType == BillingType.OURS or warehouse.billingType == BillingType.OURS_EXTERNAL:
2569
        #Now BILLED orders can also be refunded directly with low inventory cancellations
2570
        if order.status in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH]:
2571
        __create_refund(order, order.wallet_amount, reason)
2572
        if order.status in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH] or (order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED and order.previousStatus in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH]):
2573
        lineitem = order.lineitems[0]
2574
        catalogClient = CatalogClient().get_client()
2575
        item = catalogClient.getItem(lineitem.item_id)
2576
        warehouseClient = WarehouseClient().get_client()
2577
        if warehouse.billingType == BillingType.OURS:
2578
        if ItemType.SERIALIZED == item.type:
2579
        for serial_number in str(lineitem.serial_number).split(','):
2580
        warehouseClient.scanSerializedItemForOrder(serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, 1, order.warehouse_id)
2581
                else:
2582
        warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
2583
        if warehouse.billingType == BillingType.OURS_EXTERNAL:
2584
        warehouseClient.scanForOursExternalSaleReturn(order.id, lineitem.transfer_price)
2585
        if order.freebieItemId:
2586
        warehouseClient.scanfreebie(order.id, order.freebieItemId, 0, ScanType.SALE_RET)
2587
 
2588
        order.status = status_transition[order.status]
2589
        order.statusDescription = OrderStatus._VALUES_TO_NAMES[order.status]
2590
        order.refund_timestamp = datetime.datetime.now()
2591
        order.refunded_by = refunded_by
2592
        order.refund_reason = reason
2593
    #to re evaluate the shipping charge if any order is being cancelled.
2594
    #_revaluate_shiping(order_id)
2595
        session.commit()
2596
        return True*/
2597
        return true;
2598
    }
2599
 
2600
    @Autowired
2601
    DebitNoteRepository debitNoteRepository;
2602
 
2603
    //initiate refund only if the stock is returned
2604
 
25724 amit.gupta 2605
}