← Back to team overview

dhis2-devs team mailing list archive

[Branch ~dhis2-devs-core/dhis2/trunk] Rev 3427: Improved Performance in Periodwise and Orgunitwise Reports

 

------------------------------------------------------------
revno: 3427
committer: Bharath <chbharathk@xxxxxxxxx>
branch nick: dhis2
timestamp: Tue 2011-04-19 13:13:37 +0530
message:
  Improved Performance in Periodwise and Orgunitwise Reports
added:
  local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/comparator/
  local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/comparator/Report_inNameComparator.java
modified:
  local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java
  local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_in.java
  local/in/dhis-in-services/dhis-in-service-reports/src/main/java/org/hisp/dhis/reports/DefaultReportService.java
  local/in/dhis-in-services/dhis-in-service-reports/src/main/resources/org/hisp/dhis/reports/hibernate/Reports.hbm.xml
  local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/action/GetReportsAction.java
  local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/ouwiseprogress/action/GenerateOuWiseProgressReportResultAction.java
  local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/periodwiseprogress/action/GeneratePeriodWiseProgressAnalyserResultAction.java
  local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/AddReportAction.java
  local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/UpdateReportAction.java
  local/in/dhis-web-reports-national/src/main/resources/META-INF/dhis/beans.xml
  local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/addReportForm.vm
  local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/editReportForm.vm


--
lp:dhis2
https://code.launchpad.net/~dhis2-devs-core/dhis2/trunk

Your team DHIS 2 developers is subscribed to branch lp:dhis2.
To unsubscribe from this branch go to https://code.launchpad.net/~dhis2-devs-core/dhis2/trunk/+edit-subscription
=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java	2011-03-01 08:17:42 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java	2011-04-19 07:43:37 +0000
@@ -31,6 +31,7 @@
 import java.util.Collection;
 import java.util.Date;
 import java.util.List;
+import java.util.Map;
 
 import org.hisp.dhis.dataelement.DataElement;
 import org.hisp.dhis.organisationunit.OrganisationUnit;
@@ -127,4 +128,8 @@
     String getAggCountForTextData( String formula, Date startDate, Date endDate, OrganisationUnit organisationUnit );
     
     String getCountForTextData( String formula, Date startDate, Date endDate, OrganisationUnit organisationUnit );
+    
+    String getResultDataValueFromAggregateTable( String formula, String periodIdsByComma, Integer orgunitId );
+    
+    Map<String, String> getResultDataValueFromAggregateTable( Integer orgunitId, String dataElmentIdsByComma, String periodIdsByComma );
 }

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_in.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_in.java	2011-04-15 11:13:19 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_in.java	2011-04-19 07:43:37 +0000
@@ -69,6 +69,8 @@
 
     private OrganisationUnitGroup orgunitGroup;
     
+    private String dataSetIds;
+    
     /**
      * All Sources that are generating this Report_in.
      */
@@ -106,6 +108,31 @@
         this.orgunitGroup = orgunitGroup;
     }
 
+    public Report_in( String name, String model, PeriodType periodType, String excelTemplateName,
+        String xmlTemplateName, String reportType, String dataSetIds )
+    {
+        this.name = name;
+        this.model = model;
+        this.periodType = periodType;
+        this.excelTemplateName = excelTemplateName;
+        this.xmlTemplateName = xmlTemplateName;
+        this.reportType = reportType;
+        this.dataSetIds = dataSetIds;
+    }
+
+    public Report_in( String name, String model, PeriodType periodType, String excelTemplateName,
+        String xmlTemplateName, String reportType, OrganisationUnitGroup orgunitGroup, String dataSetIds )
+    {
+        this.name = name;
+        this.model = model;
+        this.periodType = periodType;
+        this.excelTemplateName = excelTemplateName;
+        this.xmlTemplateName = xmlTemplateName;
+        this.reportType = reportType;
+        this.orgunitGroup = orgunitGroup;
+        this.dataSetIds = dataSetIds;
+    }
+    
     // -------------------------------------------------------------------------
     // hashCode and equals
     // -------------------------------------------------------------------------
@@ -233,5 +260,13 @@
         this.orgunitGroup = orgunitGroup;
     }
 
-    
+    public String getDataSetIds()
+    {
+        return dataSetIds;
+    }
+
+    public void setDataSetIds( String dataSetIds )
+    {
+        this.dataSetIds = dataSetIds;
+    }
 }
\ No newline at end of file

=== added directory 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/comparator'
=== added file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/comparator/Report_inNameComparator.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/comparator/Report_inNameComparator.java	1970-01-01 00:00:00 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/comparator/Report_inNameComparator.java	2011-04-19 07:43:37 +0000
@@ -0,0 +1,13 @@
+package org.hisp.dhis.reports.comparator;
+
+import java.util.Comparator;
+
+import org.hisp.dhis.reports.Report_in;
+
+public class Report_inNameComparator implements Comparator<Report_in>
+{
+    public int compare( Report_in report0, Report_in report1 )
+    {
+        return report0.getName().compareTo( report1.getName() );
+    }
+}

