Subversion Repositories SmartDukaan

Rev

Rev 35690 | Rev 35971 | 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;
34443 vikas.jang 11
import com.spice.profitmandi.dao.entity.catalog.Bid;
34832 ranu 12
import com.spice.profitmandi.dao.entity.catalog.Item;
33172 tejus.loha 13
import com.spice.profitmandi.dao.entity.catalog.TagListing;
34856 ranu 14
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
34566 ranu 15
import com.spice.profitmandi.dao.entity.fofo.LoanTransaction;
34674 aman.kumar 16
import com.spice.profitmandi.dao.entity.transaction.LineItem;
17
import com.spice.profitmandi.dao.entity.transaction.Order;
18
import com.spice.profitmandi.dao.entity.transaction.Transaction;
19
import com.spice.profitmandi.dao.entity.transaction.TransactionApproval;
33213 tejus.loha 20
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
33172 tejus.loha 21
import com.spice.profitmandi.dao.model.CartItem;
22
import com.spice.profitmandi.dao.model.UserCart;
33341 tejus.loha 23
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
34468 vikas.jang 24
import com.spice.profitmandi.dao.repository.catalog.BidRepository;
34832 ranu 25
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
34468 vikas.jang 26
import com.spice.profitmandi.dao.repository.catalog.LiquidationRepository;
33172 tejus.loha 27
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
34443 vikas.jang 28
import com.spice.profitmandi.dao.repository.cs.CsService;
34856 ranu 29
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
33172 tejus.loha 30
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
34566 ranu 31
import com.spice.profitmandi.dao.repository.fofo.LoanTransactionRepository;
33341 tejus.loha 32
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 33
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 34
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
35
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
36
import com.spice.profitmandi.dao.repository.user.AddressRepository;
34468 vikas.jang 37
import com.spice.profitmandi.dao.service.BidService;
34832 ranu 38
import com.spice.profitmandi.service.catalog.BrandsService;
34661 ranu 39
import com.spice.profitmandi.service.transaction.BlockLoanIdSanctionId;
33338 amit.gupta 40
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 41
import com.spice.profitmandi.service.transaction.TransactionService;
42
import com.spice.profitmandi.service.wallet.CommonPaymentService;
43
import com.spice.profitmandi.service.wallet.WalletService;
44
import org.apache.logging.log4j.LogManager;
45
import org.apache.logging.log4j.Logger;
33213 tejus.loha 46
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 47
import org.apache.poi.ss.usermodel.Row;
48
import org.apache.poi.xssf.usermodel.XSSFRow;
49
import org.apache.poi.xssf.usermodel.XSSFSheet;
50
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
51
import org.springframework.beans.factory.annotation.Autowired;
33213 tejus.loha 52
import org.springframework.stereotype.Service;
53
import org.springframework.transaction.annotation.Transactional;
33172 tejus.loha 54
import org.springframework.web.multipart.MultipartFile;
55
 
33338 amit.gupta 56
import java.math.BigDecimal;
35956 amit 57
import java.time.LocalDateTime;
33172 tejus.loha 58
import java.util.ArrayList;
59
import java.util.List;
60
import java.util.Map;
35690 amit 61
import java.util.Set;
33172 tejus.loha 62
import java.util.stream.Collectors;
63
 
