Subversion Repositories SmartDukaan

Rev

Rev 33547 | Rev 33597 | 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;
33172 tejus.loha 11
import com.spice.profitmandi.dao.entity.catalog.TagListing;
33341 tejus.loha 12
import com.spice.profitmandi.dao.entity.transaction.LineItem;
13
import com.spice.profitmandi.dao.entity.transaction.Order;
33213 tejus.loha 14
import com.spice.profitmandi.dao.entity.transaction.Transaction;
15
import com.spice.profitmandi.dao.entity.transaction.TransactionApproval;
16
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
33172 tejus.loha 17
import com.spice.profitmandi.dao.model.CartItem;
18
import com.spice.profitmandi.dao.model.UserCart;
33341 tejus.loha 19
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
33172 tejus.loha 20
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
21
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
33341 tejus.loha 22
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 23
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 24
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
25
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
26
import com.spice.profitmandi.dao.repository.user.AddressRepository;
33338 amit.gupta 27
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 28
import com.spice.profitmandi.service.transaction.TransactionService;
29
import com.spice.profitmandi.service.wallet.CommonPaymentService;
30
import com.spice.profitmandi.service.wallet.WalletService;
31
import org.apache.logging.log4j.LogManager;
32
import org.apache.logging.log4j.Logger;
33213 tejus.loha 33
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 34
import org.apache.poi.ss.usermodel.Row;
35
import org.apache.poi.xssf.usermodel.XSSFRow;
36
import org.apache.poi.xssf.usermodel.XSSFSheet;
37
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
38
import org.springframework.beans.factory.annotation.Autowired;
33213 tejus.loha 39
import org.springframework.stereotype.Service;
40
import org.springframework.transaction.annotation.Transactional;
33172 tejus.loha 41
import org.springframework.web.multipart.MultipartFile;
42
 
33338 amit.gupta 43
import java.math.BigDecimal;
33172 tejus.loha 44
import java.util.ArrayList;
45
import java.util.List;
46
import java.util.Map;
47
import java.util.stream.Collectors;
48
 
33213 tejus.loha 49
@Service
50
@Transactional(rollbackFor = Throwable.class)
33172 tejus.loha 51
public class BulkOrderService {
52
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
53
    @Autowired
54
    CartService cartService;
55
    @Autowired
56
    TransactionService transactionService;
57
    @Autowired
58
    CommonPaymentService commonPaymentService;
59
    @Autowired
60
    TagListingRepository tagListingRepository;
61
    @Autowired
62
    WalletService walletService;
63
    @Autowired
64
    UserRepository userRepository;
33213 tejus.loha 65
    @Autowired
66
    TransactionRepository transactionRepository;
67
    @Autowired
68
    TransactionApprovalRepository transactionApprovalRepository;
69
    @Autowired
70
    AddressRepository addressRepository;
33341 tejus.loha 71
    @Autowired
72
    OrderRepository orderRepository;
73
    @Autowired
74
    AuthRepository authRepository;
75
    @Autowired
76
    SDCreditRequirementRepository sdCreditRequirementRepository;
33213 tejus.loha 77
    //TODO:Tejus need to check
33172 tejus.loha 78
 
33338 amit.gupta 79
    @Autowired
80
    SDCreditService sdCreditService;
81
 
82
 
33213 tejus.loha 83
    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception {
33172 tejus.loha 84
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
85
 
86
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
87
        // Return first sheet from the XLSX workbook
88
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
89
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
90
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
33547 tejus.loha 91
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
33172 tejus.loha 92
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
93
            XSSFRow row = mySheet.getRow(rowNumber);
33547 tejus.loha 94
            LOGGER.info("Row - {}", row);
95
            if (row != null) {
96
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
97
                bulkOrderModels.add(bulkOrderModel);
98
            } else {
99
                break;
100
            }
33172 tejus.loha 101
        }
102
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
33213 tejus.loha 103
        boolean approvalNotRequired = true;
33172 tejus.loha 104
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
105
            int fofoId = fofoBulkOrderEntry.getKey();
106
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
107
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
108
 
109
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
110
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
111
            }
112
 
113
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
114
            if (hasZeroQuantity) {
115
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
116
            }
117
 
118
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 119
            double totalPayableAmount = 0;
33172 tejus.loha 120
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
121
                CartItem cartItem = new CartItem();
