Subversion Repositories SmartDukaan

Rev

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