Search in sources :

Example 71 with PurchaseOrder

use of com.axelor.apps.purchase.db.PurchaseOrder in project axelor-open-suite by axelor.

the class PurchaseRequestController method generatePo.

public void generatePo(ActionRequest request, ActionResponse response) {
    @SuppressWarnings("unchecked") List<Long> requestIds = (List<Long>) request.getContext().get("_ids");
    if (requestIds != null && !requestIds.isEmpty()) {
        Boolean groupBySupplier = (Boolean) request.getContext().get("groupBySupplier");
        groupBySupplier = groupBySupplier == null ? false : groupBySupplier;
        Boolean groupByProduct = (Boolean) request.getContext().get("groupByProduct");
        groupByProduct = groupByProduct == null ? false : groupByProduct;
        try {
            List<PurchaseRequest> purchaseRequests = Beans.get(PurchaseRequestRepository.class).all().filter("self.id in (?1)", requestIds).fetch();
            List<String> purchaseRequestSeqs = purchaseRequests.stream().filter(pr -> pr.getSupplierUser() == null).map(PurchaseRequest::getPurchaseRequestSeq).collect(Collectors.toList());
            if (purchaseRequestSeqs != null && !purchaseRequestSeqs.isEmpty()) {
                throw new AxelorException(TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, I18n.get(IExceptionMessage.PURCHASE_REQUEST_MISSING_SUPPLIER_USER), purchaseRequestSeqs.toString());
            }
            response.setCanClose(true);
            List<PurchaseOrder> purchaseOrderList = Beans.get(PurchaseRequestService.class).generatePo(purchaseRequests, groupBySupplier, groupByProduct);
            ActionViewBuilder actionViewBuilder = ActionView.define(String.format("Purchase Order%s generated", (purchaseOrderList.size() > 1 ? "s" : ""))).model(PurchaseOrder.class.getName()).add("grid", "purchase-order-quotation-grid").add("form", "purchase-order-form").param("search-filters", "purchase-order-filters").context("_showSingle", true).domain(String.format("self.id in (%s)", StringTool.getIdListString(purchaseOrderList)));
            response.setView(actionViewBuilder.map());
        } catch (AxelorException e) {
            response.setFlash(e.getMessage());
        }
    }
}
Also used : AxelorException(com.axelor.exception.AxelorException) ActionViewBuilder(com.axelor.meta.schema.actions.ActionView.ActionViewBuilder) PurchaseRequestService(com.axelor.apps.purchase.service.PurchaseRequestService) PurchaseRequestRepository(com.axelor.apps.purchase.db.repo.PurchaseRequestRepository) PurchaseOrder(com.axelor.apps.purchase.db.PurchaseOrder) List(java.util.List) PurchaseRequest(com.axelor.apps.purchase.db.PurchaseRequest)

Example 72 with PurchaseOrder

use of com.axelor.apps.purchase.db.PurchaseOrder in project axelor-open-suite by axelor.

the class StockMoveServiceSupplychainImpl method realize.

