Subversion Repositories SmartDukaan

Rev

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