예제 #1
0
  @Override
  public List<I_M_HU_Assignment> retrieveIncludedHUAssignments(final I_M_HU_Assignment assignment) {
    final IQueryBL queryBL = Services.get(IQueryBL.class);
    final IQueryBuilder<I_M_HU_Assignment> queryBuilder =
        queryBL.createQueryBuilder(I_M_HU_Assignment.class, assignment);

    queryBuilder
        // references same record..
        .addEqualsFilter(I_M_HU_Assignment.COLUMN_AD_Table_ID, assignment.getAD_Table_ID())
        .addEqualsFilter(I_M_HU_Assignment.COLUMN_Record_ID, assignment.getRecord_ID())
        // ..and same toplevel-HU..
        .addEqualsFilter(I_M_HU_Assignment.COLUMN_M_HU_ID, assignment.getM_HU_ID());

    // ..but additionally references one of the HU's components (TU or LU)
    final ICompositeQueryFilter<I_M_HU_Assignment> subFilter =
        queryBL.createCompositeQueryFilter(I_M_HU_Assignment.class);
    subFilter
        .setJoinOr()
        .addNotEqualsFilter(I_M_HU_Assignment.COLUMN_M_LU_HU_ID, null)
        .addNotEqualsFilter(I_M_HU_Assignment.COLUMN_M_TU_HU_ID, null);

    queryBuilder.filter(subFilter);

    //
    return queryBuilder.create().list(I_M_HU_Assignment.class);
  }
예제 #2
0
 @Override
 public int retrieveTableHUAssignmentsCount(
     final IContextAware contextProvider, final int adTableId, final I_M_HU hu) {
   final IQueryBuilder<I_M_HU_Assignment> queryBuilder =
       retrieveTableHUAssignmentsQuery(contextProvider, adTableId, hu);
   return queryBuilder.create().count();
 }
예제 #3
0
 @Override
 public List<I_M_HU_Assignment> retrieveTableHUAssignments(
     final IContextAware contextProvider, final int adTableId, final I_M_HU hu) {
   final IQueryBuilder<I_M_HU_Assignment> queryBuilder =
       retrieveTableHUAssignmentsQuery(contextProvider, adTableId, hu);
   return queryBuilder.create().list(I_M_HU_Assignment.class);
 }
예제 #4
0
  @Override
  public void deleteHUAssignments(
      final Object model, final Collection<I_M_HU> husToUnAssign, final String trxName) {
    Check.assumeNotNull(model, "model not null");
    Check.assumeNotNull(husToUnAssign, "husToUnAssign not null");

    final Properties ctx = InterfaceWrapperHelper.getCtx(model);
    final int adTableId = InterfaceWrapperHelper.getModelTableId(model);
    final int recordId = InterfaceWrapperHelper.getId(model);

    final Set<Integer> huIds = new HashSet<Integer>(husToUnAssign.size());
    for (final I_M_HU hu : husToUnAssign) {
      huIds.add(hu.getM_HU_ID());
    }

    if (huIds.isEmpty()) {
      return;
    }

    final IQueryBuilder<I_M_HU_Assignment> queryBuilder =
        Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Assignment.class, ctx, trxName);

    //
    // Note that here we don't want to skip anything; we want the HUAssignmentBL to do it's job, so
    // we clean everything up
    queryBuilder
        .addEqualsFilter(I_M_HU_Assignment.COLUMN_AD_Table_ID, adTableId)
        .addEqualsFilter(I_M_HU_Assignment.COLUMN_Record_ID, recordId)
        .addInArrayFilter(I_M_HU_Assignment.COLUMN_M_HU_ID, huIds)
        .create()
        .delete();
  }
예제 #5
0
  @Override
  public List<I_AD_Table> retrieveAllTables(final Properties ctx, final String trxName) {
    final IQueryBuilder<I_AD_Table> queryBuilder =
        Services.get(IQueryBL.class).createQueryBuilder(I_AD_Table.class, ctx, trxName);

    queryBuilder.orderBy().addColumn(I_AD_Table.COLUMNNAME_TableName);

    return queryBuilder.create().list();
  }
예제 #6
0
  private final IQuery<I_M_Material_Tracking_Ref> createMaterialTrackingRefQueryForModels(
      final List<?> models) {
    final IQueryBuilder<I_M_Material_Tracking_Ref> queryBuilder =
        createMaterialTrackingRefQueryBuilderForModels(models);
    if (queryBuilder == null) {
      return null;
    }

    return queryBuilder.create();
  }
