Example #1
0
  public I_AD_Org createOrg(final String name) {
    final I_AD_Org org = InterfaceWrapperHelper.create(ctx, I_AD_Org.class, ITrx.TRXNAME_None);
    org.setValue(name);
    org.setName(name);
    InterfaceWrapperHelper.save(org);

    final I_AD_OrgInfo orgInfo = InterfaceWrapperHelper.newInstance(I_AD_OrgInfo.class, org);
    orgInfo.setAD_Org_ID(org.getAD_Org_ID());

    //
    // InTransit Warehouse
    final I_M_Warehouse warehouseInTransit = createWarehouse(name + "_InTransit", org);
    warehouseInTransit.setIsInTransit(true);
    InterfaceWrapperHelper.save(warehouseInTransit);

    //
    // BP Org Link
    final I_C_BPartner bpartner = createBPartner("BPOrg_" + name);
    // bpartner.setAD_OrgBP_ID(String.valueOf(org.getAD_Org_ID()));
    bpartner.setAD_OrgBP_ID(org.getAD_Org_ID());
    InterfaceWrapperHelper.save(bpartner);
    //
    final I_C_BPartner_Location bpLocation = createBPLocation(bpartner);
    orgInfo.setOrgBP_Location(bpLocation);
    InterfaceWrapperHelper.save(orgInfo);

    return org;
  }
Example #2
0
  /**
   * Creates a dummy MRP firm demand.
   *
   * <p>NOTE:
   *
   * <ul>
   *   <li>DocStatus will be Completed
   *   <li>OrderType will be SalesOrder
   * </ul>
   *
   * @param product
   * @param qty
   * @param date
   * @param plant
   * @param warehouse
   * @return demand MRP record
   */
  public I_PP_MRP createMRPDemand(
      final I_M_Product product,
      final BigDecimal qty,
      final Date date,
      final I_S_Resource plant,
      final I_M_Warehouse warehouse,
      final I_C_BPartner bpartner) {
    final I_PP_MRP mrp = InterfaceWrapperHelper.newInstance(I_PP_MRP.class, contextProvider);
    mrp.setAD_Org_ID(warehouse.getAD_Org_ID());
    mrp.setS_Resource(plant);
    mrp.setM_Warehouse(warehouse);
    mrp.setC_BPartner(bpartner);
    //
    final Timestamp dateTS = TimeUtil.asTimestamp(date);
    mrp.setDatePromised(dateTS);
    mrp.setDateStartSchedule(dateTS);
    mrp.setDateFinishSchedule(dateTS);
    //
    mrp.setTypeMRP(X_PP_MRP.TYPEMRP_Demand);
    mrp.setDocStatus(X_PP_MRP.DOCSTATUS_Completed); // Firm Demand
    mrp.setOrderType(X_PP_MRP.ORDERTYPE_SalesOrder); // Sales Order
    mrp.setIsAvailable(true);
    //
    mrp.setM_Product(product);
    Services.get(IMRPBL.class).setQty(mrp, qty, qty, product.getC_UOM());
    //
    // mrp.setC_BPartner(C_BPartner);

    InterfaceWrapperHelper.save(mrp);

    return mrp;
  }
Example #3
0
 public I_C_BP_Group createBPGroup(final String name) {
   final I_C_BP_Group bpGroup =
       InterfaceWrapperHelper.newInstance(I_C_BP_Group.class, contextProvider);
   bpGroup.setValue(name);
   bpGroup.setName(name);
   InterfaceWrapperHelper.save(bpGroup);
   return bpGroup;
 }
Example #4
0
  public I_M_Product_Category createProductCategory(final String name) {
    final I_M_Product_Category productCategory =
        InterfaceWrapperHelper.newInstance(I_M_Product_Category.class, contextProvider);
    productCategory.setValue(name);
    productCategory.setName(name);
    InterfaceWrapperHelper.save(productCategory);

    return productCategory;
  }
Example #5
0
 public void createMRPMessage(final String code) {
   final I_AD_Message message =
       InterfaceWrapperHelper.newInstance(I_AD_Message.class, contextProvider);
   InterfaceWrapperHelper.setValue(message, "AD_Client_ID", 0);
   message.setAD_Org_ID(0);
   message.setValue(code);
   message.setMsgText(code);
   InterfaceWrapperHelper.save(message);
 }
Example #6
0
  public I_M_Shipper createShipper(final I_C_BPartner bpartner) {
    final I_M_Shipper shipper =
        InterfaceWrapperHelper.newInstance(I_M_Shipper.class, contextProvider);
    shipper.setName(bpartner.getName());
    shipper.setC_BPartner_ID(bpartner.getC_BPartner_ID());

    InterfaceWrapperHelper.save(shipper);
    return shipper;
  }
Example #7
0
 public I_AD_Workflow createWorkflow(final String name) {
   final I_AD_Workflow wf =
       InterfaceWrapperHelper.newInstance(I_AD_Workflow.class, contextProvider);
   wf.setValue(name);
   wf.setName(name);
   wf.setWorkflowType(X_AD_Workflow.WORKFLOWTYPE_Manufacturing);
   InterfaceWrapperHelper.save(wf);
   return wf;
 }
