Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
33172 tejus.loha 1
package com.spice.profitmandi.service.order;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.BulkOrderModel;
33341 tejus.loha 5
import com.spice.profitmandi.common.model.LineItemModel;
33547 tejus.loha 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
33341 tejus.loha 7
import com.spice.profitmandi.common.model.TransactionApprovalModel;
33172 tejus.loha 8
import com.spice.profitmandi.common.util.ExcelUtils;
9
import com.spice.profitmandi.dao.cart.CartService;
33341 tejus.loha 10
import com.spice.profitmandi.dao.entity.auth.AuthUser;
34443 vikas.jang 11
import com.spice.profitmandi.dao.entity.catalog.Bid;
34832 ranu 12
import com.spice.profitmandi.dao.entity.catalog.Item;
33172 tejus.loha 13
import com.spice.profitmandi.dao.entity.catalog.TagListing;
34856 ranu 14
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
34566 ranu 15
import com.spice.profitmandi.dao.entity.fofo.LoanTransaction;
34674 aman.kumar 16
import com.spice.profitmandi.dao.entity.transaction.LineItem;
17
import com.spice.profitmandi.dao.entity.transaction.Order;
18
import com.spice.profitmandi.dao.entity.transaction.Transaction;
19
import com.spice.profitmandi.dao.entity.transaction.TransactionApproval;
33213 tejus.loha 20
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
33172 tejus.loha 21
import com.spice.profitmandi.dao.model.CartItem;
22
import com.spice.profitmandi.dao.model.UserCart;
33341 tejus.loha 23
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
34468 vikas.jang 24
import com.spice.profitmandi.dao.repository.catalog.BidRepository;
34832 ranu 25
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
34468 vikas.jang 26
import com.spice.profitmandi.dao.repository.catalog.LiquidationRepository;
33172 tejus.loha 27
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
34443 vikas.jang 28
import com.spice.profitmandi.dao.repository.cs.CsService;
34856 ranu 29
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33172 tejus.loha 30
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
34566 ranu 31
import com.spice.profitmandi.dao.repository.fofo.LoanTransactionRepository;
33341 tejus.loha 32
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 33
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 34
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
35
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
36
import com.spice.profitmandi.dao.repository.user.AddressRepository;
34468 vikas.jang 37
import com.spice.profitmandi.dao.service.BidService;
34832 ranu 38
import com.spice.profitmandi.service.catalog.BrandsService;
34661 ranu 39
import com.spice.profitmandi.service.transaction.BlockLoanIdSanctionId;
33338 amit.gupta 40
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 41
import com.spice.profitmandi.service.transaction.TransactionService;
42
import com.spice.profitmandi.service.wallet.CommonPaymentService;
43
import com.spice.profitmandi.service.wallet.WalletService;
44
import org.apache.logging.log4j.LogManager;
45
import org.apache.logging.log4j.Logger;
33213 tejus.loha 46
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 47
import org.apache.poi.ss.usermodel.Row;
48
import org.apache.poi.xssf.usermodel.XSSFRow;
49
import org.apache.poi.xssf.usermodel.XSSFSheet;
50
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
51
import org.springframework.beans.factory.annotation.Autowired;
33213 tejus.loha 52
import org.springframework.stereotype.Service;
53
import org.springframework.transaction.annotation.Transactional;
33172 tejus.loha 54
import org.springframework.web.multipart.MultipartFile;
55
 
33338 amit.gupta 56
import java.math.BigDecimal;
33172 tejus.loha 57
import java.util.ArrayList;
58
import java.util.List;
59
import java.util.Map;
60
import java.util.stream.Collectors;
61
 