예제 #7
0
  public IQueryBuilder<I_M_HU_Assignment> retrieveHUAssignmentsForModelQuery(
      final Properties ctx, final int adTableId, final int recordId, final String trxName) {
    final IQueryBuilder<I_M_HU_Assignment> queryBuilder =
        Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Assignment.class, ctx, trxName);

    applyCommonTopLevelFilters(queryBuilder, adTableId)
        .addEqualsFilter(I_M_HU_Assignment.COLUMN_Record_ID, recordId);

    queryBuilder.orderBy().addColumn(I_M_HU_Assignment.COLUMN_M_HU_Assignment_ID);

    return queryBuilder;
  }
  /**
   * Delete MRP Alternative records for given {@link I_DD_OrderLine_Alternative}.
   *
   * @param ddOrderLineAlt
   */
  private void deleteMRPAlternatives(final I_DD_OrderLine_Alternative ddOrderLineAlt) {
    Check.assumeNotNull(ddOrderLineAlt, "ddOrderLineAlt not null");
    final IQueryBL queryBL = Services.get(IQueryBL.class);
    final IQueryBuilder<I_PP_MRP_Alternative> queryBuilder =
        queryBL
            .createQueryBuilder(I_PP_MRP_Alternative.class, ddOrderLineAlt)
            .addEqualsFilter(
                I_PP_MRP_Alternative.COLUMN_DD_OrderLine_Alternative_ID,
                ddOrderLineAlt.getDD_OrderLine_Alternative_ID());

    queryBuilder.create().deleteDirectly();
  }
예제 #9
0
  @Override
  public List<I_M_HU> retrieveTUHUsForModel(final Object model) {
    final IQueryBuilder<I_M_HU> queryBuilder =
        retrieveTUHUAssignmentsForModelQuery(model).andCollect(I_M_HU_Assignment.COLUMN_M_TU_HU_ID);

    queryBuilder.orderBy().addColumn(I_M_HU.COLUMN_M_HU_ID);

    // NOTE: this method will NOT exclude destroyed HUs.
    // Before changing this, please carefully check the depending API.

    return queryBuilder.create().list();
  }
  private final Iterator<I_GL_JournalLine> retrieveGLJournalLines() {
    final I_C_TaxDeclaration taxDeclaration = getC_TaxDeclaration();

    final IQuery<I_C_TaxDeclarationLine> existingTaxDeclarationLinesQuery =
        createQueryBuilder(I_C_TaxDeclarationLine.class).create();

    final ICompositeQueryFilter<I_GL_JournalLine> taxAccountableFilter =
        queryBL
            .createCompositeQueryFilter(I_GL_JournalLine.class)
            .setJoinOr()
            .addEqualsFilter(I_GL_JournalLine.COLUMN_DR_AutoTaxAccount, true)
            .addEqualsFilter(I_GL_JournalLine.COLUMN_CR_AutoTaxAccount, true);

    final IQueryBuilder<I_GL_JournalLine> queryBuilder =
        createQueryBuilder(I_GL_JournalLine.class)
            //
            // Only invoices from reporting interval
            .addBetweenFilter(
                I_GL_JournalLine.COLUMN_DateAcct,
                taxDeclaration.getDateFrom(),
                taxDeclaration.getDateTo(),
                DateTruncQueryFilterModifier.DAY)
            //
            // Only those which are processed
            .addEqualsFilter(I_GL_JournalLine.COLUMN_Processed, true)
            //
            // Only those which are about taxes
            .filter(taxAccountableFilter)
            //
            // Only those which were not already included in other tax declaration
            .addNotInSubQueryFilter(
                I_GL_JournalLine.COLUMN_GL_JournalLine_ID,
                I_C_TaxDeclarationLine.COLUMN_GL_JournalLine_ID,
                existingTaxDeclarationLinesQuery)
        //
        ;

    queryBuilder
        .orderBy()
        .addColumn(I_GL_JournalLine.COLUMN_DateAcct)
        .addColumn(I_GL_JournalLine.COLUMN_GL_JournalLine_ID); // to have a predictable order

    return queryBuilder
        .create()
        // guaranteed because we are inserting in C_TaxDeclarationLine and in our query we check to
        // not have the record already there
        .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
        //
        .iterate(I_GL_JournalLine.class);
  }
