Subversion Repositories SmartDukaan

Rev

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