Subversion Repositories SmartDukaan

Rev

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