Subversion Repositories SmartDukaan

Rev

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