001/*
002 *  Copyright 2016 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.cms.search.query;
017
018import java.util.Date;
019
020import org.ametys.cms.content.indexing.solr.SolrFieldNames;
021
022/**
023 * {@link Query} testing the existence of a particular step on the workflow history.
024 */
025public class HistoryStepQuery implements Query
026{
027    private int _stepId;
028    private Date _startBefore;
029    private Date _startAfter;
030
031    /**
032     * Create a new HistoryStepQuery.
033     * @param stepId the workflow step ID.
034     */
035    public HistoryStepQuery(int stepId)
036    {
037        _stepId = stepId;
038    }
039    
040    /**
041     * Create a new HistoryStepQuery.
042     * @param stepId the workflow step ID.
043     * @param startAfter the beginning Date
044     * @param startBefore the ending Date
045     */
046    public HistoryStepQuery(int stepId, Date startAfter, Date startBefore)
047    {
048        _stepId = stepId;
049        _startBefore = startBefore;
050        _startAfter = startAfter;
051    }
052    
053    @Override
054    public String build()
055    {
056        StringBuilder query = new StringBuilder();
057        
058        // {!ametys join=workflowRef->wfHistorySteps q="wfStepId:x AND wfStepStartDate:[yyy TO zzz]"}
059        query.append("{!ametys join=").append(SolrFieldNames.WORKFLOW_REF)
060             .append("->").append(SolrFieldNames.WORKFLOW_HISTORY_STEPS).append(" q=\"")
061             .append(SolrFieldNames.WORKFLOW_STEP_ID).append(":").append(_stepId);
062        
063        if (_startAfter != null || _startBefore != null)
064        {
065            query.append(" AND ").append(SolrFieldNames.WORKFLOW_STEP_STARTDATE).append(":[")
066                 .append(_startAfter == null ? "*" : DateQuery.DATE_FORMAT.format(_startAfter))
067                 .append(" TO ")
068                 .append(_startBefore == null ? "*" : DateQuery.DATE_FORMAT.format(_startBefore))
069                 .append("}");
070        }
071        
072        query.append("\"}");
073        
074        return query.toString();
075    }
076}