Subversion Repositories SmartDukaan

Rev

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