=== modified file 'local/in/dhis-in-services/dhis-in-service-reports/src/main/java/org/hisp/dhis/reports/DefaultReportService.java'
--- local/in/dhis-in-services/dhis-in-service-reports/src/main/java/org/hisp/dhis/reports/DefaultReportService.java	2011-04-15 11:14:02 +0000
+++ local/in/dhis-in-services/dhis-in-service-reports/src/main/java/org/hisp/dhis/reports/DefaultReportService.java	2011-04-19 07:43:37 +0000
@@ -9,8 +9,10 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -1652,26 +1654,8 @@
                 }
                 if ( dataElement.getType().equalsIgnoreCase( "int" ) )
                 {
-                    //PeriodType dePeriodType = getDataElementPeriodType( dataElement );
-                    //List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( dePeriodType, startDate, endDate ) );
-                    //List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( startDate, endDate ) );
-                    
                     Double aggregatedValue = aggregatedDataValueService.getAggregatedValue( dataElement.getId(), optionCombo.getId(), periodIds, organisationUnit.getId() );
                     
-                    /*
-                    for( Period period : periodList )
-                    {
-                        Double tempAggValue = aggregatedDataValueService.getAggregatedValue( dataElement, optionCombo, period, organisationUnit );
-                        if( tempAggValue != null )
-                        {
-                            aggregatedValue += tempAggValue;
-                            isAggregated = 1;
-                        }
-                    }
-                    
-                    replaceString = String.valueOf( aggregatedValue );
-                    */
-                    
                     if ( aggregatedValue == null )
                     {
                         replaceString = NULL_REPLACEMENT;
@@ -1687,16 +1671,10 @@
                 else
                 {
                     deFlag1 = 1;
-                    //PeriodType dePeriodType = getDataElementPeriodType( dataElement );
-                    //List<Period> periodList = new ArrayList<Period>( periodService.getIntersectingPeriodsByPeriodType( dePeriodType, startDate, endDate ) );
-                    //periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( dePeriodType, startDate, endDate ) );
-                    //Period tempPeriod = new Period();
                     
                     Period tempPeriod = new Period();
-                    //tempPeriod = periodService.getPeriod( Integer.parseInt( periodIds.split( "," )[0] ) );
                     
                     if ( periodIds == null || periodIds.isEmpty() )
-                    //if ( tempPeriod == null )
                     {
                         replaceString = "";
                         matcher.appendReplacement( buffer, replaceString );
@@ -1794,6 +1772,111 @@
             throw new RuntimeException( "Illegal DataElement id", ex );
         }
     }
+
+    public Map<String, String> getResultDataValueFromAggregateTable( Integer orgunitId, String dataElmentIdsByComma, String periodIdsByComma )
+    {
+        Map<String, String> aggDeMap = new HashMap<String, String>();
+        try
+        {
+            String query = "SELECT dataelementid,categoryoptioncomboid, SUM(value) FROM aggregateddatavalue" +
+                           " WHERE dataelementid IN (" + dataElmentIdsByComma + " ) AND "+
+                           " organisationunitid = "+ orgunitId +" AND "+
+                           " periodid IN (" + periodIdsByComma +") GROUP BY dataelementid,categoryoptioncomboid";
+
+            SqlRowSet rs = jdbcTemplate.queryForRowSet( query );
+            
+            while ( rs.next() )
+            {
+                Integer deId = rs.getInt( 1 );
+                Integer optionComId = rs.getInt( 2 );
+                Double aggregatedValue = rs.getDouble( 3 );
+                if( aggregatedValue != null )
+                {
+                    aggDeMap.put( deId+"."+optionComId, ""+aggregatedValue );
+                }
+            }
+            
+            return aggDeMap;
+        }
+        catch( Exception e )
+        {
+            throw new RuntimeException( "Illegal DataElement id", e );
+        }
+    }
+    
+    public String getResultDataValueFromAggregateTable( String formula, String periodIdsByComma, Integer orgunitId )
+    {
+        try
+        {
+            Pattern pattern = Pattern.compile( "(\\[\\d+\\.\\d+\\])" );
+
+            Matcher matcher = pattern.matcher( formula );
+            StringBuffer buffer = new StringBuffer();
+
+            String resultValue = "";
+
+            while ( matcher.find() )
+            {
+                String replaceString = matcher.group();
+
+                replaceString = replaceString.replaceAll( "[\\[\\]]", "" );
+                String optionComboIdStr = replaceString.substring( replaceString.indexOf( '.' ) + 1, replaceString
+                    .length() );
+
+                replaceString = replaceString.substring( 0, replaceString.indexOf( '.' ) );
+
+                int dataElementId = Integer.parseInt( replaceString );
+                int optionComboId = Integer.parseInt( optionComboIdStr );
+                
+                String query = "SELECT SUM(value) FROM aggregateddatavalue WHERE dataelementid = " + dataElementId + 
+                                " AND categoryoptioncomboid = "+optionComboId + 
+                                " AND periodid IN ("+ periodIdsByComma +")"+
+                                " AND organisationunitid = "+  orgunitId;
+
+                SqlRowSet rs = jdbcTemplate.queryForRowSet( query );
+
+                Double aggregatedValue = null;
+                if( rs.next() )
+                {
+                    aggregatedValue = rs.getDouble( 1 );
+                }
+
+                if ( aggregatedValue == null )
+                {
+                    replaceString = NULL_REPLACEMENT;
+                }
+                else
+                {
+                    replaceString = String.valueOf( aggregatedValue );
+                }
+                    
+                matcher.appendReplacement( buffer, replaceString );
+
+                resultValue = replaceString;
+            }
+
+            matcher.appendTail( buffer );
+            
+            double d = 0.0;
+            try
+            {
+                d = MathUtils.calculateExpression( buffer.toString() );
+            }
+            catch ( Exception e )
+            {
+                d = 0.0;
+                resultValue = "";
+            }
+            
+            resultValue = "" + (double) d;
+
+            return resultValue;
+        }
+        catch ( NumberFormatException ex )
+        {
+            throw new RuntimeException( "Illegal DataElement id", ex );
+        }
+    }
     
     public String getSurveyDesc( String formula )
     {

=== modified file 'local/in/dhis-in-services/dhis-in-service-reports/src/main/resources/org/hisp/dhis/reports/hibernate/Reports.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-reports/src/main/resources/org/hisp/dhis/reports/hibernate/Reports.hbm.xml	2011-04-15 11:14:02 +0000
+++ local/in/dhis-in-services/dhis-in-service-reports/src/main/resources/org/hisp/dhis/reports/hibernate/Reports.hbm.xml	2011-04-19 07:43:37 +0000
@@ -1,36 +1,37 @@
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
-  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
-  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
-
-<hibernate-mapping>
-  <class name="org.hisp.dhis.reports.Report_in" table="reportin">
-    <id name="id" column="reportid">
-      <generator class="native"/>
-    </id>
-
-    <property name="name" not-null="true" unique="true" length="160"/>
-    
-    <property name="model" not-null="true" length="100"/>
-
-    <many-to-one name="periodType" class="org.hisp.dhis.period.PeriodType" lazy="false"
-        column="periodtypeid" not-null="true" foreign-key="fk_reports_periodtypeid"/>
-
-    <property name="excelTemplateName" column="excelname" not-null="true" length="100"/>
-    
-    <property name="xmlTemplateName" column="xmlname" not-null="true" length="100"/>
-    
-    <property name="reportType" column="reporttype" not-null="true" length="100"/>
-
-    <many-to-one name="orgunitGroup" class="org.hisp.dhis.organisationunit.OrganisationUnitGroup" lazy="false"
-        column="orgunitgroupid" not-null="false" foreign-key="fk_reports_orgunitgroupid"/>
-
-    
-    <set name="sources" table="reportsource">
-      <key column="reportid"/>
-      <many-to-many column="sourceid" 
-        class="org.hisp.dhis.source.Source"/>
-    </set>
-        
-  </class>
-</hibernate-mapping>
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
+
+<hibernate-mapping>
+  <class name="org.hisp.dhis.reports.Report_in" table="reportin">
+    <id name="id" column="reportid">
+      <generator class="native"/>
+    </id>
+
+    <property name="name" not-null="true" unique="true" length="160"/>
+    
+    <property name="model" not-null="true" length="100"/>
+
+    <many-to-one name="periodType" class="org.hisp.dhis.period.PeriodType" lazy="false"
+        column="periodtypeid" not-null="true" foreign-key="fk_reports_periodtypeid"/>
+
+    <property name="excelTemplateName" column="excelname" not-null="true" length="100"/>
+    
+    <property name="xmlTemplateName" column="xmlname" not-null="true" length="100"/>
+    
+    <property name="reportType" column="reporttype" not-null="true" length="100"/>
+
+    <many-to-one name="orgunitGroup" class="org.hisp.dhis.organisationunit.OrganisationUnitGroup" lazy="false"
+        column="orgunitgroupid" not-null="false" foreign-key="fk_reports_orgunitgroupid"/>
+
+    <property name="dataSetIds" column="datasetids" not-null="false" length="100"/>
+    
+    <set name="sources" table="reportsource">
+      <key column="reportid"/>
+      <many-to-many column="sourceid" 
+        class="org.hisp.dhis.source.Source"/>
+    </set>
+        
+  </class>
+</hibernate-mapping>

=== modified file 'local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/action/GetReportsAction.java'
--- local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/action/GetReportsAction.java	2011-01-05 05:31:43 +0000
+++ local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/action/GetReportsAction.java	2011-04-19 07:43:37 +0000
@@ -1,6 +1,7 @@
 package org.hisp.dhis.reports.action;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 
 import org.hisp.dhis.organisationunit.OrganisationUnit;
@@ -9,6 +10,7 @@
 import org.hisp.dhis.period.PeriodType;
 import org.hisp.dhis.reports.ReportService;
 import org.hisp.dhis.reports.Report_in;
+import org.hisp.dhis.reports.comparator.Report_inNameComparator;
 
 import com.opensymphony.xwork2.Action;
 
@@ -96,11 +98,10 @@
 
                 PeriodType periodTypeObj = periodService.getPeriodTypeByName( periodType );
                 
-                System.out.println( "report type  : " + reportType  + " ,Period Type :" + periodTypeObj.getName() + " ,org Unit :"  + ouName );
-                
                 reportList = new ArrayList<Report_in>( reportService.getReportsByPeriodSourceAndReportType(
                     periodTypeObj, orgUnit, reportType ) );
-                System.out.println( "Size of Reports List : " + reportList.size() );
+                
+                Collections.sort( reportList, new Report_inNameComparator() );
             }
             catch ( Exception e )
             {

=== modified file 'local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/ouwiseprogress/action/GenerateOuWiseProgressReportResultAction.java'
--- local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/ouwiseprogress/action/GenerateOuWiseProgressReportResultAction.java	2011-04-15 11:53:12 +0000
+++ local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/ouwiseprogress/action/GenerateOuWiseProgressReportResultAction.java	2011-04-19 07:43:37 +0000
@@ -2,6 +2,7 @@
 package org.hisp.dhis.reports.ouwiseprogress.action;
 
 import static org.hisp.dhis.system.util.ConversionUtils.getIdentifiers;
+import static org.hisp.dhis.system.util.TextUtils.getCommaDelimitedString;
 
 import java.io.BufferedInputStream;
 import java.io.File;
@@ -12,9 +13,13 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import jxl.Workbook;
 import jxl.format.Alignment;
@@ -30,6 +35,10 @@
 import jxl.write.WritableWorkbook;
 
 import org.amplecode.quick.StatementManager;
+import org.hisp.dhis.dataelement.DataElement;
+import org.hisp.dhis.dataelement.DataElementService;
+import org.hisp.dhis.dataset.DataSet;
+import org.hisp.dhis.dataset.DataSetService;
 import org.hisp.dhis.i18n.I18nFormat;
 import org.hisp.dhis.organisationunit.OrganisationUnit;
 import org.hisp.dhis.organisationunit.OrganisationUnitService;
@@ -39,6 +48,7 @@
 import org.hisp.dhis.reports.ReportService;
 import org.hisp.dhis.reports.Report_in;
 import org.hisp.dhis.reports.Report_inDesign;
+import org.hisp.dhis.system.util.MathUtils;
 
 import com.opensymphony.xwork2.Action;
 
@@ -83,6 +93,20 @@
         this.organisationUnitService = organisationUnitService;
     }
 
+    private DataSetService dataSetService;
+    
+    public void setDataSetService( DataSetService dataSetService )
+    {
+        this.dataSetService = dataSetService;
+    }
+    
+    private DataElementService dataElementService;
+    
+    public void setDataElementService( DataElementService dataElementService )
+    {
+        this.dataElementService = dataElementService;
+    }
+
     private I18nFormat format;
 
     public void setFormat( I18nFormat format )
@@ -176,8 +200,6 @@
         String colArray[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
                                 "AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ",
                                 "BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ" };
-        //char colArray[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
-        //char[] colArray = new char[ 101 ];
 
         // Getting Report Details       
         String deCodesXMLFileName = "";
@@ -211,7 +233,31 @@
 
         WritableWorkbook outputReportWorkbook = Workbook.createWorkbook( new File( outputReportPath ), templateWorkbook );
         WritableFont arialBold = new WritableFont( WritableFont.ARIAL, 10, WritableFont.BOLD );
+        WritableCellFormat wCellformat = new WritableCellFormat();
+        wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
+        wCellformat.setAlignment( Alignment.CENTRE );
+        wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE );
+        wCellformat.setWrap( true );
+        
+        String dataSetIds = selReportObj.getDataSetIds();
+        Collection<Integer> dataElementIdList = new ArrayList<Integer>();
+        if( dataSetIds != null )
+        {
+            String[] partsOfDataSetIds = dataSetIds.split( "," );
+            for( int i = 0; i < partsOfDataSetIds.length; i++ )
+            {
+                DataSet dataSet = dataSetService.getDataSet( Integer.parseInt( partsOfDataSetIds[i] ) );
+                dataElementIdList.addAll( getIdentifiers( DataElement.class, dataSet.getDataElements() ) );
+            }
+        }
+        else
+        {
+            dataElementIdList.addAll( getIdentifiers( DataElement.class, dataElementService.getAggregateableDataElements() ) );
+        }
+            
+        String dataElmentIdsByComma = getCommaDelimitedString( dataElementIdList );
 
+        
         // Period Info
         sDate = format.parseDate( startDate );
         eDate = format.parseDate( endDate );
@@ -220,6 +266,8 @@
         
         Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodList ) );
         