33213 tejus.loha 62
@Service
33172 tejus.loha 63
public class BulkOrderService {
64
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
65
    @Autowired
66
    CartService cartService;
67
    @Autowired
68
    TransactionService transactionService;
69
    @Autowired
70
    CommonPaymentService commonPaymentService;
71
    @Autowired
72
    TagListingRepository tagListingRepository;
73
    @Autowired
74
    WalletService walletService;
75
    @Autowired
76
    UserRepository userRepository;
33213 tejus.loha 77
    @Autowired
78
    TransactionRepository transactionRepository;
79
    @Autowired
80
    TransactionApprovalRepository transactionApprovalRepository;
81
    @Autowired
82
    AddressRepository addressRepository;
33341 tejus.loha 83
    @Autowired
84
    OrderRepository orderRepository;
34443 vikas.jang 85
    //TODO:Tejus need to check
33341 tejus.loha 86
    @Autowired
87
    SDCreditRequirementRepository sdCreditRequirementRepository;
33338 amit.gupta 88
    @Autowired
89
    SDCreditService sdCreditService;
34443 vikas.jang 90
    @Autowired
91
    private CsService csService;
92
    @Autowired
34468 vikas.jang 93
    private AuthRepository authRepository;
34443 vikas.jang 94
    @Autowired
34468 vikas.jang 95
    private BidRepository bidRepository;
96
    @Autowired
97
    private BidService bidService;
98
    @Autowired
34832 ranu 99
    ItemRepository itemRepository;
100
    @Autowired
101
    private BrandsService brandsService;
102
    @Autowired
34566 ranu 103
    private LoanTransactionRepository loanTransactionRepository;
104
 
105
    @Autowired
34468 vikas.jang 106
    private LiquidationRepository liquidationRepository;
33338 amit.gupta 107
 
34674 aman.kumar 108
    @Autowired
109
    com.spice.profitmandi.dao.repository.user.UserRepository user_userRepository;
33338 amit.gupta 110
 
34856 ranu 111
    @Autowired
112
    FofoStoreRepository fofoStoreRepository;
34674 aman.kumar 113
 
34856 ranu 114
 
34468 vikas.jang 115
    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception {
33172 tejus.loha 116
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
117
 
118
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
119
        // Return first sheet from the XLSX workbook
120
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
121
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
122
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
33547 tejus.loha 123
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
33172 tejus.loha 124
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
125
            XSSFRow row = mySheet.getRow(rowNumber);
33547 tejus.loha 126
            LOGGER.info("Row - {}", row);
127
            if (row != null) {
128
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
129
                bulkOrderModels.add(bulkOrderModel);
130
            } else {
131
                break;
132
            }
33172 tejus.loha 133
        }
34468 vikas.jang 134
        this.generatePurchaseOrder(bulkOrderModels, creatorId, ProfitMandiConstants.PO_TYPE.MANUAL, ProfitMandiConstants.BID_CRON_ENUM.TODAY);
34443 vikas.jang 135
    }
136
 
34592 vikas.jang 137
    public ProfitMandiConstants.BID_ENUM generatePurchaseOrder(List<BulkOrderModel> bulkOrderModels, int creatorId, ProfitMandiConstants.PO_TYPE type, ProfitMandiConstants.BID_CRON_ENUM scheduleType) throws Exception {
33172 tejus.loha 138
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
34443 vikas.jang 139
        boolean approvalRequired = false;
34592 vikas.jang 140
        ProfitMandiConstants.BID_ENUM finalBidStatus = ProfitMandiConstants.BID_ENUM.CLOSED;
33172 tejus.loha 141
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
142
            int fofoId = fofoBulkOrderEntry.getKey();
143
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
144
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
145
 
146
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
147
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
148
            }
149
 
150
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
151
            if (hasZeroQuantity) {
152
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
153
            }
154
 
155
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 156
            double totalPayableAmount = 0;
34957 amit 157
            BigDecimal totalPayableAmountBD = new BigDecimal(0);
33172 tejus.loha 158
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
159
                CartItem cartItem = new CartItem();
160
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
161
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
162
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
33556 amit.gupta 163
                if (tagListing == null) {
164
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
165
                    throw new ProfitMandiBusinessException(message, message, message);
166
                }
34832 ranu 167
                List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
168
                Item item = itemRepository.selectById(fofoBulkOrderModel.getItemId());
34856 ranu 169
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
170
                if (!fofoStore.isInternal()) {
171
                    if (partnerIneligibleBrands.contains(item.getBrand())) {
172
                        throw new ProfitMandiBusinessException("Brand is not allowed", "Brand ( " + item.getBrand() + ") is not allowed for this partner", "");
173
                    }
34832 ranu 174
                }
175
 
33213 tejus.loha 176
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 177
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
178
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 179
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
180
                int itemId = cartItem.getItemId();
33597 tejus.loha 181
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 182
                    cartItem.setSellingPrice(itemSellingPrice);
183
                } else {
33216 tejus.loha 184
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 185
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 186
                        approvalRequired = true;
33213 tejus.loha 187
 
188
                    } else {
189
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
190
                    }
191
 
192
                }
34958 amit 193
                totalPayableAmountBD = totalPayableAmountBD.add(new BigDecimal(String.valueOf(cartItem.getSellingPrice())).multiply(new BigDecimal(cartItem.getQuantity())));
33172 tejus.loha 194
                cartItems.add(cartItem);
195
            }
34957 amit 196
            totalPayableAmount = totalPayableAmountBD.doubleValue();
34501 vikas.jang 197
            Bid bid = null;
198
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
199
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
34592 vikas.jang 200
                approvalRequired = false;
34957 amit 201
                totalPayableAmount = totalPayableAmountBD.doubleValue() - ProfitMandiConstants.BID_CHARGES;
34501 vikas.jang 202
            }
33338 amit.gupta 203
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 204
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 205
 
206
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
207
 
208
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 209
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 210
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 211
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34695 aman.kumar 212
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, String.valueOf(fofoId));
34443 vikas.jang 213
                } else {
34468 vikas.jang 214
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
34592 vikas.jang 215
                        finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 216
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
217
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
34468 vikas.jang 218
                    } else {
34592 vikas.jang 219
                        finalBidStatus = bidService.cancelYesterdayProcessBid(bid);
34572 vikas.jang 220
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
221
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
34468 vikas.jang 222
                    }