Example #8
0
  private final I_M_HU createHU_InTrx(final I_M_HU_Item parentHUItem) {
    //
    // Get HUStatus to set
    final String huStatus;
    if (isHUStatusSet()) {
      huStatus = getHUStatus();
    } else if (parentHUItem != null) {
      huStatus = parentHUItem.getM_HU().getHUStatus();
    } else {
      huStatus = null;
    }

    //
    // Get M_Locator to set
    final I_M_Locator locator;
    if (_locatorSet) {
      locator = _locator;
    } else if (parentHUItem != null) {
      locator = parentHUItem.getM_HU().getM_Locator();
    } else {
      locator = null;
    }

    //
    // Create and save HU
    final I_M_HU hu = InterfaceWrapperHelper.newInstance(I_M_HU.class, getContext());
    POJOWrapper.setInstanceName(hu, _instanceName);
    hu.setM_HU_PI_Version(getM_HU_PI_Version());
    hu.setM_HU_Item_Parent(parentHUItem);
    hu.setC_BPartner(_bpartner);
    hu.setC_BPartner_Location(_bpartnerLocation);
    hu.setHUStatus(huStatus);
    hu.setM_Locator(locator);
    InterfaceWrapperHelper.save(hu);

    //
    // Create HU Attributes
    if (attributesExpectations != null) {
      attributesExpectations.createHUAttributes(hu);
    }

    //
    // Create HU Items
    if (huItemExpectations != null) {
      for (final HUItemExpectation<HUExpectation<ParentExpectationType>> huItemExpectation :
          huItemExpectations) {
        huItemExpectation.createHUItem(hu);
      }
    }

    // Capture the HU if required
    if (_huToSetRef != null) {
      _huToSetRef.setValue(hu);
    }

    return hu;
  }
Example #9
0
 public I_C_UOM createUOM(final String name, final int stdPrecision) {
   final I_C_UOM uom = InterfaceWrapperHelper.newInstance(I_C_UOM.class, contextProvider);
   uom.setName(name);
   uom.setUOMSymbol(name);
   uom.setX12DE355(name);
   uom.setStdPrecision(stdPrecision);
   uom.setCostingPrecision(0);
   InterfaceWrapperHelper.save(uom);
   return uom;
 }
Example #10
0
  public I_C_DocType createDocType(final String docBaseType) {
    final I_C_DocType docType =
        InterfaceWrapperHelper.newInstance(I_C_DocType.class, contextProvider);
    docType.setAD_Org_ID(adOrg01.getAD_Org_ID());
    docType.setDocBaseType(docBaseType);
    docType.setName(docBaseType);

    InterfaceWrapperHelper.save(docType);
    return docType;
  }
  @Override
  public I_M_HU_LUTU_Configuration copy(final I_M_HU_LUTU_Configuration lutuConfiguration) {
    Check.assumeNotNull(lutuConfiguration, "lutuConfiguration not null");
    final I_M_HU_LUTU_Configuration lutuConfigurationNew =
        InterfaceWrapperHelper.newInstance(I_M_HU_LUTU_Configuration.class, lutuConfiguration);
    final boolean honorIsCalculated = true;
    InterfaceWrapperHelper.copyValues(lutuConfiguration, lutuConfigurationNew, honorIsCalculated);

    return lutuConfigurationNew;
  }
Example #12
0
 public I_C_BPartner_Location createBPLocation(final I_C_BPartner bpartner) {
   final I_C_BPartner_Location bpLocation =
       InterfaceWrapperHelper.newInstance(I_C_BPartner_Location.class, bpartner);
   bpLocation.setC_BPartner_ID(bpartner.getC_BPartner_ID());
   bpLocation.setIsBillToDefault(true);
   bpLocation.setIsBillTo(true);
   bpLocation.setIsShipToDefault(true);
   bpLocation.setIsShipTo(true);
   InterfaceWrapperHelper.save(bpLocation);
   return bpLocation;
 }
Example #13
0
  public I_S_ResourceType createResourceType(final String name) {
    final I_S_ResourceType resourceType =
        InterfaceWrapperHelper.newInstance(I_S_ResourceType.class, contextProvider);
    resourceType.setIsActive(true);
    resourceType.setName(name);
    resourceType.setValue(name);
    resourceType.setIsDateSlot(false);
    resourceType.setIsTimeSlot(false);
    InterfaceWrapperHelper.save(resourceType);

    return resourceType;
  }
Example #14
0
  public I_C_BPartner createBPartner(final String name) {
    final I_C_BPartner bpartner =
        InterfaceWrapperHelper.newInstance(I_C_BPartner.class, contextProvider);
    bpartner.setValue(name);
    bpartner.setName(name);
    bpartner.setIsCustomer(true);
    bpartner.setIsVendor(true);
    bpartner.setAD_OrgBP_ID(-1);
    bpartner.setC_BP_Group_ID(bpGroupDefault == null ? -1 : bpGroupDefault.getC_BP_Group_ID());

    InterfaceWrapperHelper.save(bpartner);
    return bpartner;
  }
Example #15
0
  public I_M_Warehouse createWarehouse(
      final String name, final I_AD_Org org, final I_S_Resource plant) {
    final I_M_Warehouse warehouse =
        InterfaceWrapperHelper.newInstance(I_M_Warehouse.class, contextProvider);
    warehouse.setAD_Org_ID(org.getAD_Org_ID());
    warehouse.setValue(name);
    warehouse.setName(name);
    warehouse.setIsInTransit(false);
    warehouse.setPP_Plant(plant);
    InterfaceWrapperHelper.save(warehouse);

    return warehouse;
  }
Example #16
0
  public I_M_Product createProduct(final String name, final I_C_UOM uom) {
    final I_M_Product product =
        InterfaceWrapperHelper.newInstance(I_M_Product.class, contextProvider);
    product.setValue(name);
    product.setName(name);
    product.setM_Product_Category_ID(
        productCategoryDefault == null ? -1 : productCategoryDefault.getM_Product_Category_ID());
    product.setC_UOM_ID(uom.getC_UOM_ID());
    product.setLowLevel(0);
    InterfaceWrapperHelper.save(product);

    return product;
  }