+        String periodIdsByComma = getCommaDelimitedString( periodIds );
+        
         // Getting DataValues
         List<Report_inDesign> reportDesignList = reportService.getReportDesign( deCodesXMLFileName );
         int orgUnitCount = 0;
@@ -229,6 +277,12 @@
         {
             OrganisationUnit currentOrgUnit = (OrganisationUnit) it.next();
 
+            Map<String, String> aggDeMap = new HashMap<String, String>();
+            if( aggData.equalsIgnoreCase( USEEXISTINGAGGDATA ) )
+            {
+                aggDeMap.putAll( reportService.getResultDataValueFromAggregateTable( currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma ) );
+            }
+
             int count1 = 0;
             Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
             while ( reportDesignIterator.hasNext() )
@@ -239,7 +293,7 @@
                 String deCodeString = report_inDesign.getExpression();
                 String tempStr = "";
 
-                if ( deCodeString.equalsIgnoreCase( "FACILITY" ) )
+                if ( deCodeString.equalsIgnoreCase( "FACILITY" ) )                    
                 {
                     tempStr = selectedOrgUnit.getName();
                 }
@@ -289,7 +343,7 @@
                         }
                         else if( aggData.equalsIgnoreCase( USEEXISTINGAGGDATA ) )
                         {
-                            tempStr = reportService.getResultDataValueFromAggregateTable( deCodeString, periodIds, currentOrgUnit, reportModelTB );
+                            tempStr = getAggVal( deCodeString, aggDeMap );
                         }
                     }
                 }
@@ -311,12 +365,6 @@
                         tempColNo += orgUnitCount;
                     }
 
-                    WritableCellFormat wCellformat = new WritableCellFormat();
-                    wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
-                    wCellformat.setAlignment( Alignment.CENTRE );
-                    wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE );
-                    wCellformat.setWrap( true );
-
                     try
                     {
                         sheet0.addCell( new Number( tempColNo, tempRowNo, Double.parseDouble( tempStr ), wCellformat ) );
@@ -335,6 +383,11 @@
         // ---------------------------------------------------------------------
         // Writing Total Values
         // ---------------------------------------------------------------------
+        WritableCellFormat totalCellformat = new WritableCellFormat( arialBold );
+        totalCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
+        totalCellformat.setAlignment( Alignment.CENTRE );
+        totalCellformat.setVerticalAlignment( VerticalAlignment.CENTRE );
+        totalCellformat.setWrap( true );
         
         Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
         while (  reportDesignIterator.hasNext() )
@@ -364,11 +417,6 @@
             String tempFormula = "SUM("+colStart+(tempRowNo+1)+":"+colEnd+(tempRowNo+1)+")";
             
             WritableSheet totalSheet = outputReportWorkbook.getSheet( sheetNo );
-            WritableCellFormat totalCellformat = new WritableCellFormat( arialBold );
-            totalCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
-            totalCellformat.setAlignment( Alignment.CENTRE );
-            totalCellformat.setVerticalAlignment( VerticalAlignment.CENTRE );
-            totalCellformat.setWrap( true );
 
             if( deCodeString.equalsIgnoreCase( "PROGRESSIVE-ORGUNIT" ) )
             {
@@ -401,4 +449,57 @@
 
         return SUCCESS;
     }
+    
+    private String getAggVal( String expression, Map<String, String> aggDeMap )
+    {
+        try
+        {
+            Pattern pattern = Pattern.compile( "(\\[\\d+\\.\\d+\\])" );
+
+            Matcher matcher = pattern.matcher( expression );
+            StringBuffer buffer = new StringBuffer();
+
+            String resultValue = "";
+
+            while ( matcher.find() )
+            {
+                String replaceString = matcher.group();
+
+                replaceString = replaceString.replaceAll( "[\\[\\]]", "" );
+
+                replaceString = aggDeMap.get( replaceString );
+                
+                if( replaceString == null )
+                {
+                    replaceString = "0";
+                }
+                
+                matcher.appendReplacement( buffer, replaceString );
+
+                resultValue = replaceString;
+            }
+
+            matcher.appendTail( buffer );
+            
+            double d = 0.0;
+            try
+            {
+                d = MathUtils.calculateExpression( buffer.toString() );
+            }
+            catch ( Exception e )
+            {
+                d = 0.0;
+                resultValue = "";
+            }
+            
+            resultValue = "" + (double) d;
+
+            return resultValue;
+        }
+        catch ( NumberFormatException ex )
+        {
+            throw new RuntimeException( "Illegal DataElement id", ex );
+        }
+    }
+
 }