34443 vikas.jang 223
                }
33172 tejus.loha 224
            }
225
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 226
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 227
 
33351 amit.gupta 228
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 229
            int loanId = 0;
34492 vikas.jang 230
            try {
231
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34576 vikas.jang 232
                    LOGGER.info("Creating new loan for: {}",userCart.getUserId());
34675 aman.kumar 233
                    BlockLoanIdSanctionId loan = sdCreditService.createSDDirectOrder(userCart.getUserId(), totalPayableAmount, 0);
34661 ranu 234
                    loanId = loan.getLoanId();
34492 vikas.jang 235
                }
236
            } catch (Exception exception){
34501 vikas.jang 237
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
34592 vikas.jang 238
                    finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 239
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
240
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
34501 vikas.jang 241
                }
33338 amit.gupta 242
            }
34443 vikas.jang 243
 
34576 vikas.jang 244
            LOGGER.info("finalBidStatus: {}",finalBidStatus);
34573 vikas.jang 245
            if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {
34959 amit 246
                LOGGER.info("totalPayableAmount - {}", totalPayableAmount);
34573 vikas.jang 247
                int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
248
                //Set here created by
249
                Transaction transaction = transactionRepository.selectById(transactionId);
250
                transaction.setCreatedBy(creatorId);
34637 vikas.jang 251
                LOGGER.info("transaction created by {}", transaction.getCreatedBy());
34573 vikas.jang 252
                commonPaymentService.payThroughWallet(transactionId);
253
                if (approvalRequired) {
254
                    this.createApproval(transactionId);
255
                    if (loanId > 0) {
256
                        LoanTransaction loanTransaction = new LoanTransaction();
257
                        loanTransaction.setLoanId(loanId);
258
                        loanTransaction.setTransactionId(transactionId);
259
                        loanTransactionRepository.persist(loanTransaction);
260
                    }
261
                } else {
262
                    transactionService.processTransaction(transactionId, loanId);
263
                }
33213 tejus.loha 264
            }
265
 
33172 tejus.loha 266
        }
34592 vikas.jang 267
        return finalBidStatus;
33172 tejus.loha 268
    }
269
 
33213 tejus.loha 270
    public void createApproval(int transactionId) {
271
        TransactionApproval transactionApproval = new TransactionApproval();
272
        transactionApproval.setId(transactionId);
273
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
274
        transactionApprovalRepository.persist(transactionApproval);
275
    }
276
 
33172 tejus.loha 277
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
278
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
279
        int i = 0;
280
        bulkOrderModel.setRowIndex(row.getRowNum());
281
        try {
33696 amit.gupta 282
            Cell partnerName = row.getCell(i++);
283
            if (partnerName == null)
33213 tejus.loha 284
                bulkOrderModel.setPartnerName("");
285
            else
33696 amit.gupta 286
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 287
            Cell description = row.getCell(i++);
288
            if (description == null)
289
                bulkOrderModel.setDescription("");
290
            else
291
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
292
 
33172 tejus.loha 293
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
294
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 295
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 296
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
297
        } catch (Throwable e) {
298
            LOGGER.info(e.getCause());
33213 tejus.loha 299
            throw new ProfitMandiBusinessException("Field", "Field at row - " + row.getRowNum() + ", column - " + (i - 1), "Invalid field value at - " + ExcelUtils.toAlphabet(i - 1) + (row.getRowNum() + 1) + ", " + ExcelUtils.getCellValue(row.getCell(i - 1)));
33172 tejus.loha 300
        }
301
        LOGGER.info(bulkOrderModel);
302
        return bulkOrderModel;
303
    }
304
 
33341 tejus.loha 305
    // create model for transaction Approval so that finance team see all order and approve
306
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
307
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
308
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
309
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
310
        for (TransactionApproval transactionApproval : transactionApprovals) {
311
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
312
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
313
            List<LineItemModel> lineItemModelList = new ArrayList<>();
314
            for (Order order : orderList) {
315
                LineItem lineItem = order.getLineItem();
316
                LineItemModel lineItemModel = new LineItemModel();
317
                lineItemModel.setItemId(lineItem.getItemId());
318
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
319
                lineItemModel.setItemQuantity(lineItem.getQuantity());
320
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
321
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
322
                lineItemModelList.add(lineItemModel);
323
            }
324
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
325
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
326
            String retailerName = " ";
327
            retailerName = orderList.get(0).getRetailerName();
328
            transactionApprovalModel.setRetailerName(retailerName);
34573 vikas.jang 329
            if (authUser == null) {
330
                transactionApprovalModel.setCreatedBy(retailerName);
331
            } else {
332
                transactionApprovalModel.setCreatedBy(authUser.getFullName());
333
            }
33341 tejus.loha 334
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
335
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
336
            transactionApprovalModel.setLineItemModels(lineItemModelList);
337
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 338
 
33341 tejus.loha 339
        }
340
        return approvalModelList;
341
    }
342
 
33172 tejus.loha 343
}