Subversion Repositories SmartDukaan

Rev

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