Subversion Repositories SmartDukaan

Rev

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