Subversion Repositories SmartDukaan

Rev

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