Subversion Repositories SmartDukaan

Rev

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