天天看點

(背景)Openbravo如何定義一個背景程序

1. 介紹

          背景程序的意思是,定義一個計劃,比如每隔10分鐘執行一次。現在我們要實作一個功能,查詢所有商品最近6個月的銷售總額。目前我們把銷售總額,放在産品的說明屬性上,做一個測試。

2. 定義計劃

        用系統管理者登陸,節點如下 :Application Dictionary || Report and Process 定義一個計劃如下截圖

(背景)Openbravo如何定義一個背景程式

      幾個字段需要注意:

      searchkey和name可以随便填,Data Access Level選擇All

      UI Pattern: 選擇Manual,因為沒有前台界面

      Backgroud:打鈎,因為我們這個是背景業務

      java Class Name:填上業務實作類,代碼見如下:

/*
 *************************************************************************
 * The contents of this file are subject to the Openbravo  Public  License
 * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
 * Version 1.1  with a permitted attribution clause; you may not  use this
 * file except in compliance with the License. You  may  obtain  a copy of
 * the License at http://www.openbravo.com/legal/license.html
 * Software distributed under the License  is  distributed  on  an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific  language  governing  rights  and  limitations
 * under the License.
 * The Original Code is Openbravo ERP.
 * The Initial Developer of the Original Code is Openbravo SLU
 * All portions are Copyright (C) 2011 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************
 */
package org.openbravo.client.application.examples;

import java.math.BigDecimal;
import java.util.Calendar;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.openbravo.dal.service.OBCriteria;
import org.openbravo.dal.service.OBDal;
import org.openbravo.model.common.order.OrderLine;
import org.openbravo.model.common.plm.Product;
import org.openbravo.scheduling.ProcessBundle;
import org.openbravo.scheduling.ProcessLogger;
import org.openbravo.service.db.DalBaseProcess;
import org.quartz.JobExecutionException;

/**
 * Shows an example of a background process implemented in java. The background
 * process needs to extend DalBaseProcess since we will be using DAL objects to
 * perform database operations
 * 
 * This class is used as an example in howtos in the Openbravo Developers Guide:
 * http://wiki.openbravo.com/wiki/Category:Developers_Guide
 * 
 * @author mtaal
 */
public class ProductRevenueCalculation extends DalBaseProcess {

    static int counter = 0;

    private ProcessLogger logger;

    // abstract method doExecute needs to be implemented and carries
    // with itself the ProcessBundle object deriving from Openbravo Quartz
    // scheduler
    public void doExecute(ProcessBundle bundle) throws Exception {

	logger = bundle.getLogger(); // this logger logs into the LOG column of
	// the AD_PROCESS_RUN database table
	BigDecimal sumAmount = new BigDecimal(0);

	logger.log("Starting background product revenue calculation. Loop "
		+ counter + "\n");

	// define time 6 months ago from today which is the timespan that our
	// calculation will consider
	Calendar timeSixMonthsAgo = Calendar.getInstance();
	timeSixMonthsAgo.add(Calendar.DAY_OF_MONTH, -180);

	try {
	    // get all products that are sold (M_PRODUCT.ISSOLD = 'Y')
	    final OBCriteria<Product> productList = OBDal.getInstance()
		    .createCriteria(Product.class);
	    productList.add(Restrictions.eq(Product.PROPERTY_SALE, true));

	    logger.log("No of products = " + productList.list().size() + "\n");

	    // loop through all products that are sold and calculate revenues
	    // for each
	    for (Product product : productList.list()) {

		sumAmount = new BigDecimal(0);

		// select lines from C_ORDERLINE table that match the product
		final Criteria orderLineList = OBDal.getInstance()
			.createCriteria(OrderLine.class).add(
				Restrictions.eq(OrderLine.PROPERTY_PRODUCT,
					product));

		// filter out lines that belong to sales (as opposed to
		// purchase) and fit within the last six months
		//
		// when you want to filter on a property of an associated entity
		// then the property of that association needs an alias, see
		// here: http://www.javalobby.org/articles/hibernatequery102/
		orderLineList.createAlias(OrderLine.PROPERTY_SALESORDER,
			"order").add(
			Restrictions.eq("order.salesTransaction", true)).add(
			Restrictions.gt("order.orderDate", timeSixMonthsAgo
				.getTime()));

		// Sum line amounts grouped by product
		orderLineList.setProjection(Projections.projectionList().add(
			Projections.sum(OrderLine.PROPERTY_LINENETAMOUNT)).add(
			Projections.groupProperty(OrderLine.PROPERTY_PRODUCT)));

		// due to grouping and sum operation there will really only be
		// one resulting record but in theory there could be more (a
		// list)
		for (Object o : orderLineList.list()) {
		    // the query returns a list of arrays (columns of the query)
		    final Object[] os = (Object[]) o;
		    sumAmount = (BigDecimal) os[0];
		    final Product p = (Product) os[1];
		    logger.log(p.getName() + " Amount " + sumAmount + "\n");
		}
		product.setDescription("6 monthRevenue = " + sumAmount);
	    }

	} catch (Exception e) {
	    // catch any possible exception and throw it as a Quartz
	    // JobExecutionException
	    throw new JobExecutionException(e.getMessage(), e);
	}
    }
}
           

      這個類主要是要繼承DalBaseProcess,并且寫一個叫做doExecute方法,這個方法裡面定義你的業務邏輯。

3. 添加規劃

      在openbravo系統裡面将剛剛定義的業務假如到一個計劃裡面,比如每隔10分鐘執行一次。

      以公司管理者登陸,在如下節點: General Setup || Process Scheduling || Process Request  打開點選新增如下所示:

(背景)Openbravo如何定義一個背景程式

     處理字段選擇:第二步定義的計劃

     timing選擇 :schedule表示我是一個計劃

     scheduling頁簽,選擇開始日期,時間,頻率 頻率間隔。我這定義的是即刻開始,5分鐘執行一次。

     點選儲存,然後點選右上角的schedule process

     我們可以在這下面還有一個節點檢視執行狀态,路徑是General Setup || Process Scheduling || Process Monitor

繼續閱讀