Subversion Repositories SmartDukaan

Rev

Rev 34319 | Rev 34340 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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