Subversion Repositories SmartDukaan

Rev

Rev 34468 | Rev 34501 | 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;
34443 vikas.jang 9
import com.spice.profitmandi.common.util.Utils;
33172 tejus.loha 10
import com.spice.profitmandi.dao.cart.CartService;
33341 tejus.loha 11
import com.spice.profitmandi.dao.entity.auth.AuthUser;
34443 vikas.jang 12
import com.spice.profitmandi.dao.entity.catalog.Bid;
13
import com.spice.profitmandi.dao.entity.catalog.Liquidation;
33172 tejus.loha 14
import com.spice.profitmandi.dao.entity.catalog.TagListing;
34443 vikas.jang 15
import com.spice.profitmandi.dao.entity.dtr.User;
34312 ranu 16
import com.spice.profitmandi.dao.entity.transaction.*;
34443 vikas.jang 17
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
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;
33341 tejus.loha 27
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 28
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 29
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
30
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
31
import com.spice.profitmandi.dao.repository.user.AddressRepository;
34468 vikas.jang 32
import com.spice.profitmandi.dao.service.BidService;
33
import com.spice.profitmandi.service.AuthService;
33338 amit.gupta 34
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 35
import com.spice.profitmandi.service.transaction.TransactionService;
36
import com.spice.profitmandi.service.wallet.CommonPaymentService;
37
import com.spice.profitmandi.service.wallet.WalletService;
38
import org.apache.logging.log4j.LogManager;
39
import org.apache.logging.log4j.Logger;
33213 tejus.loha 40
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 41
import org.apache.poi.ss.usermodel.Row;
42
import org.apache.poi.xssf.usermodel.XSSFRow;
43
import org.apache.poi.xssf.usermodel.XSSFSheet;
44
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
45
import org.springframework.beans.factory.annotation.Autowired;
34443 vikas.jang 46
import org.springframework.mail.javamail.JavaMailSender;
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;
34468 vikas.jang 52
import java.nio.charset.StandardCharsets;
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;
95
    @Autowired
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
 
34468 vikas.jang 121
    public void 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;
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
            }
34492 vikas.jang 169
            Bid bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
33338 amit.gupta 170
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 171
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 172
 
173
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
174
 
175
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 176
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 177
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 178
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34443 vikas.jang 179
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
180
                } else {
34468 vikas.jang 181
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
182
                        bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34492 vikas.jang 183
                        bid.setStatus(ProfitMandiConstants.BID_ENUM.PROCESSING);
34468 vikas.jang 184
                        throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
185
                    } else {
34492 vikas.jang 186
                        bidService.cancelYesterdayProcessBid(bid);
34468 vikas.jang 187
                        throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
188
                    }
34443 vikas.jang 189
                }
33172 tejus.loha 190
            }
191
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 192
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 193
 
33351 amit.gupta 194
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 195
            int loanId = 0;
34492 vikas.jang 196
            try {
197
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
198
                    Loan loan = sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 365, "Credit limit assigned via SD Credit");
199
                    loanId = loan.getId();
200
                }
201
            } catch (Exception exception){
202
                bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
203
                bid.setStatus(ProfitMandiConstants.BID_ENUM.PROCESSING);
204
                throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
33338 amit.gupta 205
            }
34443 vikas.jang 206
 
33338 amit.gupta 207
            int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
33213 tejus.loha 208
            //Set here created by
209
            Transaction transaction = transactionRepository.selectById(transactionId);
210
            transaction.setCreatedBy(creatorId);
211
            LOGGER.info("transaction  created by {}", transaction.getCreatedBy());
33172 tejus.loha 212
            commonPaymentService.payThroughWallet(transactionId);
34492 vikas.jang 213
            bid.setStatus(ProfitMandiConstants.BID_ENUM.CLOSED);
34443 vikas.jang 214
            if (approvalRequired) {
215
                this.createApproval(transactionId);
216
            } else {
34312 ranu 217
                transactionService.processTransaction(transactionId,loanId);
33213 tejus.loha 218
            }
219
 
33172 tejus.loha 220
        }
221
    }
222
 
33213 tejus.loha 223
    public void createApproval(int transactionId) {
224
        TransactionApproval transactionApproval = new TransactionApproval();
225
        transactionApproval.setId(transactionId);
226
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
227
        transactionApprovalRepository.persist(transactionApproval);
228
    }
229
 
33172 tejus.loha 230
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
231
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
232
        int i = 0;
233
        bulkOrderModel.setRowIndex(row.getRowNum());
234
        try {
33696 amit.gupta 235
            Cell partnerName = row.getCell(i++);
236
            if (partnerName == null)
33213 tejus.loha 237
                bulkOrderModel.setPartnerName("");
238
            else
33696 amit.gupta 239
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 240
            Cell description = row.getCell(i++);
241
            if (description == null)
242
                bulkOrderModel.setDescription("");
243
            else
244
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
245
 
33172 tejus.loha 246
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
247
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 248
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 249
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
250
        } catch (Throwable e) {
251
            LOGGER.info(e.getCause());
33213 tejus.loha 252
            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 253
        }
254
        LOGGER.info(bulkOrderModel);
255
        return bulkOrderModel;
256
    }
257
 
33341 tejus.loha 258
    // create model for transaction Approval so that finance team see all order and approve
259
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
260
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
261
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
262
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
263
        for (TransactionApproval transactionApproval : transactionApprovals) {
264
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
265
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
266
            List<LineItemModel> lineItemModelList = new ArrayList<>();
267
            for (Order order : orderList) {
268
                LineItem lineItem = order.getLineItem();
269
                LineItemModel lineItemModel = new LineItemModel();
270
                lineItemModel.setItemId(lineItem.getItemId());
271
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
272
                lineItemModel.setItemQuantity(lineItem.getQuantity());
273
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
274
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
275
                lineItemModelList.add(lineItemModel);
276
            }
277
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
278
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
279
            String retailerName = " ";
280
            retailerName = orderList.get(0).getRetailerName();
281
            transactionApprovalModel.setRetailerName(retailerName);
282
            transactionApprovalModel.setCreatedBy(authUser.getFullName());
283
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
284
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
285
            transactionApprovalModel.setLineItemModels(lineItemModelList);
286
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 287
 
33341 tejus.loha 288
        }
289
        return approvalModelList;
290
    }
291
 
33172 tejus.loha 292
}