Subversion Repositories SmartDukaan

Rev

Rev 34568 | Rev 34573 | 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
 
34468 vikas.jang 120
    public void 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;
33172 tejus.loha 123
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
124
            int fofoId = fofoBulkOrderEntry.getKey();
125
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
126
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
127
 
128
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
129
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
130
            }
131
 
132
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
133
            if (hasZeroQuantity) {
134
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
135
            }
136
 
137
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 138
            double totalPayableAmount = 0;
33172 tejus.loha 139
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
140
                CartItem cartItem = new CartItem();
141
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
142
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
143
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
33556 amit.gupta 144
                if (tagListing == null) {
145
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
146
                    throw new ProfitMandiBusinessException(message, message, message);
147
                }
33213 tejus.loha 148
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 149
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
150
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 151
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
152
                int itemId = cartItem.getItemId();
33597 tejus.loha 153
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 154
                    cartItem.setSellingPrice(itemSellingPrice);
155
                } else {
33216 tejus.loha 156
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 157
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 158
                        approvalRequired = true;
33213 tejus.loha 159
 
160
                    } else {
161
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
162
                    }
163
 
164
                }
33338 amit.gupta 165
                totalPayableAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
33172 tejus.loha 166
                cartItems.add(cartItem);
167
            }
34501 vikas.jang 168
            Bid bid = null;
169
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
170
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
171
            }
33338 amit.gupta 172
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 173
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 174
 
175
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
176
 
177
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 178
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 179
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 180
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34443 vikas.jang 181
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
182
                } else {
34468 vikas.jang 183
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
184
                        bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34492 vikas.jang 185
                        bid.setStatus(ProfitMandiConstants.BID_ENUM.PROCESSING);
34572 vikas.jang 186
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
187
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
34468 vikas.jang 188
                    } else {
34492 vikas.jang 189
                        bidService.cancelYesterdayProcessBid(bid);
34572 vikas.jang 190
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
191
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
34468 vikas.jang 192
                    }
34443 vikas.jang 193
                }
33172 tejus.loha 194
            }
195
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 196
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 197
 
33351 amit.gupta 198
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 199
            int loanId = 0;
34492 vikas.jang 200
            try {
201
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34568 vikas.jang 202
                    Loan loan = sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 0, "Credit limit assigned via SD Credit");
34492 vikas.jang 203
                    loanId = loan.getId();
204
                }
205
            } catch (Exception exception){
34501 vikas.jang 206
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
207
                    bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
208
                    bid.setStatus(ProfitMandiConstants.BID_ENUM.PROCESSING);
34572 vikas.jang 209
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
210
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
34501 vikas.jang 211
                }
33338 amit.gupta 212
            }
34443 vikas.jang 213
 
33338 amit.gupta 214
            int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
33213 tejus.loha 215
            //Set here created by
216
            Transaction transaction = transactionRepository.selectById(transactionId);
217
            transaction.setCreatedBy(creatorId);
218
            LOGGER.info("transaction  created by {}", transaction.getCreatedBy());
33172 tejus.loha 219
            commonPaymentService.payThroughWallet(transactionId);
34501 vikas.jang 220
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
221
                bid.setStatus(ProfitMandiConstants.BID_ENUM.CLOSED);
222
            }
34443 vikas.jang 223
            if (approvalRequired) {
224
                this.createApproval(transactionId);
34566 ranu 225
                if (loanId > 0) {
226
                    LoanTransaction loanTransaction = new LoanTransaction();
227
                    loanTransaction.setLoanId(loanId);
228
                    loanTransaction.setTransactionId(transactionId);
229
                    loanTransactionRepository.persist(loanTransaction);
230
                }
34443 vikas.jang 231
            } else {
34312 ranu 232
                transactionService.processTransaction(transactionId,loanId);
33213 tejus.loha 233
            }
234
 
33172 tejus.loha 235
        }
236
    }
237
 
33213 tejus.loha 238
    public void createApproval(int transactionId) {
239
        TransactionApproval transactionApproval = new TransactionApproval();
240
        transactionApproval.setId(transactionId);
241
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
242
        transactionApprovalRepository.persist(transactionApproval);
243
    }
244
 
33172 tejus.loha 245
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
246
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
247
        int i = 0;
248
        bulkOrderModel.setRowIndex(row.getRowNum());
249
        try {
33696 amit.gupta 250
            Cell partnerName = row.getCell(i++);
251
            if (partnerName == null)
33213 tejus.loha 252
                bulkOrderModel.setPartnerName("");
253
            else
33696 amit.gupta 254
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 255
            Cell description = row.getCell(i++);
256
            if (description == null)
257
                bulkOrderModel.setDescription("");
258
            else
259
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
260
 
33172 tejus.loha 261
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
262
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 263
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 264
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
265
        } catch (Throwable e) {
266
            LOGGER.info(e.getCause());
33213 tejus.loha 267
            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 268
        }
269
        LOGGER.info(bulkOrderModel);
270
        return bulkOrderModel;
271
    }
272
 
33341 tejus.loha 273
    // create model for transaction Approval so that finance team see all order and approve
274
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
275
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
276
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
277
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
278
        for (TransactionApproval transactionApproval : transactionApprovals) {
279
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
280
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
281
            List<LineItemModel> lineItemModelList = new ArrayList<>();
282
            for (Order order : orderList) {
283
                LineItem lineItem = order.getLineItem();
284
                LineItemModel lineItemModel = new LineItemModel();
285
                lineItemModel.setItemId(lineItem.getItemId());
286
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
287
                lineItemModel.setItemQuantity(lineItem.getQuantity());
288
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
289
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
290
                lineItemModelList.add(lineItemModel);
291
            }
292
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
293
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
294
            String retailerName = " ";
295
            retailerName = orderList.get(0).getRetailerName();
296
            transactionApprovalModel.setRetailerName(retailerName);
297
            transactionApprovalModel.setCreatedBy(authUser.getFullName());
298
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
299
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
300
            transactionApprovalModel.setLineItemModels(lineItemModelList);
301
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 302
 
33341 tejus.loha 303
        }
304
        return approvalModelList;
305
    }
306
 
33172 tejus.loha 307
}