@Override
@Transactional(rollbackOn = { Exception.class })
public String realize(StockMove stockMove, boolean check) throws AxelorException {
    if (!Beans.get(AppSupplychainService.class).isApp("supplychain")) {
        return super.realize(stockMove, check);
    }
    LOG.debug("RĂ©alisation du mouvement de stock : {} ", stockMove.getStockMoveSeq());
    String newStockSeq = super.realize(stockMove, check);
    AppSupplychain appSupplychain = appSupplyChainService.getAppSupplychain();
    if (StockMoveRepository.ORIGIN_SALE_ORDER.equals(stockMove.getOriginTypeSelect())) {
        updateSaleOrderLinesDeliveryState(stockMove, !stockMove.getIsReversion());
        // Update linked saleOrder delivery state depending on BackOrder's existence
        SaleOrder saleOrder = saleOrderRepo.find(stockMove.getOriginId());
        if (newStockSeq != null) {
            saleOrder.setDeliveryState(SaleOrderRepository.DELIVERY_STATE_PARTIALLY_DELIVERED);
        } else {
            Beans.get(SaleOrderStockService.class).updateDeliveryState(saleOrder);
            if (appSupplychain.getTerminateSaleOrderOnDelivery()) {
                terminateOrConfirmSaleOrderStatus(saleOrder);
            }
        }
        Beans.get(SaleOrderRepository.class).save(saleOrder);
    } else if (StockMoveRepository.ORIGIN_PURCHASE_ORDER.equals(stockMove.getOriginTypeSelect())) {
        updatePurchaseOrderLines(stockMove, !stockMove.getIsReversion());
        // Update linked purchaseOrder receipt state depending on BackOrder's existence
        PurchaseOrder purchaseOrder = purchaseOrderRepo.find(stockMove.getOriginId());
        if (newStockSeq != null) {
            purchaseOrder.setReceiptState(PurchaseOrderRepository.STATE_PARTIALLY_RECEIVED);
        } else {
            Beans.get(PurchaseOrderStockService.class).updateReceiptState(purchaseOrder);
            if (appSupplychain.getTerminatePurchaseOrderOnReceipt()) {
                finishOrValidatePurchaseOrderStatus(purchaseOrder);
            }
        }
        Beans.get(PurchaseOrderRepository.class).save(purchaseOrder);
    }
    if (appSupplyChainService.getAppSupplychain().getManageStockReservation()) {
        Beans.get(ReservedQtyService.class).updateReservedQuantity(stockMove, StockMoveRepository.STATUS_REALIZED);
    }
    detachNonDeliveredStockMoveLines(stockMove);
    List<Long> trackingNumberIds = stockMove.getStockMoveLineList().stream().map(StockMoveLine::getTrackingNumber).filter(Objects::nonNull).map(TrackingNumber::getId).filter(Objects::nonNull).collect(Collectors.toList());
    if (CollectionUtils.isNotEmpty(trackingNumberIds)) {
        Query update = JPA.em().createQuery("UPDATE FixedAsset self SET self.stockLocation = :stockLocation WHERE self.trackingNumber.id IN (:trackingNumber)");
        update.setParameter("stockLocation", stockMove.getToStockLocation());
        update.setParameter("trackingNumber", trackingNumberIds);
        update.executeUpdate();
    }
    return newStockSeq;
}
Also used : AppSupplychain(com.axelor.apps.base.db.AppSupplychain) TrackingNumber(com.axelor.apps.stock.db.TrackingNumber) Query(javax.persistence.Query) SaleOrderRepository(com.axelor.apps.sale.db.repo.SaleOrderRepository) PurchaseOrder(com.axelor.apps.purchase.db.PurchaseOrder) StockMoveLine(com.axelor.apps.stock.db.StockMoveLine) SaleOrder(com.axelor.apps.sale.db.SaleOrder) Transactional(com.google.inject.persist.Transactional)

Example 73 with PurchaseOrder

use of com.axelor.apps.purchase.db.PurchaseOrder in project axelor-open-suite by axelor.

the class WorkflowCancelServiceSupplychainImpl method purchaseOrderProcess.

public void purchaseOrderProcess(Invoice invoice) throws AxelorException {
    PurchaseOrder invoicePurchaseOrder = invoice.getPurchaseOrder();
    if (invoicePurchaseOrder != null) {
        log.debug("Update the invoiced amount of the purchase order : {}", invoicePurchaseOrder.getPurchaseOrderSeq());
        invoicePurchaseOrder.setAmountInvoiced(purchaseOrderInvoiceService.getInvoicedAmount(invoicePurchaseOrder, invoice.getId(), true));
    } else {
        // Get all different purchaseOrders from invoice
        List<PurchaseOrder> purchaseOrderList = Lists.newArrayList();
        ;
        for (InvoiceLine invoiceLine : invoice.getInvoiceLineList()) {
            PurchaseOrder purchaseOrder = this.purchaseOrderLineProcess(invoice, invoiceLine);
            if (purchaseOrder != null && !purchaseOrderList.contains(purchaseOrder)) {
                purchaseOrderList.add(purchaseOrder);
            }
        }
        for (PurchaseOrder purchaseOrder : purchaseOrderList) {
            log.debug("Update the invoiced amount of the purchase order : {}", purchaseOrder.getPurchaseOrderSeq());
            purchaseOrder.setAmountInvoiced(purchaseOrderInvoiceService.getInvoicedAmount(purchaseOrder, invoice.getId(), true));
            purchaseOrderRepository.save(purchaseOrder);
        }
    }
}
Also used : InvoiceLine(com.axelor.apps.account.db.InvoiceLine) PurchaseOrder(com.axelor.apps.purchase.db.PurchaseOrder)

Example 74 with PurchaseOrder

use of com.axelor.apps.purchase.db.PurchaseOrder in project axelor-open-suite by axelor.

the class WorkflowVentilationServiceSupplychainImpl method purchaseOrderLineProcess.