=== modified file 'local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/periodwiseprogress/action/GeneratePeriodWiseProgressAnalyserResultAction.java'
--- local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/periodwiseprogress/action/GeneratePeriodWiseProgressAnalyserResultAction.java	2011-04-15 11:39:32 +0000
+++ local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/periodwiseprogress/action/GeneratePeriodWiseProgressAnalyserResultAction.java	2011-04-19 07:43:37 +0000
@@ -1,22 +1,24 @@
 package org.hisp.dhis.reports.periodwiseprogress.action;
 
 import static org.hisp.dhis.system.util.ConversionUtils.getIdentifiers;
+import static org.hisp.dhis.system.util.TextUtils.getCommaDelimitedString;
 
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
-import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
-import java.util.Calendar;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import jxl.Workbook;
 import jxl.format.Alignment;
@@ -33,6 +35,10 @@
 import jxl.write.WritableWorkbook;
 
 import org.amplecode.quick.StatementManager;
+import org.hisp.dhis.dataelement.DataElement;
+import org.hisp.dhis.dataelement.DataElementService;
+import org.hisp.dhis.dataset.DataSet;
+import org.hisp.dhis.dataset.DataSetService;
 import org.hisp.dhis.i18n.I18nFormat;
 import org.hisp.dhis.organisationunit.OrganisationUnit;
 import org.hisp.dhis.organisationunit.OrganisationUnitService;
@@ -42,6 +48,8 @@
 import org.hisp.dhis.reports.ReportService;
 import org.hisp.dhis.reports.Report_in;
 import org.hisp.dhis.reports.Report_inDesign;
+import org.hisp.dhis.system.util.MathUtils;
+import org.hisp.dhis.util.comparator.PeriodStartDateComparator;
 
 import com.opensymphony.xwork2.Action;
 
@@ -87,6 +95,20 @@
         this.organisationUnitService = organisationUnitService;
     }
 
+    private DataSetService dataSetService;
+    
+    public void setDataSetService( DataSetService dataSetService )
+    {
+        this.dataSetService = dataSetService;
+    }
+    
+    private DataElementService dataElementService;
+    
+    public void setDataElementService( DataElementService dataElementService )
+    {
+        this.dataElementService = dataElementService;
+    }
+
     private I18nFormat format;
 
     public void setFormat( I18nFormat format )
@@ -140,6 +162,13 @@
         this.availablePeriodsto = availablePeriodsto;
     }
 
+    private String periodTypeId;
+    
+    public void setPeriodTypeId( String periodTypeId )
+    {
+        this.periodTypeId = periodTypeId;
+    }
+
     private String aggData;
     
     public void setAggData( String aggData )
@@ -147,62 +176,24 @@
         this.aggData = aggData;
     }
 
-    private List<OrganisationUnit> orgUnitList;
-
     private Period selectedPeriod;
     
     private Period selectedEndPeriod;
 
     private SimpleDateFormat simpleDateFormat;
 
-    private SimpleDateFormat monthFormat;
-
-    private SimpleDateFormat yearFormat;
-
-    private String reportFileNameTB;
-
-    private String reportModelTB;
-
     private Date sDate;
 
     private Date eDate;
 
-    private Date sDateTemp;
-
-    private Date eDateTemp;
-
-    private PeriodType periodType;
-
     private String raFolderName;
 
-    Integer startMonth;
-
-    Integer endMonth;
-
-    private Map<Integer, Double> mapOfTotalValues;
-
-    private int startRowNumber;
-
-    private int totalColumnNumber;
-
     private int sheetNo = 0;
 
     private int tempColNo;
 
     private int tempRowNo;
     
-    private Integer tempMonthCount;
-    
-    Map<String, String> months;
-
-    Map<String, Integer> monthOrder;
-
-    String[] monthArray;
-    
-    private Date tempSDate;
-
-    private Date tempEDate;
-
     // -------------------------------------------------------------------------
     // Action implementation
     // -------------------------------------------------------------------------
@@ -214,271 +205,115 @@
         // Initialization
         raFolderName = reportService.getRAFolderName();
 
-        simpleDateFormat = new SimpleDateFormat( "MMM-yyyy" );
-        monthFormat = new SimpleDateFormat( "MMMM" );
-        yearFormat = new SimpleDateFormat( "yyyy" );
-        mapOfTotalValues = new HashMap<Integer, Double>();
-        List<Integer> totalRowList = new ArrayList<Integer>();
-        
-        //char colArray[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
-       // String colArray[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ"};
         String colArray[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
             "AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ",
             "BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ" };
         
-        startMonth = 0;
-        endMonth = 0;
-        
-        String deCodesXMLFileName = "";
-
         Report_in selReportObj = reportService.getReport( Integer.parseInt( reportList ) );
 