33213 tejus.loha 64
@Service
33172 tejus.loha 65
public class BulkOrderService {
66
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
67
    @Autowired
68
    CartService cartService;
69
    @Autowired
70
    TransactionService transactionService;
71
    @Autowired
72
    CommonPaymentService commonPaymentService;
73
    @Autowired
74
    TagListingRepository tagListingRepository;
75
    @Autowired
76
    WalletService walletService;
77
    @Autowired
78
    UserRepository userRepository;
33213 tejus.loha 79
    @Autowired
80
    TransactionRepository transactionRepository;
81
    @Autowired
82
    TransactionApprovalRepository transactionApprovalRepository;
83
    @Autowired
84
    AddressRepository addressRepository;
33341 tejus.loha 85
    @Autowired
86
    OrderRepository orderRepository;
34443 vikas.jang 87
    //TODO:Tejus need to check
33341 tejus.loha 88
    @Autowired
89
    SDCreditRequirementRepository sdCreditRequirementRepository;
33338 amit.gupta 90
    @Autowired
91
    SDCreditService sdCreditService;
34443 vikas.jang 92
    @Autowired
93
    private CsService csService;
94
    @Autowired
34468 vikas.jang 95
    private AuthRepository authRepository;
34443 vikas.jang 96
    @Autowired
34468 vikas.jang 97
    private BidRepository bidRepository;
98
    @Autowired
99
    private BidService bidService;
100
    @Autowired
34832 ranu 101
    ItemRepository itemRepository;
102
    @Autowired
103
    private BrandsService brandsService;
104
    @Autowired
34566 ranu 105
    private LoanTransactionRepository loanTransactionRepository;
106
 
107
    @Autowired
34468 vikas.jang 108
    private LiquidationRepository liquidationRepository;
33338 amit.gupta 109
 
34674 aman.kumar 110
    @Autowired
111
    com.spice.profitmandi.dao.repository.user.UserRepository user_userRepository;
33338 amit.gupta 112
 
34856 ranu 113
    @Autowired
114
    FofoStoreRepository fofoStoreRepository;
34674 aman.kumar 115
 
34856 ranu 116
 
34468 vikas.jang 117
    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception {
33172 tejus.loha 118
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
119
 
120
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
121
        // Return first sheet from the XLSX workbook
122
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
123
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
124
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
33547 tejus.loha 125
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
33172 tejus.loha 126
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
127
            XSSFRow row = mySheet.getRow(rowNumber);
33547 tejus.loha 128
            LOGGER.info("Row - {}", row);
129
            if (row != null) {
130
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
131
                bulkOrderModels.add(bulkOrderModel);
132
            } else {
133
                break;
134
            }
33172 tejus.loha 135
        }
34468 vikas.jang 136
        this.generatePurchaseOrder(bulkOrderModels, creatorId, ProfitMandiConstants.PO_TYPE.MANUAL, ProfitMandiConstants.BID_CRON_ENUM.TODAY);
34443 vikas.jang 137
    }
138
 
34592 vikas.jang 139
    public ProfitMandiConstants.BID_ENUM generatePurchaseOrder(List<BulkOrderModel> bulkOrderModels, int creatorId, ProfitMandiConstants.PO_TYPE type, ProfitMandiConstants.BID_CRON_ENUM scheduleType) throws Exception {
33172 tejus.loha 140
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
34443 vikas.jang 141
        boolean approvalRequired = false;
34592 vikas.jang 142
        ProfitMandiConstants.BID_ENUM finalBidStatus = ProfitMandiConstants.BID_ENUM.CLOSED;
33172 tejus.loha 143
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
144
            int fofoId = fofoBulkOrderEntry.getKey();
145
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
146
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
147
 
148
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
149
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
150
            }
151
 
152
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
153
            if (hasZeroQuantity) {
154
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
155
            }
156
 
35690 amit 157
            // Batch-fetch per-fofo data once (instead of per-item)
158
            FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
159
            List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
160
 
161
            // Batch-fetch items and tag listings for all items in this fofo's order (2 queries instead of 2N)
162
            Set<Integer> allItemIds = fofoBulkOrderModels.stream().map(BulkOrderModel::getItemId).collect(Collectors.toSet());
163
            Map<Integer, TagListing> tagListingMap = tagListingRepository.selectByItemIds(allItemIds);
164
            Map<Integer, Item> itemMap = itemRepository.selectByIds(allItemIds).stream()
165
                    .collect(Collectors.toMap(Item::getId, item -> item));
166
 
33172 tejus.loha 167
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 168
            double totalPayableAmount = 0;
34957 amit 169
            BigDecimal totalPayableAmountBD = new BigDecimal(0);
33172 tejus.loha 170
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
171
                CartItem cartItem = new CartItem();
172
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
173
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
35690 amit 174
                TagListing tagListing = tagListingMap.get(fofoBulkOrderModel.getItemId());
33556 amit.gupta 175
                if (tagListing == null) {
176
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
177
                    throw new ProfitMandiBusinessException(message, message, message);
178
                }
35690 amit 179
                Item item = itemMap.get(fofoBulkOrderModel.getItemId());
180
                if (item == null) {
181
                    throw new ProfitMandiBusinessException("Item not found", fofoBulkOrderModel.getItemId(), "Item does not exist: " + fofoBulkOrderModel.getItemId());
182
                }