Example #17
0
 private I_PP_Cost_Collector createVarianceCostCollector(
     I_PP_Cost_Collector cc, String CostCollectorType) {
   final I_PP_Cost_Collector ccv =
       InterfaceWrapperHelper.newInstance(I_PP_Cost_Collector.class, cc);
   InterfaceWrapperHelper.copyValues(cc, ccv);
   ccv.setProcessing(false);
   ccv.setProcessed(false);
   ccv.setDocStatus(X_PP_Cost_Collector.DOCSTATUS_Drafted);
   ccv.setDocAction(X_PP_Cost_Collector.DOCACTION_Complete);
   ccv.setCostCollectorType(CostCollectorType);
   ccv.setDocumentNo(null); // reset
   cc.setPP_Cost_Collector_Parent(cc); // link to parent
   InterfaceWrapperHelper.save(ccv);
   return ccv;
 }
Example #18
0
  public I_S_Resource createResource(
      String name, String manufacturingResourceType, final I_S_ResourceType resourceType) {
    final I_S_Resource resource =
        InterfaceWrapperHelper.newInstance(I_S_Resource.class, contextProvider);
    resource.setIsManufacturingResource(true);
    resource.setManufacturingResourceType(manufacturingResourceType);
    resource.setIsAvailable(true);
    resource.setName(name);
    resource.setValue(name);
    resource.setPlanningHorizon(365);
    resource.setS_ResourceType_ID(resourceType.getS_ResourceType_ID());
    InterfaceWrapperHelper.save(resource);

    return resource;
  }
Example #19
0
  private final void createReversal(
      final I_M_CostDetail costDetail, final I_PP_Cost_Collector reversalCostCollector) {
    final I_M_CostDetail costDetailReversal =
        InterfaceWrapperHelper.newInstance(I_M_CostDetail.class, costDetail);
    InterfaceWrapperHelper.copyValues(
        costDetail, costDetailReversal, true); // honorIsCalculated=true
    costDetailReversal.setPP_Cost_Collector_ID(reversalCostCollector.getPP_Cost_Collector_ID());
    costDetailReversal.setQty(costDetail.getQty().negate());
    costDetailReversal.setAmt(costDetail.getAmt().negate());
    costDetailReversal.setDeltaQty(costDetail.getDeltaQty().negate());
    costDetailReversal.setDeltaAmt(costDetail.getDeltaAmt().negate());
    costDetailReversal.setProcessed(false);
    InterfaceWrapperHelper.save(costDetailReversal);

    processCostDetail(costDetailReversal);
  }
Example #20
0
  public I_AD_WF_Node createWorkflowNode(
      final I_AD_Workflow wf, final String nodeName, final boolean startNode) {
    final I_AD_WF_Node node =
        InterfaceWrapperHelper.newInstance(I_AD_WF_Node.class, contextProvider);
    node.setAD_Workflow_ID(wf.getAD_Workflow_ID());
    node.setValue(nodeName);
    node.setName(nodeName);

    InterfaceWrapperHelper.save(node);

    if (startNode) {
      wf.setAD_WF_Node_ID(node.getAD_WF_Node_ID());
      InterfaceWrapperHelper.save(wf);
    }

    return node;
  }
  private void createDD_OrderLine_Alternative(
      IMRPContext mrpContext, I_DD_OrderLine ddOrderLine, I_PP_MRP_Alternative mrpAlternative) {
    final I_DD_OrderLine_Alternative ddOrderLineAlt =
        InterfaceWrapperHelper.newInstance(I_DD_OrderLine_Alternative.class, ddOrderLine);
    ddOrderLineAlt.setAD_Org_ID(mrpAlternative.getAD_Org_ID());
    ddOrderLineAlt.setDD_OrderLine(ddOrderLine);

    final I_M_Product product = mrpAlternative.getM_Product();
    final I_C_UOM uom = mrpBL.getC_UOM(mrpAlternative);
    final BigDecimal qty = mrpAlternative.getQty();

    ddOrderLineAlt.setM_Product(product);
    ddOrderLineAlt.setM_AttributeSetInstance(ddOrderLine.getM_AttributeSetInstance());
    ddOrderLineAlt.setC_UOM(uom);
    ddOrderLineAlt.setQtyOrdered(qty);
    ddOrderLineAlt.setQtyDelivered(BigDecimal.ZERO);
    ddOrderLineAlt.setQtyInTransit(BigDecimal.ZERO);

    InterfaceWrapperHelper.save(ddOrderLineAlt);
  }
  /**
   * Creates and {@link I_PMM_PurchaseCandidate} to {@link I_C_OrderLine} line allocation using the
   * whole candidate's QtyToOrder.
   *
   * @param orderLine
   */
  /* package */ void createAllocation(final I_C_OrderLine orderLine) {
    Check.assumeNotNull(orderLine, "orderLine not null");

    final BigDecimal qtyToOrder = getQtyToOrder();
    final BigDecimal qtyToOrderTU = getQtyToOrder_TU();

    //
    // Create allocation
    final I_PMM_PurchaseCandidate_OrderLine alloc =
        InterfaceWrapperHelper.newInstance(I_PMM_PurchaseCandidate_OrderLine.class, orderLine);
    alloc.setC_OrderLine(orderLine);
    alloc.setPMM_PurchaseCandidate(model);
    alloc.setQtyOrdered(qtyToOrder);
    alloc.setQtyOrdered_TU(qtyToOrderTU);
    InterfaceWrapperHelper.save(alloc);

    // NOTE: on alloc's save we expect the model's quantities to be updated
    InterfaceWrapperHelper.markStaled(
        model); // FIXME: workaround because we are modifying the model from alloc's model
                // interceptor
  }
  /**
   * Creates five invoice lines, with partially same line numbers. Flags three of the with {@link
   * InvoiceBL#setHasFixedLineNumber(I_C_InvoiceLine, boolean)} and then renumber them by calling
   * {@link InvoiceBL#renumberLines(java.util.List, int)}.<br>
   * Verify that they are renumbered such that the invoice lines with fixed number retain that
   * number and that only the reset actually get renumbered.
   */
  @Test
  public void test() {
    final InvoiceBL invoiceBL = new InvoiceBL();

    final I_C_Invoice invoice = InterfaceWrapperHelper.newInstance(I_C_Invoice.class, context);
    InterfaceWrapperHelper.save(invoice);

    final I_C_InvoiceLine il1 = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, context);
    il1.setC_Invoice(invoice);
    il1.setLine(10);
    InterfaceWrapperHelper.save(il1);

    final I_C_InvoiceLine il2 = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, context);
    il2.setC_Invoice(invoice);
    il2.setLine(20);
    InterfaceWrapperHelper.save(il2);

    final I_C_InvoiceLine il3 = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, context);
    il3.setC_Invoice(invoice);
    il3.setLine(10);
    InterfaceWrapperHelper.save(il3);
    invoiceBL.setHasFixedLineNumber(il3, true);

    final I_C_InvoiceLine il4 = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, context);
    il4.setC_Invoice(invoice);
    il4.setLine(20);
    InterfaceWrapperHelper.save(il4);
    invoiceBL.setHasFixedLineNumber(il4, true);

    final I_C_InvoiceLine il5 = InterfaceWrapperHelper.newInstance(I_C_InvoiceLine.class, context);
    il5.setC_Invoice(invoice);
    il5.setLine(30);
    InterfaceWrapperHelper.save(il5);
    invoiceBL.setHasFixedLineNumber(il5, true);

    final ImmutableList<I_C_InvoiceLine> lines =
        ImmutableList.<I_C_InvoiceLine>of(il1, il2, il3, il4, il5);

    invoiceBL.renumberLines(lines, 10);

    assertThat(il1.getLine(), is(40));
    assertThat(il2.getLine(), is(50));
    assertThat(il3.getLine(), is(10));
    assertThat(il4.getLine(), is(20));
    assertThat(il5.getLine(), is(30));
  }