-        deCodesXMLFileName = selReportObj.getXmlTemplateName();
-        reportModelTB = selReportObj.getModel();
-        reportFileNameTB = selReportObj.getExcelTemplateName();
-        String parentUnit = "";
-
-        if( reportModelTB.equalsIgnoreCase( "PROGRESSIVE-PERIOD" ) )
-        {
-            orgUnitList = new ArrayList<OrganisationUnit>();
-            OrganisationUnit orgUnit = organisationUnitService.getOrganisationUnit( ouIDTB );
-            orgUnitList.add( orgUnit );
-        }
-
-        System.out.println( orgUnitList.get( 0 ).getName()+ " : " + selReportObj.getName()+" : Report Generation Start Time is : " + new Date() );
-
-        months = new HashMap<String, String>();
-        monthOrder = new HashMap<String, Integer>();
-        monthArray = new String[12];
-
-        init();
-        
-        selectedPeriod = periodService.getPeriod( availablePeriods );
-        selectedEndPeriod = periodService.getPeriod( availablePeriodsto );
-
-        sDate = format.parseDate( String.valueOf( selectedPeriod.getStartDate() ) );
-
-        eDate = format.parseDate( String.valueOf( selectedPeriod.getEndDate() ) );
-
-        //simpleDateFormat = new SimpleDateFormat( "MMM-yyyy" );
-        
-        // for Month count
-        tempSDate = format.parseDate( String.valueOf( selectedPeriod.getStartDate() ) );
-        tempEDate = format.parseDate( String.valueOf( selectedEndPeriod.getStartDate() ) );
-        
-        Calendar tempStartMonth = Calendar.getInstance();
-        Calendar tempEndMonth = Calendar.getInstance();
-        tempStartMonth.setTime( selectedPeriod.getStartDate() );
-        
-        Calendar startDate = Calendar.getInstance();
-        Calendar endDate = Calendar.getInstance();
-        
-        startDate.setTime( tempSDate );
-        endDate.setTime( tempEDate );
-        
-        int eYear = endDate.get( Calendar.YEAR );
-        int sYear = startDate.get( Calendar.YEAR );
-        int eMonth = endDate.get( Calendar.MONTH );
-        int sMonth = startDate.get( Calendar.MONTH );
-
-        tempMonthCount = ((eYear - sYear) * 12) - sMonth + eMonth + 1;
-        
-        // period count for use existing agg data
-        //Date tempStartD = format.parseDate( String.valueOf( selectedPeriod.getStartDate() ) );
-        //Date tempEndD = format.parseDate( String.valueOf( selectedEndPeriod.getEndDate() ) );
-        
-        //List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( tempStartD, tempEndD ) );
-        
-        //Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodList ) );
-        
-        
-        //System.out.println( "Temp Month Count : " + tempMonthCount );
-        // month Count End
-        /*
-        if( tempStartMonth.get( Calendar.MONTH ) == Calendar.JANUARY || tempStartMonth.get( Calendar.MONTH ) == Calendar.FEBRUARY || tempStartMonth.get( Calendar.MONTH ) == Calendar.MARCH )
-        {
-            tempStartMonth.set( Calendar.MONTH, Calendar.APRIL );
-            tempStartMonth.roll( Calendar.YEAR, -1 );
-        } 
-        else
-        {
-            tempStartMonth.set( Calendar.MONTH, Calendar.APRIL );
-        }
-        */
-        String startMonthName = "";
-
-        String endMonthName = "";
-
-        startMonth = Calendar.MONTH;
-
-        startMonthName = monthFormat.format( tempStartMonth.getTime() );
-        
-       // tempEndMonth.setTime( selectedPeriod.getStartDate() );
-        
-        tempEndMonth.setTime( selectedEndPeriod.getStartDate() );
-
-        endMonth = Calendar.MONTH;
-
-        endMonthName = monthFormat.format( tempEndMonth.getTime() );
+        // OrgUnit Info
+        OrganisationUnit currentOrgUnit = organisationUnitService.getOrganisationUnit( ouIDTB );
+
+        System.out.println( currentOrgUnit.getName()+ " : " + selReportObj.getName()+" : Report Generation Start Time is : " + new Date() );
+
+        // Report Info
+        String deCodesXMLFileName = selReportObj.getXmlTemplateName();
+        String reportModelTB = selReportObj.getModel();
+        String reportFileNameTB = selReportObj.getExcelTemplateName();
 
         String inputTemplatePath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName + File.separator + "template" + File.separator + reportFileNameTB;
         String outputReportPath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName + File.separator + "output" + File.separator + UUID.randomUUID().toString() + ".xls";
         Workbook templateWorkbook = Workbook.getWorkbook( new File( inputTemplatePath ) );
 
         WritableWorkbook outputReportWorkbook = Workbook.createWorkbook( new File( outputReportPath ), templateWorkbook );
-        
-        // Getting DataValues
+        WritableCellFormat wCellformat = new WritableCellFormat();
+        wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
+        wCellformat.setAlignment( Alignment.CENTRE );
+        wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE );
+        wCellformat.setWrap( true );
+
+        // Period Info
+        selectedPeriod = periodService.getPeriod( availablePeriods );
+        selectedEndPeriod = periodService.getPeriod( availablePeriodsto );
+
+        sDate = format.parseDate( String.valueOf( selectedPeriod.getStartDate() ) );
+        eDate = format.parseDate( String.valueOf( selectedEndPeriod.getEndDate() ) );
+
+        PeriodType periodType = periodService.getPeriodTypeByName( periodTypeId );
+        List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( periodType, sDate, eDate ) );
+        Collections.sort( periodList, new PeriodStartDateComparator() );
+        
+        if( periodTypeId.equalsIgnoreCase( "monthly" ) )
+        {
+            simpleDateFormat = new SimpleDateFormat( "MMM-yyyy" ); 
+        }
+        else if( periodTypeId.equalsIgnoreCase( "yearly" ) )
+        {
+            simpleDateFormat = new SimpleDateFormat( "yyyy" );
+        }
+        else
+        {
+            simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
+        }
+        
+        // To get Aggregation Data
+        String dataSetIds = selReportObj.getDataSetIds();
+        Collection<Integer> dataElementIdList = new ArrayList<Integer>();
+        if( dataSetIds != null )
+        {
+            String[] partsOfDataSetIds = dataSetIds.split( "," );
+            for( int i = 0; i < partsOfDataSetIds.length; i++ )
+            {
+                DataSet dataSet = dataSetService.getDataSet( Integer.parseInt( partsOfDataSetIds[i] ) );
+                dataElementIdList.addAll( getIdentifiers( DataElement.class, dataSet.getDataElements() ) );
+            }
+        }
+        else
+        {
+            dataElementIdList.addAll( getIdentifiers( DataElement.class, dataElementService.getAggregateableDataElements() ) );
+        }
+            
+        String dataElmentIdsByComma = getCommaDelimitedString( dataElementIdList );
+        
         List<Report_inDesign> reportDesignList = reportService.getReportDesign( deCodesXMLFileName );
 
