Subversion Repositories SmartDukaan

Rev

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