Example #24
0
  private I_M_DeliveryDay_Alloc createDeliveryDayAlloc(
      final IContextAware context,
      final I_M_DeliveryDay deliveryDay,
      final IDeliveryDayAllocable deliveryDayAllocable) {
    Check.assume(
        !deliveryDay.isProcessed(), "Delivery day shall not be processed: {0}", deliveryDay);

    final String tableName = deliveryDayAllocable.getTableName();
    final int adTableId = Services.get(IADTableDAO.class).retrieveTableId(tableName);

    final I_M_DeliveryDay_Alloc deliveryDayAlloc =
        InterfaceWrapperHelper.newInstance(I_M_DeliveryDay_Alloc.class, context);
    deliveryDayAlloc.setAD_Org_ID(deliveryDayAllocable.getAD_Org_ID());
    deliveryDayAlloc.setM_DeliveryDay(deliveryDay);
    deliveryDayAlloc.setAD_Table_ID(adTableId);
    deliveryDayAlloc.setRecord_ID(deliveryDayAllocable.getRecord_ID());
    deliveryDayAlloc.setM_Product_ID(deliveryDayAllocable.getM_Product_ID());

    deliveryDayHandlers.updateDeliveryDayAllocFromModel(deliveryDayAlloc, deliveryDayAllocable);

    InterfaceWrapperHelper.save(deliveryDayAlloc);

    return deliveryDayAlloc;
  }
