Subversion Repositories SmartDukaan

Rev

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