예제 #11
0
  @Override
  @Cached(cacheName = I_AD_Message.Table_Name + "#by#" + I_AD_Message.COLUMNNAME_Value)
  public I_AD_Message retrieveByValue(@CacheCtx final Properties ctx, final String value) {
    final IQueryBuilder<I_AD_Message> queryBuilder =
        Services.get(IQueryBL.class)
            .createQueryBuilder(I_AD_Message.class)
            .setContext(ctx, ITrx.TRXNAME_None);

    final ICompositeQueryFilter<I_AD_Message> filters = queryBuilder.getFilters();
    filters.addEqualsFilter(I_AD_Message.COLUMNNAME_Value, value);
    filters.addOnlyActiveRecordsFilter();

    return queryBuilder.create().firstOnly(I_AD_Message.class);
  }
  @Override
  public <T extends I_M_ShipperTransportation> List<T> retrieveOpenShipperTransportations(
      final Properties ctx, final Class<T> clazz) {
    final IQueryBuilder<T> queryBuilder =
        Services.get(IQueryBL.class)
            .createQueryBuilder(clazz, ctx, ITrx.TRXNAME_None)
            .addEqualsFilter(I_M_ShipperTransportation.COLUMNNAME_Processed, false)
            .addEqualsFilter(
                I_M_ShipperTransportation.COLUMNNAME_DocStatus,
                X_M_ShipperTransportation.DOCSTATUS_Entwurf) // Drafts
        ;

    queryBuilder.orderBy().addColumn(I_M_ShipperTransportation.COLUMNNAME_DocumentNo);

    return queryBuilder.create().list();
  }
예제 #13
0
  private IQueryBuilder<I_AD_Column> retrieveColumnQueryBuilder(
      final String tableName, final String columnName) {
    //
    // Create queryBuilder with default context (not needed for tables)
    final IQueryBuilder<I_AD_Column> queryBuilder =
        Services.get(IQueryBL.class)
            .createQueryBuilder(I_AD_Column.class, Env.getCtx(), ITrx.TRXNAME_None);

    //
    // Filter by tableName
    queryBuilder.addEqualsFilter(I_AD_Column.COLUMNNAME_AD_Table_ID, retrieveTableId(tableName));
    //
    // Filter by columnName
    queryBuilder.addEqualsFilter(
        I_AD_Column.COLUMNNAME_ColumnName, columnName, UpperCaseQueryFilterModifier.instance);

    return queryBuilder;
  }
예제 #14
0
  @Override
  public <T> List<T> retrieveModelsForHU(
      final I_M_HU hu, final Class<T> clazz, final boolean topLevel) {
    final IQueryBL queryBL = Services.get(IQueryBL.class);

    final int tableId = InterfaceWrapperHelper.getTableId(clazz);
    final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(clazz);

    final IQueryBuilder<I_M_HU_Assignment> huAssigmentQueryBuilder =
        queryBL
            .createQueryBuilder(I_M_HU_Assignment.class, hu)
            .addOnlyContextClientOrSystem()
            .addOnlyActiveRecordsFilter()
            .addEqualsFilter(I_M_HU_Assignment.COLUMN_AD_Table_ID, tableId);
    if (topLevel) {
      huAssigmentQueryBuilder.addEqualsFilter(I_M_HU_Assignment.COLUMN_M_HU_ID, hu.getM_HU_ID());
      applyCommonTopLevelFilters(huAssigmentQueryBuilder, tableId);
    } else {
      final ICompositeQueryFilter<I_M_HU_Assignment> filter =
          queryBL
              .createCompositeQueryFilter(I_M_HU_Assignment.class)
              .setJoinOr()
              .addEqualsFilter(I_M_HU_Assignment.COLUMN_M_LU_HU_ID, hu.getM_HU_ID())
              .addEqualsFilter(I_M_HU_Assignment.COLUMN_M_TU_HU_ID, hu.getM_HU_ID())
              .addEqualsFilter(I_M_HU_Assignment.COLUMN_VHU_ID, hu.getM_HU_ID());
      huAssigmentQueryBuilder.filter(filter);
    }

    final IQuery<I_M_HU_Assignment> huAssigmentQuery = huAssigmentQueryBuilder.create();

    // @formatter:off
    return queryBL
        .createQueryBuilder(clazz, hu)
        .addOnlyContextClientOrSystem()
        .addOnlyActiveRecordsFilter()
        .addInSubQueryFilter(
            keyColumnName, I_M_HU_Assignment.COLUMNNAME_Record_ID, huAssigmentQuery)
        .orderBy()
        .addColumn(InterfaceWrapperHelper.getKeyColumnName(clazz))
        .endOrderBy()
        .create()
        .list(clazz);
    // @formatter:on
  }
