Subversion Repositories SmartDukaan

Rev

Rev 34443 | Rev 34492 | 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
            }
33338 amit.gupta 169
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 170
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 171
 
172
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
173
 
174
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 175
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 176
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 177
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34443 vikas.jang 178
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
179
                } else {
34468 vikas.jang 180
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
181
                        bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
182
                        throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
183
                    } else {
184
                        bidService.cancelYesterdayProcessBid(fofoBulkOrderModels.get(0).getRowIndex());
185
                        throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
186
                    }
34443 vikas.jang 187
                }
33172 tejus.loha 188
            }
189
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 190
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 191
 
33351 amit.gupta 192
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 193
            int loanId = 0;
33547 tejus.loha 194
            if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34312 ranu 195
                Loan loan = sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 365, "Credit limit assigned via SD Credit");
196
                loanId = loan.getId();
33338 amit.gupta 197
            }
34443 vikas.jang 198
 
33338 amit.gupta 199
            int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
33213 tejus.loha 200
            //Set here created by
201
            Transaction transaction = transactionRepository.selectById(transactionId);
202
            transaction.setCreatedBy(creatorId);
203
            LOGGER.info("transaction  created by {}", transaction.getCreatedBy());
33172 tejus.loha 204
            commonPaymentService.payThroughWallet(transactionId);
34443 vikas.jang 205
            if (approvalRequired) {
206
                this.createApproval(transactionId);
207
            } else {
34312 ranu 208
                transactionService.processTransaction(transactionId,loanId);
33213 tejus.loha 209
            }
210
 
33172 tejus.loha 211
        }
212
    }
213
 
33213 tejus.loha 214
    public void createApproval(int transactionId) {
215
        TransactionApproval transactionApproval = new TransactionApproval();
216
        transactionApproval.setId(transactionId);
217
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
218
        transactionApprovalRepository.persist(transactionApproval);
219
    }
220
 
33172 tejus.loha 221
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
222
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
223
        int i = 0;
224
        bulkOrderModel.setRowIndex(row.getRowNum());
225
        try {
33696 amit.gupta 226
            Cell partnerName = row.getCell(i++);
227
            if (partnerName == null)
33213 tejus.loha 228
                bulkOrderModel.setPartnerName("");
229
            else
33696 amit.gupta 230
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 231
            Cell description = row.getCell(i++);
232
            if (description == null)
233
                bulkOrderModel.setDescription("");
234
            else
235
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
236
 
33172 tejus.loha 237
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
238
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 239
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 240
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
241
        } catch (Throwable e) {
242
            LOGGER.info(e.getCause());
33213 tejus.loha 243
            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 244
        }
245
        LOGGER.info(bulkOrderModel);
246
        return bulkOrderModel;
247
    }
248
 
33341 tejus.loha 249
    // create model for transaction Approval so that finance team see all order and approve
250
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
251
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
252
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
253
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
254
        for (TransactionApproval transactionApproval : transactionApprovals) {
255
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
256
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
257
            List<LineItemModel> lineItemModelList = new ArrayList<>();
258
            for (Order order : orderList) {
259
                LineItem lineItem = order.getLineItem();
260
                LineItemModel lineItemModel = new LineItemModel();
261
                lineItemModel.setItemId(lineItem.getItemId());
262
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
263
                lineItemModel.setItemQuantity(lineItem.getQuantity());
264
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
265
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
266
                lineItemModelList.add(lineItemModel);
267
            }
268
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
269
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
270
            String retailerName = " ";
271
            retailerName = orderList.get(0).getRetailerName();
272
            transactionApprovalModel.setRetailerName(retailerName);
273
            transactionApprovalModel.setCreatedBy(authUser.getFullName());
274
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
275
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
276
            transactionApprovalModel.setLineItemModels(lineItemModelList);
277
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 278
 
33341 tejus.loha 279
        }
280
        return approvalModelList;
281
    }
282
 
33172 tejus.loha 283
}