-        int rowCounter = 0;
-
-        int monthCount = 0;
-
-        String currentMonth = "";
-
-        OrganisationUnit currentOrgUnit = orgUnitList.get( 0 );
-        
-       // int currentMonthOrder = monthOrder.get( monthFormat.format( tempEndMonth.getTime() ) );
-
-       // while ( monthCount < currentMonthOrder )
-        while ( monthCount < tempMonthCount )    
+        int colCount = 0;
+        for( Period period : periodList )
         {
-            //currentMonth = monthArray[monthCount];
-            currentMonth = monthFormat.format( tempStartMonth.getTime() );
-            String tempCurrentMonth = simpleDateFormat.format( tempStartMonth.getTime() );
-            int count1 = 0;
-
+
+            Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodService.getPeriodsBetweenDates( period.getStartDate(), period.getEndDate() ) ) );
+            String periodsByComma = getCommaDelimitedString( periodIds );
+
+            Map<String, String> aggDeMap = new HashMap<String, String>();
+            if( aggData.equalsIgnoreCase( USEEXISTINGAGGDATA ) )
+            {
+                aggDeMap.putAll( reportService.getResultDataValueFromAggregateTable( currentOrgUnit.getId(), dataElmentIdsByComma, periodsByComma ) );
+            }
+            
             Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
             while (  reportDesignIterator.hasNext() )
             {
                 Report_inDesign reportDesign =  reportDesignIterator.next();
                 String deCodeString = reportDesign.getExpression();
 
-                String deType = reportDesign.getPtype();
                 String sType = reportDesign.getStype();
                 String tempStr = "";
 
                 tempRowNo = reportDesign.getRowno();
                 tempColNo = reportDesign.getColno();
                 sheetNo = reportDesign.getSheetno();
-                totalRowList.add( count1, tempRowNo );
-                
-                Calendar tempStart = Calendar.getInstance();
-                Calendar tempEnd = Calendar.getInstance();
-
-                //months.get( currentMonth );
-
-                String tempS = "01-" + months.get( currentMonth ) + "-" + tempStartMonth.get( Calendar.YEAR );
-                String tempE = String.valueOf( tempStartMonth.getActualMaximum( Calendar.DAY_OF_MONTH ) ) + "-" + months.get( currentMonth ) + "-" + tempStartMonth.get( Calendar.YEAR );
-
-                DateFormat tempMonthFormat;
-
-                tempMonthFormat = new SimpleDateFormat( "dd-MM-yy" );
-
-                Date tempDate = new Date();
-
-                tempStart.setTime( tempStartMonth.getTime() );
-
-                tempDate = (Date) tempMonthFormat.parse( tempS );
-
-                tempDate = (Date) tempMonthFormat.parse( tempE );
-
-                tempEnd.setTime( tempDate );
-               
-                Calendar tempStartDate = Calendar.getInstance();
-                Calendar tempEndDate = Calendar.getInstance();
-                
-                List<Calendar> calendarList = new ArrayList<Calendar>( reportService.getStartingEndingPeriods( deType, tempStart.getTime(), tempEnd.getTime() ) );
-                if ( calendarList == null || calendarList.isEmpty() )
-                {
-                    //tempStr = currentMonth;
-                    tempStr = tempCurrentMonth;
-                } 
-                else
-                {
-                    tempStartDate = calendarList.get( 0 );
-                    tempEndDate = calendarList.get( 1 );
-                }
-                 
+                              
                 if( deCodeString.equalsIgnoreCase( "FACILITY" ) )
                 {
                     tempStr = currentOrgUnit.getName();
                 } 
-                else if( deCodeString.equalsIgnoreCase( "FACILITY-NOREPEAT" ) )
-                {
-                    tempStr = parentUnit;
-                } 
-                else if ( deCodeString.equalsIgnoreCase( "MONTH-RANGE" ) )
-                {
-                    //tempStr = startMonthName + " - " + endMonthName;
-                    tempStr = startMonthName + "-" + yearFormat.format( tempSDate )+ " - " + endMonthName + "-" + yearFormat.format( tempEDate );
-                } 
-                else if ( deCodeString.equalsIgnoreCase( "YEAR-FROMTO" ) )
-                {
-                    sDateTemp = sDate;
-
-                    eDateTemp = eDate;
-
-                    Calendar tempQuarterYear = Calendar.getInstance();
-
-                    String startYear = "";
-
-                    String endYear = "";
-
-                    String startMonth = "";
-
-                    startMonth = monthFormat.format( sDateTemp );
-
-                    periodType = selectedPeriod.getPeriodType();
-
-                    tempQuarterYear.setTime( sDateTemp );
-
-                    if ( periodType.getName().equalsIgnoreCase( "Yearly" ) )
-                    {
-                        sDateTemp = sDate;
-                    } 
-                    else if ( ( startMonth.equalsIgnoreCase( "January" ) || startMonth.equalsIgnoreCase( "February" ) || startMonth.equalsIgnoreCase( "March" ) ) )
-                    {
-                        tempQuarterYear.roll( Calendar.YEAR, -1 );
-
-                        sDateTemp = tempQuarterYear.getTime();
-                    }
-                    startYear = yearFormat.format( sDateTemp );
-
-                    tempQuarterYear.setTime( eDateTemp );
-
-                    if ( periodType.getName().equalsIgnoreCase( "Yearly" ) )
-                    {
-                        tempQuarterYear.roll( Calendar.YEAR, 1 );
-                        eDateTemp = tempQuarterYear.getTime();
-                    }
-                    if ( !( startMonth.equalsIgnoreCase( "January" ) || startMonth.equalsIgnoreCase( "February" ) || startMonth.equalsIgnoreCase( "March" ) ) )
-                    {
-                        tempQuarterYear.roll( Calendar.YEAR, 1 );
-                        eDateTemp = tempQuarterYear.getTime();
-                    }
-                    endYear = yearFormat.format( eDateTemp );
-
-                    tempStr = startYear + " - " + endYear;
-                } 
+                else if ( deCodeString.equalsIgnoreCase( "PERIOD-RANGE" ) )
+                {
+                    tempStr = simpleDateFormat.format( selectedPeriod.getStartDate() ) + " To " + simpleDateFormat.format( selectedEndPeriod.getEndDate() );
+                }
                 else if( deCodeString.equalsIgnoreCase( "PROGRESSIVE-PERIOD" ) )
                 {
-                    Period p = new Period();
-    
-                    p = periodService.getPeriod( tempStartDate.getTime(), tempEndDate.getTime(), periodService.getPeriodTypeByName( "Monthly" ) );
-                    
-                    startRowNumber = tempRowNo;
-    
-                    if( p == null )
-                    {
-                        //tempStr = currentMonth;
-                        tempStr = tempCurrentMonth;
-                    } 
-                    else
-                    {
-                        //tempStr = monthFormat.format( p.getStartDate() );
-                        tempStr = simpleDateFormat.format( p.getStartDate() );
-                    }
+                    tempStr = simpleDateFormat.format( period.getStartDate() );
                 } 
                 else if( deCodeString.equalsIgnoreCase( "NA" ) )
                 {
@@ -486,83 +321,28 @@
                 } 
                 else
                 {
-                    rowCounter += 1;
-                    
                     if( sType.equalsIgnoreCase( "dataelement" ) )
                     {
                         if( aggData.equalsIgnoreCase( USECAPTUREDDATA ) ) 
                         {
-                            tempStr = reportService.getIndividualResultDataValue( deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit, reportModelTB );
+                            tempStr = reportService.getIndividualResultDataValue( deCodeString, period.getStartDate(), period.getEndDate(), currentOrgUnit, reportModelTB );
                         } 
                         else if( aggData.equalsIgnoreCase( GENERATEAGGDATA ) )
                         {
-                            tempStr = reportService.getResultDataValue( deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit, reportModelTB );
+                            tempStr = reportService.getResultDataValue( deCodeString, period.getStartDate(), period.getEndDate(), currentOrgUnit, reportModelTB );
                         }
                         else if( aggData.equalsIgnoreCase( USEEXISTINGAGGDATA ) )
                         {
-                            List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( tempStartDate.getTime(), tempEndDate.getTime() ) );
-                            Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodList ) );
-                            tempStr = reportService.getResultDataValueFromAggregateTable( deCodeString, periodIds, currentOrgUnit, reportModelTB );
-                        }
-                        
-                        double totalRowValue = 0.0;
-                        
-                        if( mapOfTotalValues.get( tempRowNo ) != null )
-                        {
-                            totalRowValue = mapOfTotalValues.get( tempRowNo );
-                            
-                            if ( !( tempStr.equalsIgnoreCase( " " ) || tempStr.equalsIgnoreCase( "" ) ) )
-                            {
-                                try
-                                {
-                                    totalRowValue += Double.parseDouble( tempStr );
-                                }
-                                catch( Exception e )
-                                {
-                                
-                                }
-                            }
-                            
-                            /*
-                            if ( !( tempStr.equalsIgnoreCase( " " ) || tempStr.equalsIgnoreCase( "" ) ) )
-                            {
-                                totalRowValue += Integer.valueOf( tempStr );
-                            }
-                            */
-    
-                            mapOfTotalValues.put( tempRowNo, totalRowValue );
-                        } 
-                        else
-                        {
-                            if( !( tempStr.equalsIgnoreCase( " " ) || tempStr.equalsIgnoreCase( "" ) ) )
-                            {
-                                try
-                                {
-                                    totalRowValue += Double.parseDouble( tempStr );
-                                }
-                                catch( Exception e )
-                                {
-                                
-                                }
-                            }
-                        
-                            //System.out.println("totalRowValue = "+totalRowValue);
-                            mapOfTotalValues.put( tempRowNo, totalRowValue );
+                            tempStr = getAggVal( deCodeString, aggDeMap );
                         }
                     } 
