Subversion Repositories SmartDukaan

Rev

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