예제 #15
0
  @Override
  public List<I_M_HU> retrieveTopLevelHUsForModel(final Object model, final String trxName) {
    final Properties ctx = InterfaceWrapperHelper.getCtx(model);
    final int adTableId = InterfaceWrapperHelper.getModelTableId(model);
    final int recordId = InterfaceWrapperHelper.getId(model);

    final IQueryBL queryBL = Services.get(IQueryBL.class);
    final IQueryBuilder<I_M_HU> queryBuilder =
        queryBL
            .createQueryBuilder(I_M_HU_Assignment.class, ctx, trxName)
            .addEqualsFilter(I_M_HU_Assignment.COLUMN_AD_Table_ID, adTableId)
            .addEqualsFilter(I_M_HU_Assignment.COLUMN_Record_ID, recordId)
            .addOnlyActiveRecordsFilter()
            //
            // Collect top level HUs
            .andCollect(I_M_HU_Assignment.COLUMN_M_HU_ID);

    //
    // 07612: Order by HU ID to preserve allocation order (i.e highest HU quantities / full HUs
    // first)
    queryBuilder.orderBy().addColumn(I_M_HU.COLUMN_M_HU_ID);

    final List<I_M_HU> husTopLevel = queryBuilder.create().list(I_M_HU.class);

    //
    // Guard: make sure all those HUs are really top level
    // Normally, this shall not happen. But we could have the case when the TU was joined to a LU
    // later and the HU assignment was not updated.
    final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
    for (final Iterator<I_M_HU> husTopLevelIterator = husTopLevel.iterator();
        husTopLevelIterator.hasNext(); ) {
      final I_M_HU hu = husTopLevelIterator.next();
      if (!handlingUnitsBL.isTopLevel(hu)) {
        husTopLevelIterator.remove();
        continue;
      }
    }

    // NOTE: this method will NOT exclude destroyed HUs.
    // Before changing this, please carefully check the depending API.

    return husTopLevel;
  }
예제 #16
0
 /**
  * Adds a filter that makes sure only <b>top level-HU</b> records with the given <code>AD_Table_ID
  * </code> and in addition with <code>M_LU_HU_ID</code>, <code>M_TU_HU_ID</code> and <code>VHU_ID
  * </code> being <code>null</code> will be selected.
  *
  * @param queryBuilder the builder that is augmented by this method
  * @param adTableId
  * @return
  */
 private IQueryBuilder<I_M_HU_Assignment> applyCommonTopLevelFilters(
     final IQueryBuilder<I_M_HU_Assignment> queryBuilder, final int adTableId) {
   queryBuilder
       .addEqualsFilter(I_M_HU_Assignment.COLUMN_AD_Table_ID, adTableId)
       //
       // Filter out entries which are specifically for other levels
       //
       .addEqualsFilter(I_M_HU_Assignment.COLUMN_M_LU_HU_ID, null)
       .addEqualsFilter(I_M_HU_Assignment.COLUMN_M_TU_HU_ID, null);
   return queryBuilder;
 }
  /**
   * Retrieves MRP Alternative record for given {@link I_DD_OrderLine_Alternative}.
   *
   * @param ddOrderLineAlt
   * @param mrp
   * @return MRP Alternative or <code>null</code>
   */
  private I_PP_MRP_Alternative retrieveMRPAlternative(
      final I_DD_OrderLine_Alternative ddOrderLineAlt, final I_PP_MRP mrp) {
    // Optimization: in case the DD_OrderLine was just created, there is no point to query because
    // there won't be any result for sure
    if (InterfaceWrapperHelper.isJustCreated(ddOrderLineAlt)) {
      return null;
    }

    Check.assumeNotNull(ddOrderLineAlt, "ddOrderLineAlt not null");
    Check.assumeNotNull(mrp, "mrp not null");

    final IQueryBL queryBL = Services.get(IQueryBL.class);
    final IQueryBuilder<I_PP_MRP_Alternative> queryBuilder =
        queryBL
            .createQueryBuilder(I_PP_MRP_Alternative.class, ddOrderLineAlt)
            .addEqualsFilter(
                I_PP_MRP_Alternative.COLUMN_DD_OrderLine_Alternative_ID,
                ddOrderLineAlt.getDD_OrderLine_Alternative_ID())
            .addEqualsFilter(I_PP_MRP_Alternative.COLUMN_PP_MRP_ID, mrp.getPP_MRP_ID());

    return queryBuilder.create().firstOnly(I_PP_MRP_Alternative.class);
  }