-                                        
                 }
                 
                 if( tempStr == null || tempStr.equals( " " ) )
                 {
-                    tempColNo += monthCount;
+                    tempColNo += colCount;
 
                     WritableSheet sheet0 = outputReportWorkbook.getSheet( sheetNo );
-                    WritableCellFormat wCellformat = new WritableCellFormat();
-
-                    wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
-                    wCellformat.setWrap( true );
-                    wCellformat.setAlignment( Alignment.CENTRE );
 
                     sheet0.addCell( new Blank( tempColNo, tempRowNo, wCellformat ) );
                 } 
@@ -570,23 +350,15 @@
                 {
                     if( reportModelTB.equalsIgnoreCase( "PROGRESSIVE-PERIOD" ) )
                     {
-                        if( deCodeString.equalsIgnoreCase( "FACILITY" ) || deCodeString.equalsIgnoreCase( "FACILITYP" ) || deCodeString.equalsIgnoreCase( "FACILITYPP" ) || deCodeString.equalsIgnoreCase( "FACILITYPPP" ) || deCodeString.equalsIgnoreCase( "FACILITYPPPP" ) )
+                        if( deCodeString.equalsIgnoreCase( "FACILITY" ) || deCodeString.equalsIgnoreCase( "PERIOD-RANGE" ) )
                         {                            
                         } 
-                        else if( deCodeString.equalsIgnoreCase( "PERIOD" ) || deCodeString.equalsIgnoreCase( "PERIOD-NOREPEAT" ) || deCodeString.equalsIgnoreCase( "MONTH-RANGE" ) || deCodeString.equalsIgnoreCase( "PERIOD-WEEK" ) || deCodeString.equalsIgnoreCase( "PERIOD-MONTH" ) || deCodeString.equalsIgnoreCase( "PERIOD-QUARTER" ) || deCodeString.equalsIgnoreCase( "PERIOD-YEAR" ) || deCodeString.equalsIgnoreCase( "MONTH-START" ) || deCodeString.equalsIgnoreCase( "MONTH-END" ) || deCodeString.equalsIgnoreCase( "MONTH-START-SHORT" ) || deCodeString.equalsIgnoreCase( "MONTH-END-SHORT" ) || deCodeString.equalsIgnoreCase( "SIMPLE-QUARTER" ) || deCodeString.equalsIgnoreCase( "QUARTER-MONTHS-SHORT" ) || deCodeString.equalsIgnoreCase( "QUARTER-MONTHS" ) || deCodeString.equalsIgnoreCase( "QUARTER-START-SHORT" ) || deCodeString.equalsIgnoreCase( "QUARTER-END-SHORT" ) || deCodeString.equalsIgnoreCase( "QUARTER-START" ) || deCodeString.equalsIgnoreCase( "QUARTER-END" ) || deCodeString.equalsIgnoreCase( "SIMPLE-YEAR" ) || deCodeString.equalsIgnoreCase( "YEAR-END" ) || deCodeString.equalsIgnoreCase( "YEAR-FROMTO" ) )
-                        {
-                        } 
                         else
                         {
-                            tempColNo += monthCount;
+                            tempColNo += colCount;
                         }
 
                         WritableSheet sheet0 = outputReportWorkbook.getSheet( sheetNo );
-                        WritableCellFormat wCellformat = new WritableCellFormat();
-                        wCellformat.setBorder( Border.ALL, BorderLineStyle.THIN );
-                        wCellformat.setAlignment( Alignment.CENTRE );
-                        wCellformat.setVerticalAlignment( VerticalAlignment.CENTRE );
-                        wCellformat.setWrap( true );
 
                         try
                         {
@@ -605,18 +377,9 @@
                         }
                     }
                 }
-                count1++;
             }// inner while loop end
 
-            tempStartMonth.roll( Calendar.MONTH, 1 );
-
-            if( tempStartMonth.get( Calendar.MONTH ) == Calendar.JANUARY )
-            {
-                tempStartMonth.roll( Calendar.YEAR, 1 );
-            }
-
-            monthCount++;
-            
+            colCount++;
         }// outer while loop end
 
         // ---------------------------------------------------------------------
@@ -631,9 +394,7 @@
             String deCodeString = reportDesign.getExpression();
 
             if( deCodeString.equalsIgnoreCase( "FACILITY" ) || 
-                deCodeString.equalsIgnoreCase( "FACILITY-NOREPEAT" ) ||
-                deCodeString.equalsIgnoreCase( "MONTH-RANGE" ) ||
-                deCodeString.equalsIgnoreCase( "YEAR-FROMTO" ) ) 
+                deCodeString.equalsIgnoreCase( "PERIOD-RANGE" ) )
             {
                 continue;
             } 
@@ -643,7 +404,7 @@
             sheetNo = reportDesign.getSheetno();
             
             String colStart = ""+ colArray[tempColNo];
-            String colEnd = ""+ colArray[tempColNo+monthCount-1];
+            String colEnd = ""+ colArray[tempColNo+colCount-1];
             
             String tempFormula = "SUM("+colStart+(tempRowNo+1)+":"+colEnd+(tempRowNo+1)+")";
             
@@ -657,29 +418,28 @@
 
             if( deCodeString.equalsIgnoreCase( "PROGRESSIVE-PERIOD" ) )
             {
-                totalSheet.addCell( new Label( tempColNo+monthCount, tempRowNo, "Total", totalCellformat ) );
+                totalSheet.addCell( new Label( tempColNo+colCount, tempRowNo, "Total", totalCellformat ) );
             }
             else if( deCodeString.equalsIgnoreCase( "NA" ) )
             {
-                totalSheet.addCell( new Label( tempColNo+monthCount, tempRowNo, " ", totalCellformat ) );
+                totalSheet.addCell( new Label( tempColNo+colCount, tempRowNo, " ", totalCellformat ) );
             }
             else
             {
-                totalSheet.addCell( new Formula( tempColNo+monthCount, tempRowNo, tempFormula, totalCellformat ) );    
+                totalSheet.addCell( new Formula( tempColNo+colCount, tempRowNo, tempFormula, totalCellformat ) );    
             }
         }
         
-        
         outputReportWorkbook.write();
         outputReportWorkbook.close();
 
         fileName = reportFileNameTB.replace( ".xls", "" );
-        fileName += "_" + orgUnitList.get( 0 ).getShortName() + "_";
+        fileName += "_" + currentOrgUnit.getShortName();
         fileName += "_" + simpleDateFormat.format( selectedPeriod.getStartDate() ) + ".xls";
         File outputReportFile = new File( outputReportPath );
         inputStream = new BufferedInputStream( new FileInputStream( outputReportFile ) );
 
-        System.out.println( orgUnitList.get( 0 ).getName()+ " : " + selReportObj.getName()+" : Report Generation End Time is : " + new Date() );
+        System.out.println( currentOrgUnit.getName()+ " : " + selReportObj.getName()+" : Report Generation End Time is : " + new Date() );
 
         outputReportFile.deleteOnExit();
 
@@ -687,48 +447,57 @@
 
         return SUCCESS;
     }