private PurchaseOrder purchaseOrderLineProcess(Invoice invoice, InvoiceLine invoiceLine) throws AxelorException {
    PurchaseOrderLine purchaseOrderLine = invoiceLine.getPurchaseOrderLine();
    if (purchaseOrderLine == null) {
        return null;
    }
    PurchaseOrder purchaseOrder = purchaseOrderLine.getPurchaseOrder();
    BigDecimal invoicedAmountToAdd = invoiceLine.getExTaxTotal();
    // If is it a refund invoice, so we negate the amount invoiced
    if (InvoiceToolService.isRefund(invoiceLine.getInvoice())) {
        invoicedAmountToAdd = invoicedAmountToAdd.negate();
    }
    // Update invoiced amount on purchase order line
    if (!invoice.getCurrency().equals(purchaseOrder.getCurrency()) && purchaseOrderLine.getCompanyExTaxTotal().compareTo(BigDecimal.ZERO) != 0) {
        // If the purchase order currency is different from the invoice currency, use company currency
        // to calculate a rate. This rate will be applied to purchase order line
        BigDecimal currentCompanyInvoicedAmount = invoiceLine.getCompanyExTaxTotal();
        BigDecimal rate = currentCompanyInvoicedAmount.divide(purchaseOrderLine.getCompanyExTaxTotal(), 4, RoundingMode.HALF_UP);
        invoicedAmountToAdd = rate.multiply(purchaseOrderLine.getExTaxTotal());
    }
    purchaseOrderLine.setAmountInvoiced(purchaseOrderLine.getAmountInvoiced().add(invoicedAmountToAdd));
    return purchaseOrder;
}
Also used : PurchaseOrderLine(com.axelor.apps.purchase.db.PurchaseOrderLine) PurchaseOrder(com.axelor.apps.purchase.db.PurchaseOrder) BigDecimal(java.math.BigDecimal)

Example 75 with PurchaseOrder

use of com.axelor.apps.purchase.db.PurchaseOrder in project axelor-open-suite by axelor.

the class BatchOrderInvoicingPurchase method process.

