Subversion Repositories SmartDukaan

Rev

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