예제 #18
0
  @Override
  protected String doIt() throws Exception {
    if (p_Target_Directory == null) throw new FillMandatoryException("Target_Directory");
    if (p_EntityType == null) throw new FillMandatoryException("EntityType");

    final IQueryBuilder<I_EXP_Format> queryBuilder =
        Services.get(IQueryBL.class).createQueryBuilder(I_EXP_Format.class).setContext(this);

    if (p_FilterBy_AD_Client_ID) {
      queryBuilder.addInArrayFilter(I_EXP_Format.COLUMNNAME_AD_Client_ID, 0, getAD_Client_ID());
    }
    if (p_EntityType != null) {
      queryBuilder.addEqualsFilter(I_EXP_Format.COLUMNNAME_EntityType, p_EntityType);
    }

    queryBuilder
        .orderBy()
        .addColumn(I_EXP_Format.COLUMNNAME_EXP_Format_ID) // to have a predictible order
    ;

    final List<I_EXP_Format> expFormats = queryBuilder.create().list();

    final CanonicalXSDGenerator engine = new CanonicalXSDGenerator();
    for (final I_EXP_Format format : expFormats) {
      if (!format.isActive()) continue;
      engine.addEXPFormat(format);
      // metas-ts: commenting out for now, because taskes very long when there are many export
      // formats and it never helped me so far (mainly because it doesn't export embedded formats)
      // createTestModel(format);
    }
    createTestModelsIndex(expFormats);

    final String schemaFile = getSchemaFile().getAbsolutePath();
    engine.saveToFile(schemaFile);
    addLog("Created schema file: " + schemaFile);

    return "OK";
  }
예제 #19
0
  public final <T>
      IQueryBuilder<I_M_Material_Tracking_Ref> createMaterialTrackingRefQueryBuilderForModels(
          final IQueryBuilder<T> modelsQuery) {
    final IQueryBL queryBL = Services.get(IQueryBL.class);

    final Class<T> modelClass = modelsQuery.getModelClass();
    final int modelTableId = InterfaceWrapperHelper.getTableId(modelClass);
    final String modelKeyColumnName = InterfaceWrapperHelper.getKeyColumnName(modelClass);

    //
    // Create M_Material_Tracking_Ref query
    final IQueryBuilder<I_M_Material_Tracking_Ref> materialTrackingRefQueryBuilder =
        queryBL
            .createQueryBuilder(I_M_Material_Tracking_Ref.class)
            .setContext(getCtx(), getTrxName())
            .addEqualsFilter(I_M_Material_Tracking_Ref.COLUMN_AD_Table_ID, modelTableId)
            .addInSubQueryFilter(
                I_M_Material_Tracking_Ref.COLUMNNAME_Record_ID,
                modelKeyColumnName,
                modelsQuery.create());

    return materialTrackingRefQueryBuilder;
  }
예제 #20
0
  @Override
  public <T extends I_AD_Archive> T retrievePDFArchiveForModel(
      final Object model, final Class<T> archiveClass) {
    Check.assumeNotNull(model, "model not null");
    Check.assumeNotNull(archiveClass, "archiveClass not null");

    //
    // Services
    final IQueryBL queryBL = Services.get(IQueryBL.class);
    final IDocOutboundDAO archiveDAO = Services.get(IDocOutboundDAO.class);

    final Object contextProvider = model;
    final int adTableId = InterfaceWrapperHelper.getModelTableId(model);
    final int recordId = InterfaceWrapperHelper.getId(model);

    final IQueryBuilder<I_C_Doc_Outbound_Log> docOutboundLogQueryBuilder =
        queryBL
            .createQueryBuilder(I_C_Doc_Outbound_Log.class, contextProvider)
            .addOnlyActiveRecordsFilter()
            .addEqualsFilter(I_C_Doc_Outbound_Log.COLUMN_AD_Table_ID, adTableId)
            .addEqualsFilter(I_C_Doc_Outbound_Log.COLUMN_Record_ID, recordId);

    final IQueryBuilder<I_C_Doc_Outbound_Log_Line> docOutboundLogLineQueryBuilder =
        docOutboundLogQueryBuilder.andCollectChildren(
            I_C_Doc_Outbound_Log_Line.COLUMN_C_Doc_Outbound_Log_ID,
            I_C_Doc_Outbound_Log_Line.class);

    archiveDAO.addPDFArchiveLogLineFilters(docOutboundLogLineQueryBuilder);

    final I_C_Doc_Outbound_Log_Line pdfLine = docOutboundLogLineQueryBuilder.create().first();

    if (pdfLine == null) {
      return null;
    }
    final T archive = InterfaceWrapperHelper.create(pdfLine.getAD_Archive(), archiveClass);
    return archive;
  }
