Subversion Repositories SmartDukaan

Rev

Rev 33442 | Rev 33556 | 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());
33213 tejus.loha 126
                double itemSellingPrice = tagListing.getSellingPrice();
127
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
128
                int itemId = cartItem.getItemId();
129
                if (isPriceZero) {
130
                    cartItem.setSellingPrice(itemSellingPrice);
131
                } else {
33216 tejus.loha 132
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 133
                        cartItem.setSellingPrice(customSellingPrice);
134
                        approvalNotRequired = false;
135
 
136
                    } else {
137
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
138
                    }
139
 
140
                }
33338 amit.gupta 141
                totalPayableAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
33172 tejus.loha 142
                cartItems.add(cartItem);
143
            }
33338 amit.gupta 144
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 145
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 146
 
147
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
148
 
149
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 150
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 151
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
33442 tejus.loha 152
                throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
33172 tejus.loha 153
            }
154
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 155
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 156
 
33351 amit.gupta 157
            double creditAmountRequired = totalPayableAmount - walletAmount;
33547 tejus.loha 158
            if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
33338 amit.gupta 159
                sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 0);
160
            }
161
            //return this.createLoan(userCart.getUserId(), creditAmountRequired);
162
            int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
33213 tejus.loha 163
            //Set here created by
164
            Transaction transaction = transactionRepository.selectById(transactionId);
165
            transaction.setCreatedBy(creatorId);
166
            LOGGER.info("transaction  created by {}", transaction.getCreatedBy());
33172 tejus.loha 167
            commonPaymentService.payThroughWallet(transactionId);
33213 tejus.loha 168
            if (approvalNotRequired) {
169
                transactionService.processTransaction(transactionId);
170
            } else {
171
                this.createApproval(transactionId);
172
            }
173
 
33172 tejus.loha 174
        }
33213 tejus.loha 175
 
33172 tejus.loha 176
    }
177
 
33213 tejus.loha 178
    public void createApproval(int transactionId) {
179
        TransactionApproval transactionApproval = new TransactionApproval();
180
        transactionApproval.setId(transactionId);
181
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
182
        transactionApprovalRepository.persist(transactionApproval);
183
    }
184
 
33172 tejus.loha 185
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
186
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
187
        int i = 0;
188
        bulkOrderModel.setRowIndex(row.getRowNum());
189
        try {
33213 tejus.loha 190
            Cell partneranme = row.getCell(i++);
191
            if (partneranme == null)
192
                bulkOrderModel.setPartnerName("");
193
            else
194
                bulkOrderModel.setPartnerName(partneranme.getStringCellValue().trim());
195
            Cell description = row.getCell(i++);
196
            if (description == null)
197
                bulkOrderModel.setDescription("");
198
            else
199
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
200
 
33172 tejus.loha 201
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
202
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 203
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 204
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
205
        } catch (Throwable e) {
206
            LOGGER.info(e.getCause());
33213 tejus.loha 207
            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 208
        }
209
        LOGGER.info(bulkOrderModel);
210
        return bulkOrderModel;
211
    }
212
 
33341 tejus.loha 213
    // create model for transaction Approval so that finance team see all order and approve
214
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
215
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
216
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
217
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
218
        for (TransactionApproval transactionApproval : transactionApprovals) {
219
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
220
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
221
            List<LineItemModel> lineItemModelList = new ArrayList<>();
222
            for (Order order : orderList) {
223
                LineItem lineItem = order.getLineItem();
224
                LineItemModel lineItemModel = new LineItemModel();
225
                lineItemModel.setItemId(lineItem.getItemId());
226
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
227
                lineItemModel.setItemQuantity(lineItem.getQuantity());
228
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
229
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
230
                lineItemModelList.add(lineItemModel);
231
            }
232
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
233
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
234
            String retailerName = " ";
235
            retailerName = orderList.get(0).getRetailerName();
236
            transactionApprovalModel.setRetailerName(retailerName);
237
            transactionApprovalModel.setCreatedBy(authUser.getFullName());
238
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
239
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
240
            transactionApprovalModel.setLineItemModels(lineItemModelList);
241
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 242
 
33341 tejus.loha 243
        }
244
        return approvalModelList;
245
    }
246
 
247
 
33172 tejus.loha 248
}