@Override
protected void process() {
    SupplychainBatch supplychainBatch = batch.getSupplychainBatch();
    List<String> filterList = new ArrayList<>();
    Query<PurchaseOrder> query = Beans.get(PurchaseOrderRepository.class).all();
    if (supplychainBatch.getCompany() != null) {
        filterList.add("self.company = :company");
        query.bind("company", supplychainBatch.getCompany());
    }
    if (supplychainBatch.getSalespersonOrBuyerSet() != null && !supplychainBatch.getSalespersonOrBuyerSet().isEmpty()) {
        filterList.add("self.buyerUser IN (:buyerSet)");
        query.bind("buyerSet", supplychainBatch.getSalespersonOrBuyerSet());
    }
    if (supplychainBatch.getTeam() != null) {
        filterList.add("self.buyerUser IS NOT NULL AND self.buyerUser.activeTeam = :team");
        query.bind("team", supplychainBatch.getTeam());
    }
    if (!Strings.isNullOrEmpty(supplychainBatch.getDeliveryOrReceiptState())) {
        List<Integer> receiptStateList = StringTool.getIntegerList(supplychainBatch.getDeliveryOrReceiptState());
        filterList.add("self.receiptState IN (:receiptStateList)");
        query.bind("receiptStateList", receiptStateList);
    }
    if (!Strings.isNullOrEmpty(supplychainBatch.getStatusSelect())) {
        List<Integer> statusSelectList = StringTool.getIntegerList(supplychainBatch.getStatusSelect());
        filterList.add("self.statusSelect IN (:statusSelectList)");
        query.bind("statusSelectList", statusSelectList);
    }
    if (supplychainBatch.getOrderUpToDate() != null) {
        filterList.add("self.orderDate <= :orderUpToDate");
        query.bind("orderUpToDate", supplychainBatch.getOrderUpToDate());
    }
    filterList.add("self.amountInvoiced < self.exTaxTotal");
    filterList.add("NOT EXISTS (SELECT 1 FROM Invoice invoice WHERE invoice.statusSelect != :invoiceStatusSelect " + "AND (invoice.purchaseOrder = self " + "OR invoice.purchaseOrder IS NULL AND EXISTS (SELECT 1 FROM invoice.invoiceLineList invoiceLine " + "WHERE invoiceLine.purchaseOrderLine MEMBER OF self.purchaseOrderLineList)))");
    filterList.add("self.supplierPartner.id NOT IN (" + Beans.get(BlockingService.class).listOfBlockedPartner(supplychainBatch.getCompany(), BlockingRepository.INVOICING_BLOCKING) + ")");
    query.bind("invoiceStatusSelect", InvoiceRepository.STATUS_CANCELED);
    List<Long> anomalyList = Lists.newArrayList(0L);
    filterList.add("self.id NOT IN (:anomalyList)");
    query.bind("anomalyList", anomalyList);
    String filter = filterList.stream().map(item -> String.format("(%s)", item)).collect(Collectors.joining(" AND "));
    query.filter(filter);
    PurchaseOrderInvoiceService purchaseOrderInvoiceService = Beans.get(PurchaseOrderInvoiceService.class);
    Set<Long> treatedSet = new HashSet<>();
    for (List<PurchaseOrder> purchaseOrderList; !(purchaseOrderList = query.fetch(FETCH_LIMIT)).isEmpty(); JPA.clear()) {
        for (PurchaseOrder purchaseOrder : purchaseOrderList) {
            if (treatedSet.contains(purchaseOrder.getId())) {
                throw new IllegalArgumentException("Invoice generation error");
            }
            treatedSet.add(purchaseOrder.getId());
            try {
                purchaseOrderInvoiceService.generateInvoice(purchaseOrder);
                incrementDone();
            } catch (Exception e) {
                incrementAnomaly();
                anomalyList.add(purchaseOrder.getId());
                query.bind("anomalyList", anomalyList);
                TraceBackService.trace(e, ExceptionOriginRepository.INVOICE_ORIGIN, batch.getId());
                e.printStackTrace();
                break;
            }
        }
    }
}
Also used : Query(com.axelor.db.Query) StringTool(com.axelor.apps.tool.StringTool) JPA(com.axelor.db.JPA) PurchaseOrderRepository(com.axelor.apps.purchase.db.repo.PurchaseOrderRepository) TraceBackService(com.axelor.exception.service.TraceBackService) Set(java.util.Set) PurchaseOrderInvoiceService(com.axelor.apps.supplychain.service.PurchaseOrderInvoiceService) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) BlockingRepository(com.axelor.apps.base.db.repo.BlockingRepository) List(java.util.List) Lists(com.google.common.collect.Lists) InvoiceRepository(com.axelor.apps.account.db.repo.InvoiceRepository) Beans(com.axelor.inject.Beans) BlockingService(com.axelor.apps.base.service.BlockingService) ExceptionOriginRepository(com.axelor.exception.db.repo.ExceptionOriginRepository) PurchaseOrder(com.axelor.apps.purchase.db.PurchaseOrder) SupplychainBatch(com.axelor.apps.supplychain.db.SupplychainBatch) ArrayList(java.util.ArrayList) PurchaseOrderRepository(com.axelor.apps.purchase.db.repo.PurchaseOrderRepository) SupplychainBatch(com.axelor.apps.supplychain.db.SupplychainBatch) PurchaseOrder(com.axelor.apps.purchase.db.PurchaseOrder) PurchaseOrderInvoiceService(com.axelor.apps.supplychain.service.PurchaseOrderInvoiceService) HashSet(java.util.HashSet)

Aggregations

PurchaseOrder (com.axelor.apps.purchase.db.PurchaseOrder)84 PurchaseOrderLine (com.axelor.apps.purchase.db.PurchaseOrderLine)26 AxelorException (com.axelor.exception.AxelorException)26 Transactional (com.google.inject.persist.Transactional)16 BigDecimal (java.math.BigDecimal)12 Company (com.axelor.apps.base.db.Company)11 Context (com.axelor.rpc.Context)10 Partner (com.axelor.apps.base.db.Partner)9 Product (com.axelor.apps.base.db.Product)9 ArrayList (java.util.ArrayList)9 Invoice (com.axelor.apps.account.db.Invoice)7 List (java.util.List)7 PurchaseOrderRepository (com.axelor.apps.purchase.db.repo.PurchaseOrderRepository)6 SaleOrder (com.axelor.apps.sale.db.SaleOrder)6 PurchaseOrderSupplychainService (com.axelor.apps.supplychain.service.PurchaseOrderSupplychainService)6 LocalDate (java.time.LocalDate)6 PurchaseOrderService (com.axelor.apps.purchase.service.PurchaseOrderService)5 StockMove (com.axelor.apps.stock.db.StockMove)5 Unit (com.axelor.apps.base.db.Unit)4 PurchaseOrderLineService (com.axelor.apps.purchase.service.PurchaseOrderLineService)4