+
+    private String getAggVal( String expression, Map<String, String> aggDeMap )
+    {
+        try
+        {
+            Pattern pattern = Pattern.compile( "(\\[\\d+\\.\\d+\\])" );
+
+            Matcher matcher = pattern.matcher( expression );
+            StringBuffer buffer = new StringBuffer();
+
+            String resultValue = "";
+
+            while ( matcher.find() )
+            {
+                String replaceString = matcher.group();
+
+                replaceString = replaceString.replaceAll( "[\\[\\]]", "" );
+
+                replaceString = aggDeMap.get( replaceString );
+                
+                if( replaceString == null )
+                {
+                    replaceString = "0";
+                }
+                
+                matcher.appendReplacement( buffer, replaceString );
+
+                resultValue = replaceString;
+            }
+
+            matcher.appendTail( buffer );
+            
+            double d = 0.0;
+            try
+            {
+                d = MathUtils.calculateExpression( buffer.toString() );
+            }
+            catch ( Exception e )
+            {
+                d = 0.0;
+                resultValue = "";
+            }
+            
+            resultValue = "" + (double) d;
+
+            return resultValue;
+        }
+        catch ( NumberFormatException ex )
+        {
+            throw new RuntimeException( "Illegal DataElement id", ex );
+        }
+    }
     
-    private void init()
-    {
-        months.put( "April", "04" );
-        months.put( "May", "05" );
-        months.put( "June", "06" );
-        months.put( "July", "07" );
-        months.put( "August", "08" );
-        months.put( "September", "09" );
-        months.put( "October", "10" );
-        months.put( "November", "11" );
-        months.put( "December", "12" );
-        months.put( "January", "01" );
-        months.put( "February", "02" );
-        months.put( "March", "03" );
-
-        monthOrder.put( "April", 1 );
-        monthOrder.put( "May", 2 );
-        monthOrder.put( "June", 3 );
-        monthOrder.put( "July", 4 );
-        monthOrder.put( "August", 5 );
-        monthOrder.put( "September", 6 );
-        monthOrder.put( "October", 7 );
-        monthOrder.put( "November", 8 );
-        monthOrder.put( "December", 9 );
-        monthOrder.put( "January", 10 );
-        monthOrder.put( "February", 11 );
-        monthOrder.put( "March", 12 );
-
-        monthArray[0] = "April";
-        monthArray[1] = "May";
-        monthArray[2] = "June";
-        monthArray[3] = "July";
-        monthArray[4] = "August";
-        monthArray[5] = "September";
-        monthArray[6] = "October";
-        monthArray[7] = "November";
-        monthArray[8] = "December";
-        monthArray[9] = "January";
-        monthArray[10] = "February";
-        monthArray[11] = "March";
-        
-    }
 }
-

=== modified file 'local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/AddReportAction.java'
--- local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/AddReportAction.java	2011-04-15 11:39:32 +0000
+++ local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/AddReportAction.java	2011-04-19 07:43:37 +0000
@@ -90,6 +90,13 @@
         this.orgunitGroupId = orgunitGroupId;
     }
     
+    private String dataSetIds;
+    
+    public void setDataSetIds( String dataSetIds )
+    {
+        this.dataSetIds = dataSetIds;
+    }
+    
     // -------------------------------------------------------------------------
     // Action
     // -------------------------------------------------------------------------
@@ -98,8 +105,9 @@
         throws Exception
     {
         PeriodType periodType = periodService.getPeriodTypeByName( frequencySelect );
-        
-        if( orgunitGroupId != null )
+
+        /*
+        if( orgunitGroupId != null && dataSetIds != null )
         {
             OrganisationUnitGroup orgUnitGroup = organisationUnitGroupService.getOrganisationUnitGroup( orgunitGroupId );
             Report_in report = new Report_in( name, reportmodel, periodType, excelname, xmlname, reporttype, orgUnitGroup );
@@ -109,9 +117,22 @@
             return SUCCESS;
 
         }
+        */
         
         Report_in report = new Report_in( name, reportmodel, periodType, excelname, xmlname, reporttype );
 
+        if( orgunitGroupId != null )
+        {
+            OrganisationUnitGroup orgUnitGroup = organisationUnitGroupService.getOrganisationUnitGroup( orgunitGroupId );
+            
+            report.setOrgunitGroup( orgUnitGroup );
+        }
+
+        if( dataSetIds != null )
+        {
+            report.setDataSetIds( dataSetIds );
+        }
+        
         reportService.addReport( report );
 
         return SUCCESS;

=== modified file 'local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/UpdateReportAction.java'
--- local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/UpdateReportAction.java	2011-04-15 11:39:32 +0000
+++ local/in/dhis-web-reports-national/src/main/java/org/hisp/dhis/reports/reportmanagement/action/UpdateReportAction.java	2011-04-19 07:43:37 +0000
@@ -97,6 +97,13 @@
         this.orgunitGroupId = orgunitGroupId;
     }
 
+    private String dataSetIds;
+    
+    public void setDataSetIds( String dataSetIds )
+    {
+        this.dataSetIds = dataSetIds;
+    }
+
     // -------------------------------------------------------------------------
     // Action
     // -------------------------------------------------------------------------
@@ -121,6 +128,11 @@
             report.setOrgunitGroup( orgUnitGroup );
         }
         
+        if( dataSetIds != null )
+        {
+            report.setDataSetIds( dataSetIds );
+        }
+        
         reportService.updateReport( report );
        
         return SUCCESS;

=== modified file 'local/in/dhis-web-reports-national/src/main/resources/META-INF/dhis/beans.xml'
--- local/in/dhis-web-reports-national/src/main/resources/META-INF/dhis/beans.xml	2011-04-15 11:40:14 +0000
+++ local/in/dhis-web-reports-national/src/main/resources/META-INF/dhis/beans.xml	2011-04-19 07:43:37 +0000
@@ -391,6 +391,8 @@
         <property name="periodService" ref="org.hisp.dhis.period.PeriodService" />
         <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService" />
         <property name="reportService" ref="org.hisp.dhis.reports.ReportService" />
+        <property name="dataSetService" ref="org.hisp.dhis.dataset.DataSetService" />
+        <property name="dataElementService" ref="org.hisp.dhis.dataelement.DataElementService" />
     </bean>
     
     <!-- Orgunitwise Progress Reports -->
@@ -408,6 +410,8 @@
         <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService" />
         <property name="reportService" ref="org.hisp.dhis.reports.ReportService" />
         <property name="periodService" ref="org.hisp.dhis.period.PeriodService" />
+        <property name="dataSetService" ref="org.hisp.dhis.dataset.DataSetService" />
+        <property name="dataElementService" ref="org.hisp.dhis.dataelement.DataElementService" />
     </bean>
     
     <!-- Meta Data Reports -->

=== modified file 'local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/addReportForm.vm'
--- local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/addReportForm.vm	2011-04-15 11:40:14 +0000
+++ local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/addReportForm.vm	2011-04-19 07:43:37 +0000
@@ -63,6 +63,10 @@
           </select>
         </td>
       </tr>
+      <tr>
+        <td><label>$i18n.getString( "dataset" )</label></td>
+        <td><input type="text" id="dataSetIds" name="dataSetIds" maxlength="100" style="width:20em"></td>
+      </tr>
           
       <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
       

=== modified file 'local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/editReportForm.vm'
--- local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/editReportForm.vm	2011-04-15 11:40:14 +0000
+++ local/in/dhis-web-reports-national/src/main/webapp/dhis-web-reports/editReportForm.vm	2011-04-19 07:43:37 +0000
@@ -64,6 +64,10 @@
               </select>
             </td>
           </tr>
+          <tr>
+            <td><label>$i18n.getString( "dataset" )</label></td>
+            <td><input type="text" id="dataSetIds" name="dataSetIds" value="$!report.dataSetIds" maxlength="100" style="width:20em"></td>
+          </tr>
               
           <tr><td>&nbsp;</td><td>&nbsp;</td></tr>