34856 ranu 183
                if (!fofoStore.isInternal()) {
184
                    if (partnerIneligibleBrands.contains(item.getBrand())) {
185
                        throw new ProfitMandiBusinessException("Brand is not allowed", "Brand ( " + item.getBrand() + ") is not allowed for this partner", "");
186
                    }
34832 ranu 187
                }
188
 
33213 tejus.loha 189
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 190
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
191
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 192
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
193
                int itemId = cartItem.getItemId();
33597 tejus.loha 194
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 195
                    cartItem.setSellingPrice(itemSellingPrice);
196
                } else {
33216 tejus.loha 197
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 198
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 199
                        approvalRequired = true;
33213 tejus.loha 200
 
201
                    } else {
202
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
203
                    }
204
 
205
                }
34958 amit 206
                totalPayableAmountBD = totalPayableAmountBD.add(new BigDecimal(String.valueOf(cartItem.getSellingPrice())).multiply(new BigDecimal(cartItem.getQuantity())));
33172 tejus.loha 207
                cartItems.add(cartItem);
208
            }
34957 amit 209
            totalPayableAmount = totalPayableAmountBD.doubleValue();
34501 vikas.jang 210
            Bid bid = null;
211
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
212
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
34592 vikas.jang 213
                approvalRequired = false;
34957 amit 214
                totalPayableAmount = totalPayableAmountBD.doubleValue() - ProfitMandiConstants.BID_CHARGES;
34501 vikas.jang 215
            }
33338 amit.gupta 216
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 217
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 218
 
219
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
220
 
221
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 222
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 223
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 224
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34695 aman.kumar 225
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, String.valueOf(fofoId));
34443 vikas.jang 226
                } else {
34468 vikas.jang 227
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
34592 vikas.jang 228
                        finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 229
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
230
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
34468 vikas.jang 231
                    } else {
34592 vikas.jang 232
                        finalBidStatus = bidService.cancelYesterdayProcessBid(bid);
34572 vikas.jang 233
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
234
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
34468 vikas.jang 235
                    }
34443 vikas.jang 236
                }
33172 tejus.loha 237
            }
238
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 239
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 240
 
33351 amit.gupta 241
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 242
            int loanId = 0;
34492 vikas.jang 243
            try {
244
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34576 vikas.jang 245
                    LOGGER.info("Creating new loan for: {}",userCart.getUserId());
34675 aman.kumar 246
                    BlockLoanIdSanctionId loan = sdCreditService.createSDDirectOrder(userCart.getUserId(), totalPayableAmount, 0);
34661 ranu 247
                    loanId = loan.getLoanId();
34492 vikas.jang 248
                }
249
            } catch (Exception exception){
34501 vikas.jang 250
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
34592 vikas.jang 251
                    finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 252
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
253
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
34501 vikas.jang 254
                }
33338 amit.gupta 255
            }
34443 vikas.jang 256
 
34576 vikas.jang 257
            LOGGER.info("finalBidStatus: {}",finalBidStatus);
34573 vikas.jang 258
            if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {
34959 amit 259
                LOGGER.info("totalPayableAmount - {}", totalPayableAmount);
34573 vikas.jang 260
                int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
261
                //Set here created by
262
                Transaction transaction = transactionRepository.selectById(transactionId);
263
                transaction.setCreatedBy(creatorId);
34637 vikas.jang 264
                LOGGER.info("transaction created by {}", transaction.getCreatedBy());
34573 vikas.jang 265
                commonPaymentService.payThroughWallet(transactionId);
266
                if (approvalRequired) {
267
                    this.createApproval(transactionId);
268
                    if (loanId > 0) {
269
                        LoanTransaction loanTransaction = new LoanTransaction();
270
                        loanTransaction.setLoanId(loanId);
271
                        loanTransaction.setTransactionId(transactionId);
272
                        loanTransactionRepository.persist(loanTransaction);
273
                    }
274
                } else {
275
                    transactionService.processTransaction(transactionId, loanId);
276
                }
33213 tejus.loha 277
            }
278
 
33172 tejus.loha 279
        }
34592 vikas.jang 280
        return finalBidStatus;
33172 tejus.loha 281
    }
282
 