예제 #21
0
  public IQueryBuilder<I_M_Material_Tracking> createQueryBuilder(
      final IMaterialTrackingQuery queryVO) {
    Check.assumeNotNull(queryVO, "queryVO not null");

    final IQueryBuilder<I_M_Material_Tracking> queryBuilder =
        queryBL
            .createQueryBuilder(I_M_Material_Tracking.class)
            .setContext(getCtx(), getTrxName())
            .addOnlyContextClient()
            .addOnlyActiveRecordsFilter();

    final IQueryOrderByBuilder<I_M_Material_Tracking> orderBy = queryBuilder.orderBy();

    //
    // M_Product_ID
    final int productId = queryVO.getM_Product_ID();
    Check.assume(productId > 0, "productId > 0");
    queryBuilder.addEqualsFilter(I_M_Material_Tracking.COLUMN_M_Product_ID, productId);

    //
    // C_BPartner_ID
    final int bpartnerId = queryVO.getC_BPartner_ID();
    queryBuilder.addInArrayFilter(I_M_Material_Tracking.COLUMN_C_BPartner_ID, null, bpartnerId);
    orderBy.addColumn(I_M_Material_Tracking.COLUMN_C_BPartner_ID, Direction.Descending, Nulls.Last);

    // TODO: ValidFrom, ValidTo

    //
    // Processed
    final Boolean processed = queryVO.getProcessed();
    if (processed != null) {
      queryBuilder.addEqualsFilter(I_M_Material_Tracking.COLUMN_Processed, processed);
    }

    //
    // Linked documents
    final List<?> linkedModels = queryVO.getWithLinkedDocuments();
    if (linkedModels != null && !linkedModels.isEmpty()) {
      final IQuery<I_M_Material_Tracking_Ref> materialTrackingRefQuery =
          createMaterialTrackingRefQueryForModels(linkedModels);
      if (materialTrackingRefQuery != null) {
        queryBuilder.addInSubQueryFilter(
            I_M_Material_Tracking.COLUMN_M_Material_Tracking_ID,
            I_M_Material_Tracking_Ref.COLUMN_M_Material_Tracking_ID,
            materialTrackingRefQuery);
      }
      // TODO
    }

    return queryBuilder;
  }
예제 #22
0
 @Override
 public boolean hasColumnName(final String tableName, final String columnName) {
   final IQueryBuilder<I_AD_Column> queryBuilder =
       retrieveColumnQueryBuilder(tableName, columnName);
   return queryBuilder.create().setOnlyActiveRecords(true).match();
 }