122
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
123
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
33341 tejus.loha 124
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33172 tejus.loha 125
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
33556 amit.gupta 126
                if (tagListing == null) {
127
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
128
                    throw new ProfitMandiBusinessException(message, message, message);
129
                }
33213 tejus.loha 130
                double itemSellingPrice = tagListing.getSellingPrice();
131
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
132
                int itemId = cartItem.getItemId();
133
                if (isPriceZero) {
134
                    cartItem.setSellingPrice(itemSellingPrice);
135
                } else {
33216 tejus.loha 136
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 137
                        cartItem.setSellingPrice(customSellingPrice);
138
                        approvalNotRequired = false;
139
 
140
                    } else {
141
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
142
                    }
143
 
144
                }
33338 amit.gupta 145
                totalPayableAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
33172 tejus.loha 146
                cartItems.add(cartItem);
147
            }
33338 amit.gupta 148
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 149
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 150
 
151
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
152
 
153
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 154
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 155
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
33442 tejus.loha 156
                throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
33172 tejus.loha 157
            }
158
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 159
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 160
 
33351 amit.gupta 161
            double creditAmountRequired = totalPayableAmount - walletAmount;
33547 tejus.loha 162
            if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
33338 amit.gupta 163
                sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 0);
164
            }
165
            //return this.createLoan(userCart.getUserId(), creditAmountRequired);
166
            int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
33213 tejus.loha 167
            //Set here created by
168
            Transaction transaction = transactionRepository.selectById(transactionId);
169
            transaction.setCreatedBy(creatorId);
170
            LOGGER.info("transaction  created by {}", transaction.getCreatedBy());
33172 tejus.loha 171
            commonPaymentService.payThroughWallet(transactionId);
33213 tejus.loha 172
            if (approvalNotRequired) {
173
                transactionService.processTransaction(transactionId);
174
            } else {
175
                this.createApproval(transactionId);
176
            }
177
 
33172 tejus.loha 178
        }
33213 tejus.loha 179
 
33172 tejus.loha 180
    }
181
 
33213 tejus.loha 182
    public void createApproval(int transactionId) {
183
        TransactionApproval transactionApproval = new TransactionApproval();
184
        transactionApproval.setId(transactionId);
185
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
186
        transactionApprovalRepository.persist(transactionApproval);
187
    }
188
 
33172 tejus.loha 189
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
190
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
191
        int i = 0;
192
        bulkOrderModel.setRowIndex(row.getRowNum());
193
        try {
33213 tejus.loha 194
            Cell partneranme = row.getCell(i++);
195
            if (partneranme == null)
196
                bulkOrderModel.setPartnerName("");
197
            else
198
                bulkOrderModel.setPartnerName(partneranme.getStringCellValue().trim());
199
            Cell description = row.getCell(i++);
200
            if (description == null)
201
                bulkOrderModel.setDescription("");
202
            else
203
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
204
 
33172 tejus.loha 205
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
206
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 207
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 208
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
209
        } catch (Throwable e) {
210
            LOGGER.info(e.getCause());
33213 tejus.loha 211
            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 212
        }
213
        LOGGER.info(bulkOrderModel);
214
        return bulkOrderModel;
215
    }
216
 
33341 tejus.loha 217
    // create model for transaction Approval so that finance team see all order and approve
218
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
219
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
220
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
221
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
222
        for (TransactionApproval transactionApproval : transactionApprovals) {
223
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
224
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
225
            List<LineItemModel> lineItemModelList = new ArrayList<>();
226
            for (Order order : orderList) {
227
                LineItem lineItem = order.getLineItem();
228
                LineItemModel lineItemModel = new LineItemModel();
229
                lineItemModel.setItemId(lineItem.getItemId());
230
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
231
                lineItemModel.setItemQuantity(lineItem.getQuantity());
232
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
233
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
234
                lineItemModelList.add(lineItemModel);
235
            }
236
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
237
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
238
            String retailerName = " ";
239
            retailerName = orderList.get(0).getRetailerName();
240
            transactionApprovalModel.setRetailerName(retailerName);
241
            transactionApprovalModel.setCreatedBy(authUser.getFullName());
242
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
243
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
244
            transactionApprovalModel.setLineItemModels(lineItemModelList);
245
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 246
 
33341 tejus.loha 247
        }
248
        return approvalModelList;
249
    }
250
 
251
 
33172 tejus.loha 252
}