33213 tejus.loha 283
    public void createApproval(int transactionId) {
284
        TransactionApproval transactionApproval = new TransactionApproval();
285
        transactionApproval.setId(transactionId);
286
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
287
        transactionApprovalRepository.persist(transactionApproval);
288
    }
289
 
33172 tejus.loha 290
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
291
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
292
        int i = 0;
293
        bulkOrderModel.setRowIndex(row.getRowNum());
294
        try {
33696 amit.gupta 295
            Cell partnerName = row.getCell(i++);
296
            if (partnerName == null)
33213 tejus.loha 297
                bulkOrderModel.setPartnerName("");
298
            else
33696 amit.gupta 299
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 300
            Cell description = row.getCell(i++);
301
            if (description == null)
302
                bulkOrderModel.setDescription("");
303
            else
304
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
305
 
33172 tejus.loha 306
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
307
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 308
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 309
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
310
        } catch (Throwable e) {
311
            LOGGER.info(e.getCause());
33213 tejus.loha 312
            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 313
        }
314
        LOGGER.info(bulkOrderModel);
315
        return bulkOrderModel;
316
    }
317
 
33341 tejus.loha 318
    // create model for transaction Approval so that finance team see all order and approve
319
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
320
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
321
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
322
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
323
        for (TransactionApproval transactionApproval : transactionApprovals) {
324
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
325
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
326
            List<LineItemModel> lineItemModelList = new ArrayList<>();
327
            for (Order order : orderList) {
328
                LineItem lineItem = order.getLineItem();
329
                LineItemModel lineItemModel = new LineItemModel();
330
                lineItemModel.setItemId(lineItem.getItemId());
331
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
332
                lineItemModel.setItemQuantity(lineItem.getQuantity());
333
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
334
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
335
                lineItemModelList.add(lineItemModel);
336
            }
337
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
338
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
339
            String retailerName = " ";
340
            retailerName = orderList.get(0).getRetailerName();
341
            transactionApprovalModel.setRetailerName(retailerName);
34573 vikas.jang 342
            if (authUser == null) {
343
                transactionApprovalModel.setCreatedBy(retailerName);
344
            } else {
345
                transactionApprovalModel.setCreatedBy(authUser.getFullName());
346
            }
33341 tejus.loha 347
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
348
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
349
            transactionApprovalModel.setLineItemModels(lineItemModelList);
350
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 351
 
33341 tejus.loha 352
        }
353
        return approvalModelList;
354
    }
355
 
35956 amit 356
    public List<TransactionApprovalModel> getBulkOrderApprovalReport(LocalDateTime startDate, LocalDateTime endDate) throws ProfitMandiBusinessException {
357
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllByDateRange(startDate, endDate);
358
        LOGGER.info("Approval report: found {} records", transactionApprovals.size());
359
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
360
        for (TransactionApproval transactionApproval : transactionApprovals) {
361
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
362
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
363
            List<LineItemModel> lineItemModelList = new ArrayList<>();
364
            for (Order order : orderList) {
365
                LineItem lineItem = order.getLineItem();
366
                LineItemModel lineItemModel = new LineItemModel();
367
                lineItemModel.setItemId(lineItem.getItemId());
368
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
369
                lineItemModel.setItemQuantity(lineItem.getQuantity());
370
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
371
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
372
                lineItemModelList.add(lineItemModel);
373
            }
374
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
375
            TransactionApprovalModel model = new TransactionApprovalModel();
376
            String retailerName = orderList.isEmpty() ? "" : orderList.get(0).getRetailerName();
377
            model.setRetailerName(retailerName);
378
            if (authUser == null) {
379
                model.setCreatedBy(retailerName);
380
            } else {
381
                model.setCreatedBy(authUser.getFullName());
382
            }
383
            model.setCreatedOn(transaction.getCreateTimestamp());
384
            model.setTransactionId(transactionApproval.getId());
385
            model.setLineItemModels(lineItemModelList);
386
            model.setStatus(transactionApproval.getStatus().name());
387
            model.setApprovedBy(transactionApproval.getApprovedBy());
388
            model.setApprovedOn(transactionApproval.getApprovedOn());
389
            model.setRemark(transactionApproval.getRemark());
390
            approvalModelList.add(model);
391
        }
392
        return approvalModelList;
393
    }
394
 
33172 tejus.loha 395
}