Example #25
0
  @Override
  public void createBankStatementLines(
      final I_C_BankStatement bankStatement, final I_C_PaySelection paySelection) {
    Check.errorIf(
        bankStatement.getC_BP_BankAccount_ID() != paySelection.getC_BP_BankAccount_ID(),
        "C_BankStatement {} with C_BP_BankAccount_ID={} and C_PaySelection {} with C_BP_BankAccount_ID={} need to have the same C_BP_BankAccount_ID",
        bankStatement,
        bankStatement.getC_BP_BankAccount_ID(),
        paySelection,
        paySelection.getC_BP_BankAccount_ID());

    // services
    final IPaySelectionDAO paySelectionDAO = Services.get(IPaySelectionDAO.class);
    final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
    final IBankStatementBL bankStatementBL = Services.get(IBankStatementBL.class);

    I_C_BankStatementLine bankStatementLine = null;
    int nextReferenceLineNo = 10;

    final List<I_C_PaySelectionLine> paySelectionLines =
        paySelectionDAO.retrievePaySelectionLines(paySelection, I_C_PaySelectionLine.class);
    for (final I_C_PaySelectionLine psl : paySelectionLines) {
      // Skip if already in a bank statement
      if (isInBankStatement(psl)) {
        continue;
      }

      // Skip if no invoice
      if (psl.getC_Invoice_ID() <= 0) {
        continue;
      }

      //
      // Create the bank statement line (if not already created)
      if (bankStatementLine == null) {
        bankStatementLine =
            InterfaceWrapperHelper.newInstance(I_C_BankStatementLine.class, paySelection);
        bankStatementLine.setAD_Org_ID(paySelection.getAD_Org_ID());
        bankStatementLine.setC_BankStatement(bankStatement);
        bankStatementLine.setIsMultiplePaymentOrInvoice(
            true); // we have a reference line for each invoice
        bankStatementLine.setIsMultiplePayment(true); // each invoice shall have it's own payment
        bankStatementLine.setC_Currency_ID(bankStatement.getC_BP_BankAccount().getC_Currency_ID());
        bankStatementLine.setValutaDate(paySelection.getPayDate());
        bankStatementLine.setDateAcct(paySelection.getPayDate());
        bankStatementLine.setStatementLineDate(paySelection.getPayDate());
        bankStatementLine.setReferenceNo(null); // no ReferenceNo at this level
        bankStatementLine.setC_BPartner(
            null); // no partner because we will have it on "line reference" level
        bankStatementLine.setStmtAmt(BigDecimal.ZERO); // will be updated at the end
        bankStatementLine.setTrxAmt(BigDecimal.ZERO); // will be updated at the end
        bankStatementLine.setChargeAmt(BigDecimal.ZERO);
        bankStatementLine.setInterestAmt(BigDecimal.ZERO);
        InterfaceWrapperHelper.save(bankStatementLine);
      }

      //
      // Create new bank statement line reference for our current pay selection line.
      final I_C_BankStatementLine_Ref bankStatementLineRef =
          InterfaceWrapperHelper.newInstance(I_C_BankStatementLine_Ref.class, bankStatementLine);
      bankStatementLineRef.setAD_Org_ID(bankStatementLine.getAD_Org_ID());
      bankStatementLineRef.setC_BankStatementLine(bankStatementLine);
      IBankStatementBL.DYNATTR_DisableBankStatementLineRecalculateFromReferences.setValue(
          bankStatementLineRef, true); // disable recalculation. we will do it at the end

      //
      // Set Invoice from pay selection line
      bankStatementLineRef.setC_BPartner_ID(psl.getC_BPartner_ID());
      final I_C_Invoice invoice = psl.getC_Invoice();
      bankStatementLineRef.setC_Invoice(invoice);
      bankStatementLineRef.setC_Currency_ID(invoice.getC_Currency_ID());

      //
      // Get pay schedule line amounts:
      final boolean isReceipt;
      if (invoiceBL.isCreditMemo(invoice)) {
        // SOTrx=Y, but credit memo => receipt=N
        isReceipt = !invoice.isSOTrx();
      } else {
        // SOTrx=Y => receipt=Y
        isReceipt = invoice.isSOTrx();
      }
      final BigDecimal factor = isReceipt ? BigDecimal.ONE : BigDecimal.ONE.negate();
      final BigDecimal linePayAmt = psl.getPayAmt().multiply(factor);
      final BigDecimal lineDiscountAmt = psl.getDiscountAmt().multiply(factor);

      // we store the psl's discount amount, because if we create a payment from this line, then we
      // don't want the psl's Discount to end up as a mere underpayment.
      bankStatementLineRef.setDiscountAmt(lineDiscountAmt);
      bankStatementLineRef.setTrxAmt(linePayAmt);
      bankStatementLineRef.setReferenceNo(psl.getReference());
      bankStatementLineRef.setLine(nextReferenceLineNo);

      //
      // Set Payment from pay selection line.
      // NOTE: In case the pay selection line does not already have a payment generated,
      // we are generating it now because it's the most convenient for the user.
      createPaymentIfNeeded(psl);
      bankStatementLineRef.setC_Payment_ID(psl.getC_Payment_ID());

      //
      // Save the bank statement line reference
      InterfaceWrapperHelper.save(bankStatementLineRef);
      nextReferenceLineNo += 10;

      //
      // Update pay selection line => mark it as reconciled
      linkBankStatementLine(psl, bankStatementLine, bankStatementLineRef);
    }

    //
    // Update Bank Statement Line's totals:
    if (bankStatementLine != null) {
      bankStatementBL.recalculateStatementLineAmounts(bankStatementLine);
    }
  }
  @Override
  public I_M_HU_LUTU_Configuration createLUTUConfiguration(
      final I_M_HU_PI_Item_Product tuPIItemProduct,
      final I_M_Product cuProduct,
      final I_C_UOM cuUOM,
      final org.compiere.model.I_C_BPartner bpartner) {
    Check.assumeNotNull(tuPIItemProduct, "tuPIItemProduct not null");
    Check.assumeNotNull(cuProduct, "cuProduct not null");
    Check.assumeNotNull(cuUOM, "cuUOM not null");

    // Services used:
    final ITrxManager trxManager = Services.get(ITrxManager.class);
    final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
    final IHUCapacityBL huCapacityBL = Services.get(IHUCapacityBL.class);

    //
    // Context
    final Properties ctx = InterfaceWrapperHelper.getCtx(tuPIItemProduct);
    final IContextAware contextProvider;
    final String threadTrxName = trxManager.getThreadInheritedTrxName();
    if (trxManager.isNull(threadTrxName)) {
      contextProvider = new PlainContextAware(ctx, ITrx.TRXNAME_None);
    } else {
      contextProvider = trxManager.createThreadContextAware(ctx);
    }

    //
    // LU/TU configuration (draft)
    final I_M_HU_LUTU_Configuration lutuConfiguration =
        InterfaceWrapperHelper.newInstance(I_M_HU_LUTU_Configuration.class, contextProvider);
    lutuConfiguration.setC_BPartner(bpartner);
    lutuConfiguration.setIsActive(true);

    //
    // TU Configuration
    final I_M_HU_PI tuPI = tuPIItemProduct.getM_HU_PI_Item().getM_HU_PI_Version().getM_HU_PI();
    final IHUCapacityDefinition tuCapacity =
        huCapacityBL.getCapacity(tuPIItemProduct, cuProduct, cuUOM);
    //
    lutuConfiguration.setM_HU_PI_Item_Product(tuPIItemProduct);
    lutuConfiguration.setM_TU_HU_PI(tuPI);
    lutuConfiguration.setM_Product(cuProduct);
    lutuConfiguration.setC_UOM(cuUOM);
    if (tuCapacity.isInfiniteCapacity()) {
      lutuConfiguration.setIsInfiniteQtyCU(true);
      lutuConfiguration.setQtyCU(BigDecimal.ZERO);
    } else {
      lutuConfiguration.setIsInfiniteQtyCU(false);
      lutuConfiguration.setQtyCU(tuCapacity.getCapacity());
    }

    //
    // LU Configuration
    final I_M_HU_PI_Item luPIItem =
        handlingUnitsDAO.retrieveDefaultParentPIItem(
            tuPI, X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit, bpartner);
    if (luPIItem != null) {
      final I_M_HU_PI luPI = luPIItem.getM_HU_PI_Version().getM_HU_PI();
      lutuConfiguration.setM_LU_HU_PI(luPI);
      lutuConfiguration.setM_LU_HU_PI_Item(luPIItem);

      lutuConfiguration.setIsInfiniteQtyLU(true); // we produce as many as needed
      lutuConfiguration.setQtyLU(BigDecimal.ZERO);

      final int qtyTU = luPIItem.getQty().intValueExact();
      lutuConfiguration.setIsInfiniteQtyTU(false);
      lutuConfiguration.setQtyTU(BigDecimal.valueOf(qtyTU));
    } else {
      lutuConfiguration.setM_LU_HU_PI(null);
      lutuConfiguration.setM_LU_HU_PI_Item(null);

      lutuConfiguration.setIsInfiniteQtyLU(false);
      lutuConfiguration.setQtyLU(BigDecimal.ZERO);

      lutuConfiguration.setIsInfiniteQtyTU(true); // as many as needed
      lutuConfiguration.setQtyTU(BigDecimal.ZERO);
    }

    return lutuConfiguration;
  }
  /**
   * Creates a counter document for an order. The counter document is also processed, if there is a
   * {@link I_C_DocTypeCounter} with a <code>DocAction</code> configured.
   *
   * <p>This implementation partially uses legacy code. I didn't yet get to refactor/remove/replace
   * it all.
   */
  @Override
  public DocAction createCounterDocument(final DocAction document) {
    final I_C_Order order = InterfaceWrapperHelper.create(document, I_C_Order.class);
    final MOrder orderPO = LegacyAdapters.convertToPO(order);

    final I_C_DocType counterDocType = retrieveCounterDocTypeOrNull(document);

    final I_AD_Org counterOrg = retrieveCounterOrgOrNull(document);

    final de.metas.adempiere.model.I_C_Order counterOrder =
        InterfaceWrapperHelper.newInstance(
            de.metas.adempiere.model.I_C_Order.class, document.getCtx());
    final MOrder counterOrderPO = (MOrder) LegacyAdapters.convertToPO(counterOrder);

    counterOrder.setAD_Org(counterOrg); // 09700

    //
    counterOrder.setC_DocTypeTarget(counterDocType);
    counterOrder.setIsSOTrx(counterDocType.isSOTrx());

    // the new order needs to figure out the pricing by itself
    counterOrder.setM_PricingSystem(null);
    counterOrder.setM_PriceList(null);

    counterOrder.setDateOrdered(order.getDateOrdered());
    counterOrder.setDateAcct(order.getDateAcct());
    counterOrder.setDatePromised(order.getDatePromised());

    counterOrder.setRef_Order_ID(order.getC_Order_ID());

    final I_C_BPartner counterBP = retrieveCounterPartnerOrNull(document);
    counterOrderPO.setBPartner(counterBP);

    final I_M_Warehouse counterWarehouse =
        Services.get(IWarehouseAdvisor.class).evaluateOrderWarehouse(counterOrder);
    counterOrder.setM_Warehouse(counterWarehouse);

    // References (should not be required)
    counterOrder.setSalesRep_ID(order.getSalesRep_ID());
    InterfaceWrapperHelper.save(counterOrder);

    // copy the order lines
    final boolean counter = true;
    final boolean copyASI = true;
    counterOrderPO.copyLinesFrom(orderPO, counter, copyASI);

    // Update copied lines
    final boolean requery = true;
    final MOrderLine[] counterLines = counterOrderPO.getLines(requery, null);
    for (int i = 0; i < counterLines.length; i++) {
      final MOrderLine counterLine = counterLines[i];
      counterLine.setOrder(counterOrderPO); // copies header values (BP, etc.)
      counterLine.setPrice();
      counterLine.setTax();
      InterfaceWrapperHelper.save(counterLine);
    }
    logger.debug(counterOrder.toString());

    // Document Action
    final MDocTypeCounter counterDT =
        MDocTypeCounter.getCounterDocType(document.getCtx(), order.getC_DocType_ID());
    if (counterDT != null) {
      if (counterDT.getDocAction() != null) {
        counterOrder.setDocAction(counterDT.getDocAction());
        Services.get(IDocActionBL.class)
            .processEx(
                counterOrder,
                counterDT.getDocAction(),
                null); // not expecting a particular docStatus (e.g. for prepay orders, it might be
                       // "waiting to payment")
      }
    }
    return counterOrderPO;
  }
  @Override
  public void createSupply(final IMRPCreateSupplyRequest request) {
    final IMRPContext mrpContext = request.getMRPContext();
    final IMRPExecutor executor = request.getMRPExecutor();

    final Properties ctx = mrpContext.getCtx();
    final I_PP_Product_Planning productPlanningData = mrpContext.getProductPlanning();
    final I_AD_Org org = mrpContext.getAD_Org();
    final I_S_Resource plant = mrpContext.getPlant();
    final Timestamp supplyDateFinishSchedule = TimeUtil.asTimestamp(request.getDemandDate());

    // QtyToSupply: qty for which we need to produce the supply
    final BigDecimal qtyToSupply = request.getQtyToSupply();

    // TODO vpj-cd I need to create logic for DRP-040 Shipment Due Action Notice
    // Indicates that a shipment for a Order Distribution is due.
    // Action should be taken at the source warehouse to ensure that the order is received on time.

    // TODO vpj-cd I need to create logic for DRP-050 Shipment Pas Due Action Notice
    // Indicates that a shipment for a Order Distribution is past due. You should either delay the
    // orders created the requirement for the product
    // or expedite them when the product does arrive.

    if (productPlanningData.getDD_NetworkDistribution_ID() <= 0) {
      // Indicates that the Product Planning Data for this product does not specify a valid network
      // distribution.
      executor.newMRPNote(mrpContext, ERR_DRP_060_NoSourceOfSupply).collect();
      //
      return;
    }

    final I_DD_NetworkDistribution network = productPlanningData.getDD_NetworkDistribution();
    final List<I_DD_NetworkDistributionLine> networkLines =
        Services.get(IDistributionNetworkDAO.class)
            .retrieveNetworkLinesByTargetWarehouse(
                network, productPlanningData.getM_Warehouse_ID());
    if (networkLines.isEmpty()) {
      // No network lines were found for our target warehouse
      final I_M_Warehouse warehouseTo = productPlanningData.getM_Warehouse();
      executor
          .newMRPNote(mrpContext, ERR_DRP_060_NoSourceOfSupply)
          .setComment("@NotFound@ @DD_NetworkDistributionLine_ID@")
          .addParameter(
              I_DD_NetworkDistribution.COLUMNNAME_DD_NetworkDistribution_ID,
              network == null ? "?" : network.getName())
          .addParameter("M_Warehouse_Dest_ID", warehouseTo == null ? "?" : warehouseTo.getName())
          .collect();
      //
      return;
    }

    int M_Shipper_ID = -1;
    I_DD_Order order = null;

    BigDecimal qtyToSupplyRemaining = qtyToSupply;
    for (final I_DD_NetworkDistributionLine networkLine : networkLines) {
      //
      // Check: if we created DD Orders for all qty that needed to be supplied, stop here
      if (qtyToSupplyRemaining.signum() <= 0) {
        break;
      }

      // get supply source warehouse and locator
      final I_M_Warehouse warehouseFrom = networkLine.getM_WarehouseSource();
      final I_M_Locator locatorFrom =
          Services.get(IWarehouseBL.class).getDefaultLocator(warehouseFrom);

      // get supply target warehouse and locator
      final I_M_Warehouse warehouseTo = networkLine.getM_Warehouse();
      final I_M_Locator locatorTo = Services.get(IWarehouseBL.class).getDefaultLocator(warehouseTo);

      if (locatorFrom == null || locatorTo == null) {
        executor
            .newMRPNote(mrpContext, "DRP-001") // FIXME: DRP-001 error code does not exist
            .addParameter(
                I_DD_NetworkDistribution.COLUMNNAME_DD_NetworkDistribution_ID,
                network == null ? "?" : network.getName())
            .addParameter(
                I_DD_NetworkDistributionLine.COLUMNNAME_M_WarehouseSource_ID,
                warehouseFrom.getName())
            .addParameter(
                I_DD_NetworkDistributionLine.COLUMNNAME_M_Warehouse_ID, warehouseTo.getName())
            .setComment("No locators found for source or target warehouse")
            .collect();
        //
        continue;
      }

      //
      // Get the warehouse in transit
      final I_M_Warehouse warehouseInTrasit =
          retrieveInTransitWarehouse(ctx, warehouseFrom.getAD_Org_ID());
      if (warehouseInTrasit == null) {
        // DRP-010: Do not exist Transit Warehouse to this Organization
        executor
            .newMRPNote(mrpContext, ERR_DRP_010_InTransitWarehouseNotFound)
            .addParameter(I_AD_Org.COLUMNNAME_AD_Org_ID, org.getName())
            .collect();
        //
        continue;
      }

      //
      // DRP-030: Do not exist Shipper for Create Distribution Order
      if (networkLine.getM_Shipper_ID() <= 0) {
        executor
            .newMRPNote(mrpContext, "DRP-030")
            .addParameter(
                I_DD_NetworkDistribution.COLUMNNAME_DD_NetworkDistribution_ID,
                network == null ? "?" : network.getName())
            .addParameter(
                I_DD_NetworkDistributionLine.COLUMNNAME_DD_NetworkDistributionLine_ID, networkLine)
            .collect();
        //
        continue;
      }

      if (M_Shipper_ID != networkLine.getM_Shipper_ID()) {
        // Org Must be linked to BPartner
        final I_AD_Org locatorToOrg = locatorTo.getAD_Org();
        final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class);
        final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(locatorToOrg);
        if (orgBPartner == null) {
          // DRP-020: Target Org has no BP linked to it
          executor
              .newMRPNote(mrpContext, "DRP-020")
              .addParameter(I_AD_Org.COLUMNNAME_AD_Org_ID, locatorToOrg.getName())
              .collect();
          //
          continue;
        }

        final I_C_BPartner_Location orgBPLocation =
            bpartnerOrgBL.retrieveOrgBPLocation(
                mrpContext.getCtx(), locatorToOrg.getAD_Org_ID(), ITrx.TRXNAME_None);

        //
        // Try found some DD_Order with Shipper , Business Partner and Doc Status = Draft
        // Consolidate the demand in a single order for each Shipper , Business Partner ,
        // DemandDateStartSchedule
        order =
            getDDOrderFromCache(
                org,
                plant,
                warehouseInTrasit,
                networkLine.getM_Shipper_ID(),
                orgBPartner.getC_BPartner_ID(),
                supplyDateFinishSchedule);
        if (order == null) {
          order = InterfaceWrapperHelper.newInstance(I_DD_Order.class, mrpContext);
          order.setMRP_Generated(true);
          order.setMRP_AllowCleanup(true);
          order.setAD_Org_ID(warehouseTo.getAD_Org_ID());
          order.setPP_Plant(plant);
          order.setC_BPartner(orgBPartner);
          order.setC_BPartner_Location(orgBPLocation);
          // order.setAD_User_ID(productPlanningData.getPlanner_ID()); // FIXME: improve
          // performances/cache and retrive Primary BP's User
          order.setSalesRep_ID(productPlanningData.getPlanner_ID());

          final int docTypeDO_ID =
              getC_DocType_ID(mrpContext, X_C_DocType.DOCBASETYPE_DistributionOrder);
          order.setC_DocType_ID(docTypeDO_ID);
          order.setM_Warehouse(warehouseInTrasit);
          order.setDocStatus(X_DD_Order.DOCSTATUS_Drafted);
          order.setDocAction(X_DD_Order.DOCACTION_Complete);
          order.setDateOrdered(mrpContext.getDateAsTimestamp());
          order.setDatePromised(supplyDateFinishSchedule);
          order.setM_Shipper_ID(networkLine.getM_Shipper_ID());
          order.setIsInDispute(false);
          order.setIsInTransit(false);

          InterfaceWrapperHelper.save(order);

          executor.addGeneratedSupplyDocument(order);
          addToCache(order);
        }
        M_Shipper_ID = networkLine.getM_Shipper_ID();
      }

      //
      // Crate DD order line
      final BigDecimal qtyToMove =
          calculateQtyToMove(qtyToSupplyRemaining, networkLine.getPercent());
      createDD_OrderLine(
          mrpContext,
          order,
          networkLine,
          locatorFrom,
          locatorTo,
          qtyToMove,
          supplyDateFinishSchedule,
          request);

      qtyToSupplyRemaining = qtyToSupplyRemaining.subtract(qtyToMove);
    }

    //
    // Check: remaining qtyToSupply shall be ZERO
    if (qtyToSupplyRemaining.signum() != 0) {
      // TODO: introduce DRP-XXX notice
      throw new LiberoException(
          "Cannot create DD Order for required Qty To Supply."
              + "\nQtyToSupply: "
              + qtyToSupply
              + "\nQtyToSupply (remaining): "
              + qtyToSupplyRemaining
              + "\n@DD_NetworkDistribution_ID@: "
              + network
              + "\n@DD_NetworkDistributionLine_ID@: "
              + networkLines
              + "\nMRPContext: "
              + mrpContext);
    }
  }
  private I_DD_OrderLine createDD_OrderLine(
      final IMRPContext mrpContext,
      final I_DD_Order order,
      final I_DD_NetworkDistributionLine networkLine,
      final I_M_Locator locatorFrom,
      final I_M_Locator locatorTo,
      final BigDecimal qtyToMove,
      final Timestamp supplyDateFinishSchedule,
      final IMRPCreateSupplyRequest request) {
    final I_M_Product product = mrpContext.getM_Product();
    final int bpartnerId = request.getMRPDemandBPartnerId();
    final int orderLineSOId = request.getMRPDemandOrderLineSOId();

    //
    // Create DD Order Line
    final I_DD_OrderLine ddOrderline =
        InterfaceWrapperHelper.newInstance(I_DD_OrderLine.class, order);
    ddOrderline.setAD_Org_ID(order.getAD_Org_ID());
    ddOrderline.setDD_Order(order);
    ddOrderline.setC_BPartner_ID(bpartnerId);
    ddOrderline.setC_OrderLineSO_ID(orderLineSOId);

    //
    // Locator From/To
    ddOrderline.setM_Locator(locatorFrom);
    ddOrderline.setM_LocatorTo(locatorTo);

    //
    // Product, UOM, Qty
    // NOTE: we assume qtyToMove is in "mrpContext.getC_UOM()" which shall be the Product's stocking
    // UOM
    ddOrderline.setM_Product(product);
    ddOrderline.setC_UOM(mrpContext.getC_UOM());
    ddOrderline.setQtyEntered(qtyToMove);
    ddOrderline.setQtyOrdered(qtyToMove);
    ddOrderline.setTargetQty(qtyToMove);

    //
    // Dates
    ddOrderline.setDateOrdered(order.getDateOrdered());
    ddOrderline.setDatePromised(order.getDatePromised());

    //
    // Other flags
    ddOrderline.setIsInvoiced(false);
    ddOrderline.setDD_AllowPush(networkLine.isDD_AllowPush());
    ddOrderline.setIsKeepTargetPlant(networkLine.isKeepTargetPlant());

    //
    // Save DD Order Line
    InterfaceWrapperHelper.save(ddOrderline);

    //
    // Create DD_OrderLine_Alternatives
    // NOTE: demand MRP line is available only in lot-for-lot order policy
    // TODO: i think we shall get all MRP demands, retrieve their alternatives, aggregate them and
    // create DD_OrderLine_Alternatives
    final I_PP_MRP parentMRPDemand = request.getMRPDemandRecordOrNull();
    if (parentMRPDemand != null) {
      final List<I_PP_MRP_Alternative> mrpAlternatives =
          mrpDAO.retrieveMRPAlternativesQuery(parentMRPDemand).create().list();
      for (final I_PP_MRP_Alternative mrpAlternative : mrpAlternatives) {
        createDD_OrderLine_Alternative(mrpContext, ddOrderline, mrpAlternative);
      }
    }

    //
    // Set Correct Planning Dates
    final int durationDays = calculateDurationDays(mrpContext, networkLine);
    final Timestamp supplyDateStartSchedule =
        TimeUtil.addDays(supplyDateFinishSchedule, 0 - durationDays);
    final List<I_PP_MRP> mrpList = mrpDAO.retrieveMRPRecords(ddOrderline);
    for (final I_PP_MRP mrp : mrpList) {
      mrp.setDateStartSchedule(supplyDateStartSchedule);
      mrp.setDateFinishSchedule(supplyDateFinishSchedule);
      InterfaceWrapperHelper.save(mrp);
    }

    return ddOrderline;
  }
 @Override
 public I_M_HU_Attribute newHUAttribute(final Object contextProvider) {
   final I_M_HU_Attribute huAttribute =
       InterfaceWrapperHelper.newInstance(I_M_HU_Attribute.class, contextProvider);
   return huAttribute;
 }