예제 #23
0
 @Override
 public I_AD_Column retrieveColumnOrNull(final String tableName, final String columnName) {
   final IQueryBuilder<I_AD_Column> queryBuilder =
       retrieveColumnQueryBuilder(tableName, columnName);
   return queryBuilder.create().setOnlyActiveRecords(true).firstOnly(I_AD_Column.class);
 }
  @Override
  public I_C_DocLine_Sort find() {
    //
    // BPartner query builder
    final IQueryBuilder<I_C_BP_DocLine_Sort> bpQueryBuilder =
        queryBL
            .createQueryBuilder(I_C_BP_DocLine_Sort.class, getCtx(), ITrx.TRXNAME_None)
            .addOnlyActiveRecordsFilter();

    bpQueryBuilder.addEqualsFilter(I_C_BP_DocLine_Sort.COLUMN_C_BPartner_ID, getC_BPartner_ID());

    //
    // Collect header
    final IQueryBuilder<I_C_DocLine_Sort> docLineQueryBuilder =
        bpQueryBuilder
            .andCollect(I_C_BP_DocLine_Sort.COLUMN_C_DocLine_Sort_ID, I_C_DocLine_Sort.class)
            .addOnlyActiveRecordsFilter();

    //
    // IsDefault
    docLineQueryBuilder.addEqualsFilter(I_C_DocLine_Sort.COLUMN_IsDefault, false);

    //
    // DocBaseType
    docLineQueryBuilder.addEqualsFilter(I_C_DocLine_Sort.COLUMN_DocBaseType, getDocBaseType());

    final boolean existsBPDocLineSortConfig = docLineQueryBuilder.create().match();
    if (existsBPDocLineSortConfig) {
      return docLineQueryBuilder.create().firstOnly(I_C_DocLine_Sort.class);
    }

    //
    // Retrieve default if no match was found
    final IQueryBuilder<I_C_DocLine_Sort> docLineDefaultQueryBuilder =
        queryBL
            .createQueryBuilder(I_C_DocLine_Sort.class, getCtx(), ITrx.TRXNAME_None)
            .addOnlyActiveRecordsFilter();

    //
    // IsDefault
    docLineDefaultQueryBuilder.addEqualsFilter(I_C_DocLine_Sort.COLUMN_IsDefault, true);

    //
    // DocBaseType
    docLineDefaultQueryBuilder.addEqualsFilter(
        I_C_DocLine_Sort.COLUMN_DocBaseType, getDocBaseType());

    //
    // Return default (if any)
    return docLineDefaultQueryBuilder.create().firstOnly(I_C_DocLine_Sort.class);
  }
  /** Initialize all panel fields and editors based on {@link #asiTemplate}. */
  private final void initAttributes() {
    final Properties ctx = getCtx();
    final boolean isProductWindow = isProductWindow();
    final boolean isProcessParameter = isProcessParameter();
    final boolean isPureProductASI = isPureProductASI();
    final boolean allowSelectExistingASI = isAllowSelectExistingASI();
    final MAttributeSet as = asiTemplate.getMAttributeSet();
    Check.assumeNotNull(as, "attribute set not null");
    final boolean isASITemplateNew = asiTemplate.getM_AttributeSetInstance_ID() <= 0;

    //
    // Show Select existing ASI (if allowed)
    if (allowSelectExistingASI) {
      // New/Edit - Selection
      if (isASITemplateNew) // new ASI
      cbNewEdit.setText(msgBL.getMsg(ctx, "NewRecord"));
      else cbNewEdit.setText(msgBL.getMsg(ctx, "EditRecord"));
      cbNewEdit.addActionListener(this);
      centerPanel.add(cbNewEdit, new ALayoutConstraint(m_row++, 0));
      bSelectExistingASI.setText(msgBL.getMsg(ctx, "SelectExisting"));
      bSelectExistingASI.addActionListener(this);
      centerPanel.add(bSelectExistingASI, null);
    }

    //
    // Fetch M_Attributes
    final List<MAttribute> attributes;
    if (isProductWindow) {
      attributes = Arrays.asList(as.getMAttributes(false)); // non-instance attributes
    } else if (isPureProductASI) {
      // Regular product's attribute set instance attributes
      attributes = Arrays.asList(as.getMAttributes(true)); // all instance attributes
    } else if (isProcessParameter) {
      final IQueryBuilder<MAttribute> attributesQueryBuilder =
          queryBL
              .createQueryBuilder(MAttribute.class)
              .setContext(ctx, ITrx.TRXNAME_None)
              .addOnlyActiveRecordsFilter()
              .addOnlyContextClient();
      attributesQueryBuilder
          .orderBy()
          .addColumn(I_M_Attribute.COLUMNNAME_Name)
          .addColumn(I_M_Attribute.COLUMNNAME_M_Attribute_ID);
      attributes = attributesQueryBuilder.create().list(MAttribute.class);
    } else {
      attributes = Collections.emptyList();
    }

    //
    // Create attributes UI editors
    for (final MAttribute attribute : attributes) {
      if (!attributeExcludeBL.isExcludedAttribute(
          attribute, as, m_AD_Column_ID, attributeContext.isSOTrx())) {
        addAttributeLine(attribute);
      }
    }

    //
    // Lot
    if (isPureProductASI && as.isLot()) {
      CLabel label = new CLabel(msgBL.translate(ctx, "Lot"));
      label.setLabelFor(fieldLotString);
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldLotString, null);
      fieldLotString.setText(asiTemplate.getLot());
      // M_Lot_ID
      // int AD_Column_ID = 9771; // M_AttributeSetInstance.M_Lot_ID
      // fieldLot = new VLookup ("M_Lot_ID", false,false, true,
      // MLookupFactory.get(getCtx(), m_WindowNo, 0, AD_Column_ID, DisplayType.TableDir));
      final String sql =
          "SELECT M_Lot_ID, Name "
              + "FROM M_Lot l "
              + "WHERE EXISTS (SELECT M_Product_ID FROM M_Product p "
              + "WHERE p.M_AttributeSet_ID="
              + asiTemplate.getM_AttributeSet_ID()
              + " AND p.M_Product_ID=l.M_Product_ID)";
      fieldLot = new CComboBox<>(DB.getKeyNamePairs(sql, true));
      label = new CLabel(msgBL.translate(ctx, "M_Lot_ID"));
      label.setLabelFor(fieldLot);
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldLot, null);
      if (asiTemplate.getM_Lot_ID() > 0) {
        for (int i = 1; i < fieldLot.getItemCount(); i++) {
          KeyNamePair pp = fieldLot.getItemAt(i);
          if (pp.getKey() == asiTemplate.getM_Lot_ID()) {
            fieldLot.setSelectedIndex(i);
            fieldLotString.setEditable(false);
            break;
          }
        }
      }
      fieldLot.addActionListener(this);
      // New Lot Button
      if (asiTemplate.getMAttributeSet().getM_LotCtl_ID() > 0) {
        if (Env.getUserRolePermissions().isTableAccess(MLot.Table_ID, false)
            && Env.getUserRolePermissions().isTableAccess(MLotCtl.Table_ID, false)
            && !asiTemplate.isExcludeLot(m_AD_Column_ID, attributeContext.isSOTrx())) {
          centerPanel.add(bLot, null);
          bLot.addActionListener(this);
        }
      }
      // Popup
      fieldLot.addMouseListener(new VPAttributeDialog_mouseAdapter(this)); // popup
      mZoom = new CMenuItem(msgBL.getMsg(ctx, "Zoom"), Images.getImageIcon2("Zoom16"));
      mZoom.addActionListener(this);
      popupMenu.add(mZoom);
    } // Lot

    //
    // SerNo
    if (isPureProductASI && as.isSerNo()) {
      CLabel label = new CLabel(msgBL.translate(ctx, "SerNo"));
      label.setLabelFor(fieldSerNo);
      fieldSerNo.setText(asiTemplate.getSerNo());
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldSerNo, null);
      // New SerNo Button
      if (asiTemplate.getMAttributeSet().getM_SerNoCtl_ID() != 0) {
        if (Env.getUserRolePermissions().isTableAccess(MSerNoCtl.Table_ID, false)
            && !asiTemplate.isExcludeSerNo(m_AD_Column_ID, attributeContext.isSOTrx())) {
          centerPanel.add(bSerNo, null);
          bSerNo.addActionListener(this);
        }
      }
    } // SerNo

    //
    // GuaranteeDate.
    // We are displaying it if we deal with a pure product ASI (i.e. user is not editing the ASI
    // from product window),
    // and if:
    // * the attribute set requires a GuaranteeDate
    // * or if the ASI has a GuaranteeDate already set
    if (isPureProductASI && (as.isGuaranteeDate() || asiTemplate.getGuaranteeDate() != null)) {
      CLabel label = new CLabel(msgBL.translate(ctx, "GuaranteeDate"));
      label.setLabelFor(fieldGuaranteeDate);
      if (isASITemplateNew) {
        Date guaranteeDate = asiTemplate.getGuaranteeDate();
        if (guaranteeDate == null) {
          guaranteeDate =
              attributesBL.calculateBestBeforeDate(
                  ctx,
                  m_M_Product_ID, // product
                  attributeContext.getC_BPartner_ID(), // vendor bpartner
                  Env.getDate(ctx) // dateReceipt
                  );
        }
        fieldGuaranteeDate.setValue(guaranteeDate);
      } else {
        fieldGuaranteeDate.setValue(asiTemplate.getGuaranteeDate());
      }
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldGuaranteeDate, null);
      fieldGuaranteeDateDisplayed = true;
    } // GuaranteeDate

    // Make sure we have at least something to edit or something to select,
    // else there is no point in showing empty this window.
    if (m_row == 0) {
      throw new AdempiereException("@PAttributeNoInfo@");
    }

    //
    // New/Edit Window
    if (allowSelectExistingASI) {
      cbNewEdit.setSelected(isASITemplateNew);
      cmd_newEdit();
    }

    //
    // Attrribute Set Instance Description
    {
      final CLabel labelDescription = new CLabel(msgBL.translate(ctx, "Description"));
      labelDescription.setLabelFor(fieldDescription);
      fieldDescription.setText(asiTemplate.getDescription());
      fieldDescription.setEditable(false);
      centerPanel.add(labelDescription, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldDescription, null);
    }

    // Window usually to wide (??)
    {
      final Dimension dd = centerPanel.getPreferredSize();
      dd.width = Math.min(500, dd.width);
      centerPanel.setPreferredSize(dd);
    }
  } // initAttribute